24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 log "github.com/sirupsen/logrus"
28 type importer struct {
37 func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
41 fmt.Fprintf(stderr, "%s\n", err)
44 flags := flag.NewFlagSet("", flag.ContinueOnError)
45 flags.SetOutput(stderr)
46 flags.StringVar(&cmd.tagLibraryFile, "tag-library", "", "tag library fasta `file`")
47 flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
48 flags.StringVar(&cmd.outputFile, "o", "-", "output `file`")
49 flags.StringVar(&cmd.projectUUID, "project", "", "project `UUID` for output data")
50 flags.BoolVar(&cmd.runLocal, "local", false, "run on local host (default: run in an arvados container)")
51 priority := flags.Int("priority", 500, "container request priority")
52 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
53 err = flags.Parse(args)
54 if err == flag.ErrHelp {
57 } else if err != nil {
59 } else if cmd.tagLibraryFile == "" {
60 fmt.Fprintln(os.Stderr, "cannot import without -tag-library argument")
62 } else if flags.NArg() == 0 {
69 log.Println(http.ListenAndServe(*pprof, nil))
74 runner := arvadosContainerRunner{
75 Name: "lightning import",
76 Client: arvados.NewClientFromEnv(),
77 ProjectUUID: cmd.projectUUID,
82 err = runner.TranslatePaths(&cmd.tagLibraryFile, &cmd.refFile, &cmd.outputFile)
86 inputs := flags.Args()
87 for i := range inputs {
88 err = runner.TranslatePaths(&inputs[i])
93 if cmd.outputFile == "-" {
94 cmd.outputFile = "/mnt/output/library.gob"
96 // Not yet implemented, but this should write
97 // the collection to an existing collection,
98 // possibly even an in-place update.
99 err = errors.New("cannot specify output file in container mode: not implemented")
102 runner.Args = append([]string{"import", "-local=true", "-tag-library", cmd.tagLibraryFile, "-ref", cmd.refFile, "-o", cmd.outputFile}, inputs...)
104 output, err = runner.Run()
108 fmt.Fprintln(stdout, output+"/library.gob")
112 infiles, err := listInputFiles(flags.Args())
117 tilelib, err := cmd.loadTileLibrary()
122 for range time.Tick(10 * time.Minute) {
123 log.Printf("tilelib.Len() == %d", tilelib.Len())
127 var output io.WriteCloser
128 if cmd.outputFile == "-" {
129 output = nopCloser{stdout}
131 output, err = os.OpenFile(cmd.outputFile, os.O_CREATE|os.O_WRONLY, 0777)
137 bufw := bufio.NewWriter(output)
138 cmd.encoder = gob.NewEncoder(bufw)
140 err = cmd.tileInputs(tilelib, infiles)
155 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, error) {
156 var input io.ReadCloser
157 input, err := os.Open(infile)
162 if strings.HasSuffix(infile, ".gz") {
163 input, err = gzip.NewReader(input)
169 return tilelib.TileFasta(infile, input)
172 func (cmd *importer) loadTileLibrary() (*tileLibrary, error) {
173 log.Printf("tag library %s load starting", cmd.tagLibraryFile)
174 f, err := os.Open(cmd.tagLibraryFile)
179 var rdr io.ReadCloser = f
180 if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
181 rdr, err = gzip.NewReader(f)
183 return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
187 var taglib tagLibrary
188 err = taglib.Load(rdr)
192 if taglib.Len() < 1 {
193 return nil, fmt.Errorf("cannot tile: tag library is empty")
195 log.Printf("tag library %s load done", cmd.tagLibraryFile)
196 return &tileLibrary{taglib: &taglib}, nil
199 func listInputFiles(paths []string) (files []string, err error) {
200 for _, path := range paths {
201 if fi, err := os.Stat(path); err != nil {
202 return nil, fmt.Errorf("%s: stat failed: %s", path, err)
203 } else if !fi.IsDir() {
204 if !strings.HasSuffix(path, ".2.fasta") || strings.HasSuffix(path, ".2.fasta.gz") {
205 files = append(files, path)
209 d, err := os.Open(path)
211 return nil, fmt.Errorf("%s: open failed: %s", path, err)
214 names, err := d.Readdirnames(0)
216 return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
219 for _, name := range names {
220 if strings.HasSuffix(name, ".vcf") || strings.HasSuffix(name, ".vcf.gz") {
221 files = append(files, filepath.Join(path, name))
222 } else if strings.HasSuffix(name, ".1.fasta") || strings.HasSuffix(name, ".1.fasta.gz") {
223 files = append(files, filepath.Join(path, name))
228 for _, file := range files {
229 if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
231 } else if _, err := os.Stat(file + ".csi"); err == nil {
233 } else if _, err = os.Stat(file + ".tbi"); err == nil {
236 return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
242 func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
243 starttime := time.Now()
244 errs := make(chan error, 1)
245 todo := make(chan func() error, len(infiles)*2)
246 var encodeJobs sync.WaitGroup
247 for _, infile := range infiles {
249 var phases sync.WaitGroup
251 variants := make([][]tileVariantID, 2)
252 if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
253 todo <- func() error {
255 log.Printf("%s starting", infile)
256 defer log.Printf("%s done", infile)
257 tseqs, err := cmd.tileFasta(tilelib, infile)
258 variants[0] = tseqs.Variants()
261 infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
262 todo <- func() error {
264 log.Printf("%s starting", infile2)
265 defer log.Printf("%s done", infile2)
266 tseqs, err := cmd.tileFasta(tilelib, infile2)
267 variants[1] = tseqs.Variants()
271 for phase := 0; phase < 2; phase++ {
273 todo <- func() error {
275 log.Printf("%s phase %d starting", infile, phase+1)
276 defer log.Printf("%s phase %d done", infile, phase+1)
277 tseqs, err := cmd.tileGVCF(tilelib, infile, phase)
278 variants[phase] = tseqs.Variants()
285 defer encodeJobs.Done()
290 ntags := len(variants[0])
291 if ntags < len(variants[1]) {
292 ntags = len(variants[1])
294 flat := make([]tileVariantID, ntags*2)
295 for i := 0; i < ntags; i++ {
296 flat[i*2] = variants[0][i]
297 flat[i*2+1] = variants[1][i]
299 err := cmd.encoder.Encode(LibraryEntry{
300 CompactGenomes: []CompactGenome{{Name: infile, Variants: flat}},
311 var tileJobs sync.WaitGroup
313 for i := 0; i < runtime.NumCPU()*9/8+1; i++ {
315 atomic.AddInt64(&running, 1)
317 defer tileJobs.Done()
318 defer atomic.AddInt64(&running, -1)
319 for fn := range todo {
330 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
331 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
332 eta := time.Now().Add(ttl)
333 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
343 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, err error) {
344 if cmd.refFile == "" {
345 err = errors.New("cannot import vcf: reference data (-ref) not specified")
348 args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
349 indexsuffix := ".tbi"
350 if _, err := os.Stat(infile + ".csi"); err == nil {
353 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
354 args = append([]string{
355 "docker", "run", "--rm",
357 "--volume=" + infile + ":" + infile + ":ro",
358 "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
359 "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
363 consensus := exec.Command(args[0], args[1:]...)
364 consensus.Stderr = os.Stderr
365 stdout, err := consensus.StdoutPipe()
370 err = consensus.Start()
374 defer consensus.Wait()
375 tileseq, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout)
383 err = consensus.Wait()
385 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)