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