d2073ad9c05f8900bc55dd8780e30bb6ca8cc699
[lightning.git] / slice.go
1 // Copyright (C) The Lightning Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package lightning
6
7 import (
8         "bufio"
9         "encoding/gob"
10         "errors"
11         "flag"
12         "fmt"
13         "io"
14         "net/http"
15         _ "net/http/pprof"
16         "os"
17         "path/filepath"
18         "runtime"
19         "strings"
20         "sync"
21         "sync/atomic"
22
23         "git.arvados.org/arvados.git/sdk/go/arvados"
24         "github.com/klauspost/pgzip"
25         log "github.com/sirupsen/logrus"
26 )
27
28 type slicecmd struct{}
29
30 func (cmd *slicecmd) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
31         var err error
32         defer func() {
33                 if err != nil {
34                         fmt.Fprintf(stderr, "%s\n", err)
35                 }
36         }()
37         flags := flag.NewFlagSet("", flag.ContinueOnError)
38         flags.SetOutput(stderr)
39         pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
40         runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
41         projectUUID := flags.String("project", "", "project `UUID` for output data")
42         priority := flags.Int("priority", 500, "container request priority")
43         outputDir := flags.String("output-dir", "./out", "output `directory`")
44         tagsPerFile := flags.Int("tags-per-file", 50000, "tags per file (nfiles will be ~10M÷x)")
45         err = flags.Parse(args)
46         if err == flag.ErrHelp {
47                 err = nil
48                 return 0
49         } else if err != nil {
50                 return 2
51         }
52         inputDirs := flags.Args()
53         if len(inputDirs) == 0 {
54                 err = errors.New("no input dirs specified")
55                 return 2
56         }
57
58         if *pprof != "" {
59                 go func() {
60                         log.Println(http.ListenAndServe(*pprof, nil))
61                 }()
62         }
63
64         if !*runlocal {
65                 runner := arvadosContainerRunner{
66                         Name:        "lightning slice",
67                         Client:      arvados.NewClientFromEnv(),
68                         ProjectUUID: *projectUUID,
69                         RAM:         500000000000,
70                         VCPUs:       64,
71                         Priority:    *priority,
72                         KeepCache:   2,
73                         APIAccess:   true,
74                 }
75                 for i := range inputDirs {
76                         err = runner.TranslatePaths(&inputDirs[i])
77                         if err != nil {
78                                 return 1
79                         }
80                 }
81                 runner.Args = append([]string{"slice", "-local=true",
82                         "-pprof", ":6060",
83                         "-output-dir", "/mnt/output",
84                 }, inputDirs...)
85                 var output string
86                 output, err = runner.Run()
87                 if err != nil {
88                         return 1
89                 }
90                 fmt.Fprintln(stdout, output)
91                 return 0
92         }
93
94         err = Slice(*tagsPerFile, *outputDir, inputDirs)
95         if err != nil {
96                 return 1
97         }
98         return 0
99 }
100
101 // Read tags+tiles+genomes from srcdir, write to dstdir with (up to)
102 // the specified number of tags per file.
103 func Slice(tagsPerFile int, dstdir string, srcdirs []string) error {
104         var infiles []string
105         for _, srcdir := range srcdirs {
106                 files, err := allGobFiles(srcdir)
107                 if err != nil {
108                         return err
109                 }
110                 infiles = append(infiles, files...)
111         }
112         // dirNamespace[dir] is an int in [0,len(dirNamespace)), used below to
113         // namespace variant numbers from different dirs.
114         dirNamespace := map[string]tileVariantID{}
115         for _, path := range infiles {
116                 dir, _ := filepath.Split(path)
117                 if _, ok := dirNamespace[dir]; !ok {
118                         dirNamespace[dir] = tileVariantID(len(dirNamespace))
119                 }
120         }
121         namespaces := tileVariantID(len(dirNamespace))
122
123         var (
124                 tagset     [][]byte
125                 tagsetOnce sync.Once
126                 fs         []*os.File
127                 bufws      []*bufio.Writer
128                 gzws       []*pgzip.Writer
129                 encs       []*gob.Encoder
130
131                 countTileVariants int64
132                 countGenomes      int64
133                 countReferences   int64
134         )
135
136         throttle := throttle{Max: runtime.GOMAXPROCS(0)}
137         for _, infile := range infiles {
138                 infile := infile
139                 throttle.Acquire()
140                 go func() {
141                         defer throttle.Release()
142                         f, err := open(infile)
143                         if err != nil {
144                                 throttle.Report(err)
145                                 return
146                         }
147                         defer f.Close()
148                         dir, _ := filepath.Split(infile)
149                         namespace := dirNamespace[dir]
150                         log.Printf("reading %s (namespace %d)", infile, namespace)
151                         err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
152                                 if err := throttle.Err(); err != nil {
153                                         return err
154                                 }
155                                 if len(ent.TagSet) > 0 {
156                                         tagsetOnce.Do(func() {
157                                                 tagset = ent.TagSet
158                                                 var err error
159                                                 fs, bufws, gzws, encs, err = openOutFiles(dstdir, len(ent.TagSet), tagsPerFile)
160                                                 if err != nil {
161                                                         throttle.Report(err)
162                                                         return
163                                                 }
164                                                 for _, enc := range encs {
165                                                         err = enc.Encode(LibraryEntry{TagSet: tagset})
166                                                         if err != nil {
167                                                                 throttle.Report(err)
168                                                                 return
169                                                         }
170                                                 }
171                                         })
172                                 }
173                                 if err := throttle.Err(); err != nil {
174                                         return err
175                                 }
176                                 atomic.AddInt64(&countTileVariants, int64(len(ent.TileVariants)))
177                                 for _, tv := range ent.TileVariants {
178                                         tv.Variant = tv.Variant*namespaces + namespace
179                                         fileno := 0
180                                         if !tv.Ref {
181                                                 fileno = int(tv.Tag) / tagsPerFile
182                                         }
183                                         err := encs[fileno].Encode(LibraryEntry{
184                                                 TileVariants: []TileVariant{tv},
185                                         })
186                                         if err != nil {
187                                                 return err
188                                         }
189                                 }
190                                 // Here, each output file gets a
191                                 // CompactGenome entry for each
192                                 // genome, even if there are no
193                                 // variants in the relevant range.
194                                 // Easier for downstream code.
195                                 atomic.AddInt64(&countGenomes, int64(len(ent.CompactGenomes)))
196                                 for _, cg := range ent.CompactGenomes {
197                                         for i, v := range cg.Variants {
198                                                 if v > 0 {
199                                                         cg.Variants[i] = v*namespaces + namespace
200                                                 }
201                                         }
202                                         for i, enc := range encs {
203                                                 start := i * tagsPerFile
204                                                 end := start + tagsPerFile
205                                                 if max := len(cg.Variants)/2 + int(cg.StartTag); end > max {
206                                                         end = max
207                                                 }
208                                                 if start < int(cg.StartTag) {
209                                                         start = int(cg.StartTag)
210                                                 }
211                                                 var variants []tileVariantID
212                                                 if start < end {
213                                                         variants = cg.Variants[(start-int(cg.StartTag))*2 : (end-int(cg.StartTag))*2]
214                                                 }
215                                                 err := enc.Encode(LibraryEntry{CompactGenomes: []CompactGenome{{
216                                                         Name:     cg.Name,
217                                                         Variants: variants,
218                                                         StartTag: tagID(start),
219                                                         EndTag:   tagID(start + tagsPerFile),
220                                                 }}})
221                                                 if err != nil {
222                                                         return err
223                                                 }
224                                         }
225                                 }
226                                 // Write all ref seqs to the first
227                                 // slice. Easier for downstream code.
228                                 atomic.AddInt64(&countReferences, int64(len(ent.CompactSequences)))
229                                 if len(ent.CompactSequences) > 0 {
230                                         for _, cs := range ent.CompactSequences {
231                                                 for _, tseq := range cs.TileSequences {
232                                                         for i, libref := range tseq {
233                                                                 tseq[i].Variant = libref.Variant*namespaces + namespace
234                                                         }
235                                                 }
236                                         }
237                                         err := encs[0].Encode(LibraryEntry{CompactSequences: ent.CompactSequences})
238                                         if err != nil {
239                                                 return err
240                                         }
241                                 }
242                                 return nil
243                         })
244                         throttle.Report(err)
245                 }()
246         }
247         throttle.Wait()
248         if throttle.Err() != nil {
249                 closeOutFiles(fs, bufws, gzws, encs)
250                 return throttle.Err()
251         }
252         defer log.Printf("Total %d tile variants, %d genomes, %d reference sequences", countTileVariants, countGenomes, countReferences)
253         return closeOutFiles(fs, bufws, gzws, encs)
254 }
255
256 func openOutFiles(dstdir string, tags, tagsPerFile int) (fs []*os.File, bufws []*bufio.Writer, gzws []*pgzip.Writer, encs []*gob.Encoder, err error) {
257         nfiles := (tags + tagsPerFile - 1) / tagsPerFile
258         fs = make([]*os.File, nfiles)
259         bufws = make([]*bufio.Writer, nfiles)
260         gzws = make([]*pgzip.Writer, nfiles)
261         encs = make([]*gob.Encoder, nfiles)
262         for i := 0; i*tagsPerFile < tags; i++ {
263                 fs[i], err = os.Create(dstdir + fmt.Sprintf("/library%04d.gob.gz", i))
264                 if err != nil {
265                         return
266                 }
267                 bufws[i] = bufio.NewWriterSize(fs[i], 1<<26)
268                 gzws[i] = pgzip.NewWriter(bufws[i])
269                 encs[i] = gob.NewEncoder(gzws[i])
270         }
271         return
272 }
273
274 func closeOutFiles(fs []*os.File, bufws []*bufio.Writer, gzws []*pgzip.Writer, encs []*gob.Encoder) error {
275         var firstErr error
276         for _, gzw := range gzws {
277                 if gzw != nil {
278                         err := gzw.Close()
279                         if err != nil && firstErr == nil {
280                                 firstErr = err
281                         }
282                 }
283         }
284         for _, bufw := range bufws {
285                 if bufw != nil {
286                         err := bufw.Flush()
287                         if err != nil && firstErr == nil {
288                                 firstErr = err
289                         }
290                 }
291         }
292         for _, f := range fs {
293                 if f != nil {
294                         err := f.Close()
295                         if err != nil && firstErr == nil {
296                                 firstErr = err
297                         }
298                 }
299         }
300         return firstErr
301 }