Skip to content
Snippets Groups Projects
job.go 2.1 KiB
Newer Older
  • Learn to ignore specific revisions
  • import (
    	"fmt"
    	"github.com/pkg/errors"
    	"io"
    	"log"
    	"sync"
    )
    
    type Job struct {
    	// Function to call on Collect. This is the function
    	// that will (1) update the state of this job, (2)
    	// do the actual importing, (3) write to the Job-internal
    	// log and eventually (4) finish either with success
    	// or in failure.
    	collectfunc func(self *Job, c *Collector) error
    
    	// Global lock for all following members.
    	mu sync.Mutex
    
    	// Unique identifier of this job.
    	id JobId
    
    	// The state the job is currently in.
    	state JobState
    
    	// When state is set to Failed, contains the reason
    	// for this failure.
    	failure error
    
    	// Recorded logs for this job.
    	logged concurrentbuffer
    }
    
    // Return the unique identifier of this job.
    func (bj *Job) Id() JobId {
    	bj.mu.Lock()
    	defer bj.mu.Unlock()
    
    	return bj.id
    }
    
    // Return the current state of this job.
    func (bj *Job) State() JobState {
    	bj.mu.Lock()
    	defer bj.mu.Unlock()
    
    	return bj.state
    }
    
    // When State is Failed, return the error that caused
    // the failure. When State is not failed, this method
    // always returns nil.
    func (bj *Job) Error() error {
    	bj.mu.Lock()
    	defer bj.mu.Unlock()
    
    	return bj.failure
    }
    
    // This is a synchronous operation that might take a long
    // time. Instead of invoking Collect directly, you should
    // create a Collector and Submit this job to it.
    func (bj *Job) Collect(c *Collector) error {
    	if bj.collectfunc == nil {
    		return errors.New("collectfunc not set on Job")
    	}
    
    	bj.collectfunc(bj, c)
    	return nil
    }
    
    // Write to the log associated with this Job. The log message
    // will be output with the standard logger as well as recorded
    // to the buffer accessible with Job.Logs().
    func (bj *Job) Log(v ...interface{}) {
    	log.Output(2, fmt.Sprint(v...))
    }
    
    // Write a formatted string to the log associated with this
    // Job. The log message will be output with the standard
    // logger as well as recorded to the buffer accessible with
    // Job.Logs().
    func (bj *Job) Logf(format string, v ...interface{}) {
    	log.Output(2, fmt.Sprintf(format, v...))
    }
    
    // Return the log stream of this job.
    func (bj *Job) Logs() io.Reader {
    	panic("not yet implemented")