24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 log "github.com/sirupsen/logrus"
28 type importer struct {
38 func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
42 fmt.Fprintf(stderr, "%s\n", err)
45 flags := flag.NewFlagSet("", flag.ContinueOnError)
46 flags.SetOutput(stderr)
47 flags.StringVar(&cmd.tagLibraryFile, "tag-library", "", "tag library fasta `file`")
48 flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
49 flags.StringVar(&cmd.outputFile, "o", "-", "output `file`")
50 flags.StringVar(&cmd.projectUUID, "project", "", "project `UUID` for output data")
51 flags.BoolVar(&cmd.runLocal, "local", false, "run on local host (default: run in an arvados container)")
52 flags.BoolVar(&cmd.skipOOO, "skip-ooo", false, "skip out-of-order tags")
53 priority := flags.Int("priority", 500, "container request priority")
54 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
55 err = flags.Parse(args)
56 if err == flag.ErrHelp {
59 } else if err != nil {
61 } else if cmd.tagLibraryFile == "" {
62 fmt.Fprintln(os.Stderr, "cannot import without -tag-library argument")
64 } else if flags.NArg() == 0 {
71 log.Println(http.ListenAndServe(*pprof, nil))
76 runner := arvadosContainerRunner{
77 Name: "lightning import",
78 Client: arvados.NewClientFromEnv(),
79 ProjectUUID: cmd.projectUUID,
84 err = runner.TranslatePaths(&cmd.tagLibraryFile, &cmd.refFile, &cmd.outputFile)
88 inputs := flags.Args()
89 for i := range inputs {
90 err = runner.TranslatePaths(&inputs[i])
95 if cmd.outputFile == "-" {
96 cmd.outputFile = "/mnt/output/library.gob"
98 // Not yet implemented, but this should write
99 // the collection to an existing collection,
100 // possibly even an in-place update.
101 err = errors.New("cannot specify output file in container mode: not implemented")
104 runner.Args = append([]string{"import", "-local=true", fmt.Sprintf("-skip-ooo=%v", cmd.skipOOO), "-tag-library", cmd.tagLibraryFile, "-ref", cmd.refFile, "-o", cmd.outputFile}, inputs...)
106 output, err = runner.Run()
110 fmt.Fprintln(stdout, output+"/library.gob")
114 infiles, err := listInputFiles(flags.Args())
119 tilelib, err := cmd.loadTileLibrary()
124 for range time.Tick(10 * time.Minute) {
125 log.Printf("tilelib.Len() == %d", tilelib.Len())
129 var output io.WriteCloser
130 if cmd.outputFile == "-" {
131 output = nopCloser{stdout}
133 output, err = os.OpenFile(cmd.outputFile, os.O_CREATE|os.O_WRONLY, 0777)
139 bufw := bufio.NewWriter(output)
140 cmd.encoder = gob.NewEncoder(bufw)
142 err = cmd.tileInputs(tilelib, infiles)
157 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, error) {
158 var input io.ReadCloser
159 input, err := os.Open(infile)
164 if strings.HasSuffix(infile, ".gz") {
165 input, err = gzip.NewReader(input)
171 return tilelib.TileFasta(infile, input)
174 func (cmd *importer) loadTileLibrary() (*tileLibrary, error) {
175 log.Printf("tag library %s load starting", cmd.tagLibraryFile)
176 f, err := os.Open(cmd.tagLibraryFile)
181 var rdr io.ReadCloser = f
182 if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
183 rdr, err = gzip.NewReader(f)
185 return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
189 var taglib tagLibrary
190 err = taglib.Load(rdr)
194 if taglib.Len() < 1 {
195 return nil, fmt.Errorf("cannot tile: tag library is empty")
197 log.Printf("tag library %s load done", cmd.tagLibraryFile)
198 return &tileLibrary{taglib: &taglib, skipOOO: cmd.skipOOO}, nil
201 func listInputFiles(paths []string) (files []string, err error) {
202 for _, path := range paths {
203 if fi, err := os.Stat(path); err != nil {
204 return nil, fmt.Errorf("%s: stat failed: %s", path, err)
205 } else if !fi.IsDir() {
206 if !strings.HasSuffix(path, ".2.fasta") || strings.HasSuffix(path, ".2.fasta.gz") {
207 files = append(files, path)
211 d, err := os.Open(path)
213 return nil, fmt.Errorf("%s: open failed: %s", path, err)
216 names, err := d.Readdirnames(0)
218 return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
221 for _, name := range names {
222 if strings.HasSuffix(name, ".vcf") || strings.HasSuffix(name, ".vcf.gz") {
223 files = append(files, filepath.Join(path, name))
224 } else if strings.HasSuffix(name, ".1.fasta") || strings.HasSuffix(name, ".1.fasta.gz") {
225 files = append(files, filepath.Join(path, name))
230 for _, file := range files {
231 if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
233 } else if _, err := os.Stat(file + ".csi"); err == nil {
235 } else if _, err = os.Stat(file + ".tbi"); err == nil {
238 return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
244 func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
245 starttime := time.Now()
246 errs := make(chan error, 1)
247 todo := make(chan func() error, len(infiles)*2)
248 var encodeJobs sync.WaitGroup
249 for _, infile := range infiles {
251 var phases sync.WaitGroup
253 variants := make([][]tileVariantID, 2)
254 if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
255 todo <- func() error {
257 log.Printf("%s starting", infile)
258 defer log.Printf("%s done", infile)
259 tseqs, err := cmd.tileFasta(tilelib, infile)
260 variants[0] = tseqs.Variants()
263 infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
264 todo <- func() error {
266 log.Printf("%s starting", infile2)
267 defer log.Printf("%s done", infile2)
268 tseqs, err := cmd.tileFasta(tilelib, infile2)
269 variants[1] = tseqs.Variants()
273 for phase := 0; phase < 2; phase++ {
275 todo <- func() error {
277 log.Printf("%s phase %d starting", infile, phase+1)
278 defer log.Printf("%s phase %d done", infile, phase+1)
279 tseqs, err := cmd.tileGVCF(tilelib, infile, phase)
280 variants[phase] = tseqs.Variants()
287 defer encodeJobs.Done()
292 ntags := len(variants[0])
293 if ntags < len(variants[1]) {
294 ntags = len(variants[1])
296 flat := make([]tileVariantID, ntags*2)
297 for i := 0; i < ntags; i++ {
298 for hap := 0; hap < 2; hap++ {
299 if i < len(variants[hap]) {
300 flat[i*2+hap] = variants[hap][i]
304 err := cmd.encoder.Encode(LibraryEntry{
305 CompactGenomes: []CompactGenome{{Name: infile, Variants: flat}},
316 var tileJobs sync.WaitGroup
318 for i := 0; i < runtime.NumCPU()*9/8+1; i++ {
320 atomic.AddInt64(&running, 1)
322 defer tileJobs.Done()
323 defer atomic.AddInt64(&running, -1)
324 for fn := range todo {
335 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
336 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
337 eta := time.Now().Add(ttl)
338 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
348 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, err error) {
349 if cmd.refFile == "" {
350 err = errors.New("cannot import vcf: reference data (-ref) not specified")
353 args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
354 indexsuffix := ".tbi"
355 if _, err := os.Stat(infile + ".csi"); err == nil {
358 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
359 args = append([]string{
360 "docker", "run", "--rm",
362 "--volume=" + infile + ":" + infile + ":ro",
363 "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
364 "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
368 consensus := exec.Command(args[0], args[1:]...)
369 consensus.Stderr = os.Stderr
370 stdout, err := consensus.StdoutPipe()
375 err = consensus.Start()
379 defer consensus.Wait()
380 tileseq, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout)
388 err = consensus.Wait()
390 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)