3 // Originally based on sdk/go/crunchrunner/upload.go
5 // Unlike the original, which iterates over a directory tree and uploads each
6 // file sequentially, this version supports opening and writing multiple files
7 // in a collection simultaneously.
9 // Eventually this should move into the Arvados Go SDK for a more comprehensive
10 // implementation of Collections.
17 "git.curoverse.com/arvados.git/sdk/go/keepclient"
18 "git.curoverse.com/arvados.git/sdk/go/manifest"
27 // Block is a data block in a manifest stream
33 // CollectionFileWriter is a Writer that permits writing to a file in a Keep Collection.
34 type CollectionFileWriter struct {
36 *manifest.ManifestStream
45 // Write to a file in a keep collection
46 func (m *CollectionFileWriter) Write(p []byte) (int, error) {
47 n, err := m.ReadFrom(bytes.NewReader(p))
51 // ReadFrom a Reader and write to the Keep collection file.
52 func (m *CollectionFileWriter) ReadFrom(r io.Reader) (n int64, err error) {
58 m.Block = &Block{make([]byte, keepclient.BLOCKSIZE), 0}
60 count, err = r.Read(m.Block.data[m.Block.offset:])
62 m.Block.offset += int64(count)
63 if m.Block.offset == keepclient.BLOCKSIZE {
69 m.length += uint64(total)
77 // Close stops writing a file and adds it to the parent manifest.
78 func (m *CollectionFileWriter) Close() error {
79 m.ManifestStream.FileStreamSegments = append(m.ManifestStream.FileStreamSegments,
80 manifest.FileStreamSegment{m.offset, m.length, m.fn})
84 func (m *CollectionFileWriter) NewFile(fn string) {
90 func (m *CollectionFileWriter) goUpload(workers chan struct{}) {
95 uploader := m.uploader
97 for block := range uploader {
99 m.ManifestStream.Blocks = append(m.ManifestStream.Blocks, "")
100 blockIndex := len(m.ManifestStream.Blocks) - 1
103 workers <- struct{}{} // wait for an available worker slot
106 go func(block *Block, blockIndex int) {
107 hash := fmt.Sprintf("%x", md5.Sum(block.data[0:block.offset]))
108 signedHash, _, err := m.IKeepClient.PutHB(hash, block.data[0:block.offset])
113 errors = append(errors, err)
115 m.ManifestStream.Blocks[blockIndex] = signedHash
127 // CollectionWriter implements creating new Keep collections by opening files
128 // and writing to them.
129 type CollectionWriter struct {
132 Streams []*CollectionFileWriter
133 workers chan struct{}
137 // Open a new file for writing in the Keep collection.
138 func (m *CollectionWriter) Open(path string) io.WriteCloser {
142 i := strings.Index(path, "/")
144 dir = "./" + path[0:i]
151 fw := &CollectionFileWriter{
153 &manifest.ManifestStream{StreamName: dir},
163 if m.workers == nil {
164 if m.MaxWriters < 1 {
167 m.workers = make(chan struct{}, m.MaxWriters)
170 go fw.goUpload(m.workers)
172 m.Streams = append(m.Streams, fw)
177 // Finish writing the collection, wait for all blocks to complete uploading.
178 func (m *CollectionWriter) Finish() error {
183 for _, stream := range m.Streams {
184 if stream.uploader == nil {
187 if stream.Block != nil {
188 stream.uploader <- stream.Block
190 close(stream.uploader)
191 stream.uploader = nil
193 errors := <-stream.finish
197 for _, r := range errors {
198 errstring = fmt.Sprintf("%v%v\n", errstring, r.Error())
202 return errors.New(errstring)
207 // ManifestText returns the manifest text of the collection. Calls Finish()
208 // first to ensure that all blocks are written and that signed locators and
210 func (m *CollectionWriter) ManifestText() (mt string, err error) {
220 for _, v := range m.Streams {
221 if len(v.FileStreamSegments) == 0 {
228 k = strings.Replace(k, " ", "\\040", -1)
229 k = strings.Replace(k, "\n", "", -1)
230 buf.WriteString("./" + k)
232 if len(v.Blocks) > 0 {
233 for _, b := range v.Blocks {
238 buf.WriteString(" d41d8cd98f00b204e9800998ecf8427e+0")
240 for _, f := range v.FileStreamSegments {
242 name := strings.Replace(f.Name, " ", "\\040", -1)
243 name = strings.Replace(name, "\n", "", -1)
244 buf.WriteString(fmt.Sprintf("%v:%v:%v", f.SegPos, f.SegLen, name))
246 buf.WriteString("\n")
248 return buf.String(), nil
251 type WalkUpload struct {
255 streamMap map[string]*CollectionFileWriter
257 workers chan struct{}
261 // WalkFunc walks a directory tree, uploads each file found and adds it to the
263 func (m *WalkUpload) WalkFunc(path string, info os.FileInfo, err error) error {
270 if len(path) > (len(m.stripPrefix) + len(info.Name()) + 1) {
271 dir = path[len(m.stripPrefix)+1 : (len(path) - len(info.Name()) - 1)]
277 fn := path[(len(path) - len(info.Name())):]
279 if m.streamMap[dir] == nil {
280 m.streamMap[dir] = &CollectionFileWriter{
282 &manifest.ManifestStream{StreamName: dir},
291 if m.workers == nil {
292 if m.MaxWriters < 1 {
295 m.workers = make(chan struct{}, m.MaxWriters)
299 go m.streamMap[dir].goUpload(m.workers)
302 fileWriter := m.streamMap[dir]
304 // Reset the CollectionFileWriter for a new file
305 fileWriter.NewFile(fn)
307 file, err := os.Open(path)
313 m.status.Printf("Uploading %v/%v (%v bytes)", dir, fn, info.Size())
315 _, err = io.Copy(fileWriter, file)
320 // Commits the current file. Legal to call this repeatedly.
326 func (cw *CollectionWriter) WriteTree(root string, status *log.Logger) (manifest string, err error) {
327 streamMap := make(map[string]*CollectionFileWriter)
328 wu := &WalkUpload{0, cw.IKeepClient, root, streamMap, status, nil, sync.Mutex{}}
329 err = filepath.Walk(root, wu.WalkFunc)
336 for _, st := range streamMap {
337 cw.Streams = append(cw.Streams, st)
341 return cw.ManifestText()