github.com/Cloud-Foundations/Dominator@v0.3.4/lib/filegen/file.go (about)

     1  package filegen
     2  
     3  import (
     4  	"errors"
     5  	"io"
     6  	"time"
     7  
     8  	"github.com/Cloud-Foundations/Dominator/lib/fsutil"
     9  	"github.com/Cloud-Foundations/Dominator/lib/hash"
    10  	"github.com/Cloud-Foundations/Dominator/lib/log"
    11  	"github.com/Cloud-Foundations/Dominator/lib/mdb"
    12  	"github.com/Cloud-Foundations/Dominator/lib/objectserver/memory"
    13  )
    14  
    15  type fileGenerator struct {
    16  	objectServer    *memory.ObjectServer
    17  	logger          log.Logger
    18  	hash            *hash.Hash
    19  	length          uint64
    20  	notifierChannel chan<- string
    21  }
    22  
    23  func (m *Manager) registerFileForPath(pathname string, sourceFile string) {
    24  	readCloserChannel := fsutil.WatchFile(sourceFile, m.logger)
    25  	fgen := &fileGenerator{
    26  		objectServer: m.objectServer,
    27  		logger:       m.logger}
    28  	fgen.notifierChannel = m.registerHashGeneratorForPath(pathname, fgen)
    29  	go fgen.handleReaders(readCloserChannel)
    30  
    31  }
    32  
    33  func (fgen *fileGenerator) generate(machine mdb.Machine, logger log.Logger) (
    34  	hash.Hash, uint64, time.Time, error) {
    35  	if fgen.hash == nil {
    36  		return hash.Hash{}, 0, time.Time{}, errors.New("no hash yet")
    37  	}
    38  	return *fgen.hash, fgen.length, time.Time{}, nil
    39  }
    40  
    41  func (fgen *fileGenerator) handleReaders(
    42  	readCloserChannel <-chan io.ReadCloser) {
    43  	for readCloser := range readCloserChannel {
    44  		hashVal, _, err := fgen.objectServer.AddObject(readCloser, 0, nil)
    45  		readCloser.Close()
    46  		if err != nil {
    47  			fgen.logger.Println(err)
    48  			continue
    49  		}
    50  		fgen.hash = &hashVal
    51  		hashes := make([]hash.Hash, 1)
    52  		hashes[0] = hashVal
    53  		lengths, err := fgen.objectServer.CheckObjects(hashes)
    54  		if err != nil {
    55  			fgen.logger.Println(err)
    56  			continue
    57  		}
    58  		fgen.length = lengths[0]
    59  		fgen.notifierChannel <- ""
    60  	}
    61  }