-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
620 lines (548 loc) · 17.9 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/*
BOOSTER-WEB: Web interface to BOOSTER (https://github.com/evolbioinfo/booster)
Alternative method to compute bootstrap branch supports in large trees.
Copyright (C) 2017 BOOSTER-WEB dev team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package server
import (
"bufio"
"compress/gzip"
"errors"
"fmt"
"github.com/nu7hatch/gouuid"
"github.com/russross/blackfriday"
"html/template"
goio "io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/evolbioinfo/booster-web/config"
"github.com/evolbioinfo/booster-web/database"
"github.com/evolbioinfo/booster-web/model"
"github.com/evolbioinfo/booster-web/notification"
"github.com/evolbioinfo/booster-web/processor"
"github.com/evolbioinfo/booster-web/static"
"github.com/evolbioinfo/booster-web/templates"
"github.com/fredericlemoine/goalign/align"
"github.com/fredericlemoine/goalign/io/fasta"
"github.com/fredericlemoine/goalign/io/phylip"
"github.com/fredericlemoine/goalign/io/utils"
"github.com/fredericlemoine/gotree/io/newick"
tutils "github.com/fredericlemoine/gotree/io/utils"
"github.com/fredericlemoine/gotree/tree"
)
const (
DATABASE_TYPE_DEFAULT = "memory"
HTTP_PORT_DEFAULT = 8080 // Port 8080
)
var templatePath string
var templatesMap map[string]*template.Template
var db database.BoosterwebDB
var proc processor.Processor
var uuids chan string // channel of uuids generated by a go routine
var logfile *os.File = nil
var emailNotifier notification.Notifier
var galaxyprocessor bool // if the processor is a galaxyprocessor
var emailnotification bool
// The config should contain following keys:
// runners.queuesize: Max number of jobs in the queue (default 10)
// runners.nbrunners: Max number of parallel running jobs (default 1)
// runners.timeout for each running job in Seconds (default 0=unlimited)
// runners.jobthreads : Number of cpus per bootstrap runner
// database.type: mysql or memory (default memory)
// database.user: user to connect to mysql if type is mysql
// database.host: host to connect to mysql if type is mysql
// database.port: port to connect to mysql if type is mysql
// database.pass: pass to connect to mysql if type is mysql
// database.dbname: name of db to connect to mysql if type is mysql
// logging.logfile : path to log file: stdout, stderr or any file name (default stderr)
func InitServer(cfg config.Provider) {
initLog(cfg)
log.Print("Starting booster-web")
initUUIDGenerator()
initDB(cfg)
initEmailNotification(cfg)
initProcessor(cfg)
initCleanKill()
initLogin(cfg)
templatePath = "webapp" + string(os.PathSeparator) + "templates" + string(os.PathSeparator)
formtpl, err1 := templates.Asset(templatePath + "inputform.html")
if err1 != nil {
log.Fatal(err1)
}
errtpl, err2 := templates.Asset(templatePath + "error.html")
if err2 != nil {
log.Fatal(err2)
}
viewtpl, err3 := templates.Asset(templatePath + "view.html")
if err3 != nil {
log.Fatal(err3)
}
indextpl, err4 := templates.Asset(templatePath + "index.html")
if err4 != nil {
log.Fatal(err4)
}
layouttpl, err5 := templates.Asset(templatePath + "layout.html")
if err5 != nil {
log.Fatal(err5)
}
helptpl, err6 := templates.Asset(templatePath + "help.html")
if err6 != nil {
log.Fatal(err6)
}
logintpl, err7 := templates.Asset(templatePath + "login.html")
if err7 != nil {
log.Fatal(err7)
}
templatesMap = make(map[string]*template.Template)
if t, err := template.New("inputform").Parse(string(layouttpl) + string(formtpl)); err != nil {
log.Fatal(err)
} else {
templatesMap["inputform"] = t
}
if t, err := template.New("error").Parse(string(layouttpl) + string(errtpl)); err != nil {
log.Fatal(err)
} else {
templatesMap["error"] = t
}
if t, err := template.New("view").Parse(string(layouttpl) + string(viewtpl)); err != nil {
log.Fatal(err)
} else {
templatesMap["view"] = t
}
if t, err := template.New("index").Parse(string(layouttpl) + string(indextpl)); err != nil {
log.Fatal(err)
} else {
templatesMap["index"] = t
}
if t, err := template.New("help").Funcs(template.FuncMap{"markDown": markDowner}).Parse(string(layouttpl) + string(helptpl)); err != nil {
log.Fatal(err)
} else {
templatesMap["help"] = t
}
if t, err := template.New("login").Parse(string(layouttpl) + string(logintpl)); err != nil {
log.Fatal(err)
} else {
templatesMap["login"] = t
}
/* HTML handlers */
http.HandleFunc("/new/", validateHtml(newHandler)) /* Handler for input form */
http.HandleFunc("/run", validateHtml(runHandler)) /* Handler for running a new analysis */
http.HandleFunc("/help", validateHtml(helpHandler)) /* Handler for the help page */
http.HandleFunc("/view/", validateHtml(makeHandler(viewHandler))) /* Handler for viewing analysis results */
http.HandleFunc("/itol/", validateHtml(makeRawNormHandler(itolHandler))) /* Handler for uploading tree to itol */
http.HandleFunc("/", validateHtml(indexHandler)) /* Home Page*/
http.HandleFunc("/login", loginHandler) /* Handler for login */
http.HandleFunc("/settoken", setToken) /* Set token in cookie via form post */
http.HandleFunc("/gettoken", getToken) /* get token via api using json post data */
http.HandleFunc("/logout", validateHtml(logout)) /* Handler for logout */
/* Api handlers */
http.HandleFunc("/api/analysis/", validateApi(makeApiAnalysisHandler(apiAnalysisHandler))) /* Handler for returning an analysis */
http.HandleFunc("/api/image/", validateApi(makeApiImageHandler(apiImageHandler))) /* Handler for returning a tree image */
http.HandleFunc("/api/randrunname", validateApi(makeApiHandler(apiRandNameGeneratorHandler)))
/* Static files handlers : js, css, etc. */
http.Handle("/static/", http.FileServer(static.AssetFS()))
//http.Handle("/", http.RedirectHandler("/new/", http.StatusFound))
port := cfg.GetInt("http.port")
if port == 0 {
port = HTTP_PORT_DEFAULT
}
log.Print(fmt.Sprintf("HTTP port: %d", port))
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}
func initProcessor(cfg config.Provider) {
nbrunners := cfg.GetInt("runners.nbrunners")
queuesize := cfg.GetInt("runners.queuesize")
timeout := cfg.GetInt("runners.timeout")
memlimit := cfg.GetInt("runners.memlimit")
jobthreads := cfg.GetInt("runners.jobthreads")
galaxykey := cfg.GetString("galaxy.key")
galaxyurl := cfg.GetString("galaxy.url")
proctype := cfg.GetString("runners.type")
requestattempts := cfg.GetInt("galaxy.requestattempts")
boosterid := cfg.GetString("galaxy.tools.booster")
phymlid := cfg.GetString("galaxy.tools.phyml")
fasttreeid := cfg.GetString("galaxy.tools.fasttree")
if requestattempts == 0 {
requestattempts = 1
}
galaxyprocessor = false
switch proctype {
case "galaxy":
if galaxyurl == "" {
log.Fatal("galaxyurl must be provided in configuration file when type=galaxy")
}
if galaxykey == "" {
log.Fatal("galaxykey must be provided in configuration file when type=galaxy")
}
if boosterid == "" {
log.Fatal("booster tool id must be provided in configuration file when type=galaxy")
}
if phymlid == "" {
log.Fatal("phyml-sms tool id must be provided in configuration file when type=galaxy")
}
if fasttreeid == "" {
log.Fatal("fasttree tool id must be provided in configuration file when type=galaxy")
}
galproc := &processor.GalaxyProcessor{}
galaxyprocessor = true
galproc.InitProcessor(galaxyurl, galaxykey, boosterid, phymlid, fasttreeid, requestattempts, db, emailNotifier, queuesize, timeout, memlimit)
proc = galproc
case "local", "":
// Local or not set
locproc := &processor.LocalProcessor{}
locproc.InitProcessor(nbrunners, queuesize, timeout, jobthreads, db, emailNotifier)
proc = locproc
default:
log.Fatal(errors.New("No processor named " + proctype))
}
}
func initUUIDGenerator() {
uuids = make(chan string, 100)
// The uuid generator will put uuids in the channel
// When a new analysis is launched, one uuid will be taken
// from the channel
go func() {
for {
u, err := uuid.NewV4()
if err != nil {
log.Print(err)
} else {
uuids <- u.String()
}
}
}()
}
func initCleanKill() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
go func() {
for sig := range c {
log.Print(sig)
//proc.CancelAnalyses()
if err := db.Disconnect(); err != nil {
log.Print(err)
}
os.Exit(1)
}
}()
}
func initDB(cfg config.Provider) {
dbtype := cfg.GetString("database.type")
switch dbtype {
case "memory":
db = database.NewMemoryBoosterWebDB()
case "mysql":
user := cfg.GetString("database.user")
host := cfg.GetString("database.host")
pass := cfg.GetString("database.pass")
dbname := cfg.GetString("database.dbname")
port := cfg.GetInt("database.port")
db = database.NewMySQLBoosterwebDB(user, pass, host, dbname, port)
if err := db.Connect(); err != nil {
log.Fatal(err)
}
default:
db = database.NewMemoryBoosterWebDB()
log.Print("Database type not valid, using default: " + DATABASE_TYPE_DEFAULT)
}
if err := db.InitDatabase(); err != nil {
log.Fatal(err)
}
initOldAnalysisCleaner(cfg)
}
func initOldAnalysisCleaner(cfg config.Provider) {
// Will delete old analyses from database
// once a day
agelimit := cfg.GetInt("database.keepold")
if agelimit > 0 {
go func() {
for {
if err := db.DeleteOldAnalyses(agelimit); err != nil {
log.Print("Error while deleting old analyses: " + err.Error())
}
time.Sleep(24 * time.Hour)
}
}()
}
}
func initLog(cfg config.Provider) {
logf := cfg.GetString("logging.logfile")
switch logf {
case "stderr":
log.Print("Log file: stderr")
logfile = os.Stderr
case "stdout":
log.Print("Log file: stdout")
logfile = os.Stdout
case "":
log.Print("Log file: stderr")
logfile = os.Stderr
default:
log.Print("Log file: " + logf)
var err error
logfile, err = os.OpenFile(logf, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
}
log.SetOutput(logfile)
}
func initLogin(cfg config.Provider) {
user := cfg.GetString("authentication.user")
pass := cfg.GetString("authentication.password")
if user != "" && pass != "" {
Authent = true
Username = user
Password = pass
}
}
func initEmailNotification(cfg config.Provider) {
emailnotification = false
if cfg.GetBool("notification.activated") {
smtp := cfg.GetString("notification.smtp")
port := cfg.GetInt("notification.port")
user := cfg.GetString("notification.user")
pass := cfg.GetString("notification.pass")
sender := cfg.GetString("notification.sender")
resultpage := cfg.GetString("notification.resultpage")
emailNotifier = notification.NewEmailNotifier(smtp, port, user, pass, sender, resultpage)
emailnotification = true
} else {
emailNotifier = notification.NewNullNotifier()
}
}
// Creates a new analysis
//
// workflow is sed only if sefseqs is defined : full phylogenetic workflow
func newAnalysis(refalign multipart.File, refalignheader *multipart.FileHeader,
reffile multipart.File, refheader *multipart.FileHeader,
bootfile multipart.File, bootheader *multipart.FileHeader,
email, runname string, nbootrep int, workflow string) (a *model.Analysis, err error) {
var uuid string
var dir string
var seqalignfile, treefile, boottreefile string
uuid = <-uuids
a = model.NewAnalysis()
a.Id = uuid
a.EMail = email
a.RunName = runname
a.NbootRep = nbootrep
a.Status = model.STATUS_PENDING
a.Nboot = 0
a.StartPending = time.Now().Format(time.RFC1123)
/* tmp analysis folder */
if dir, err = ioutil.TempDir("", uuid); err != nil {
log.Print(err)
return
}
// Reference sequences if given
if refalignheader != nil {
// We parse it while detecting automaticall the format
var r *bufio.Reader
var al align.Alignment
if r, err = utils.GetReaderFromReader(utils.GzipExtension(refalignheader.Filename), refalign); err != nil {
log.Print(err)
return
}
if al, _, err = utils.ParseAlignmentAuto(r, false); err != nil {
log.Print(err)
return
}
// Write alignment in fasta or in phylip depending on the workflow to launch: phyml or fasttree
if seqalignfile, err = writeAlign(al, dir, refalignheader, workflow); err != nil {
log.Print(err)
return
}
a.Alignfile = fasta.WriteAlignment(al)
a.AlignAlphabet = al.Alphabet()
a.AlignNbSeq = al.NbSequences()
a.AlignLength = al.Length()
// Given workflow to launch does not exist
if a.Workflow, err = model.WorkflowConst(workflow); err != nil {
log.Print(err)
return
}
log.Print(fmt.Sprintf("New %s (%d boot) + booster analysis submited | id=%s | ", workflow, a.NbootRep, a.Id))
} else {
log.Print(fmt.Sprintf("New booster analysis submited | id=%s | ", a.Id))
if treefile, err = copyTreeFile(dir, reffile, refheader); err != nil {
err = errors.New("Reference tree : Newick format error (" + err.Error() + ")")
log.Print(err)
return nil, err
}
if boottreefile, err = copyTreeFile(dir, bootfile, bootheader); err != nil {
err = errors.New("Bootstrap trees : Newick format error (" + err.Error() + ")")
log.Print(err)
return nil, err
}
if err = testSameTips(treefile, boottreefile); err != nil {
log.Print(err)
err = errors.New("Reference and bootstrap trees do not have the same tip names")
log.Print(err)
return nil, err
}
}
a.SeqAlign = seqalignfile
a.Reffile = treefile
a.Bootfile = boottreefile
err = proc.LaunchAnalysis(a)
return
}
func getAnalysis(id string) (a *model.Analysis, err error) {
a, err = db.GetAnalysis(id)
return
}
func markDowner(args ...interface{}) template.HTML {
s := blackfriday.MarkdownCommon([]byte(fmt.Sprintf("%s", args...)))
return template.HTML(s)
}
func copyFile(tmpdir string, infile multipart.File, infileheader *multipart.FileHeader) (fpath string, err error) {
var f *os.File
if infileheader != nil {
fpath = filepath.Join(tmpdir, infileheader.Filename)
if f, err = os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE, 0666); err != nil {
log.Print(err)
} else {
goio.Copy(f, infile)
}
defer f.Close()
} else {
err = errors.New("File to copy does not exist")
log.Print(err)
}
return
}
/*
Clean tip names (remove spaces before and after tip names) and copy the tree file
returns an error if the tree file is not in newick format
*/
func copyTreeFile(tmpdir string, infile multipart.File, infileheader *multipart.FileHeader) (fpath string, err error) {
var treereader *bufio.Reader
var gzreader *gzip.Reader
var t tree.Trees
var trees <-chan tree.Trees
var f *os.File
if infileheader != nil {
/* Read trees */
/* File reader (plain text or gzip) */
if strings.HasSuffix(infileheader.Filename, ".gz") {
if gzreader, err = gzip.NewReader(f); err != nil {
return
}
treereader = bufio.NewReader(gzreader)
} else {
treereader = bufio.NewReader(infile)
}
trees = tutils.ReadMultiTrees(treereader, tutils.FORMAT_NEWICK)
/* Open output file */
fpath = filepath.Join(tmpdir, infileheader.Filename)
if f, err = os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE, 0666); err != nil {
log.Print(err)
return
}
for t = range trees {
if t.Err != nil {
err = t.Err
return
}
// Clean tip names if needed
for _, t := range t.Tree.Tips() {
t.SetName(strings.TrimSpace(t.Name()))
}
// Write the to the output file */
f.WriteString(t.Tree.Newick() + "\n")
}
defer f.Close()
} else {
err = errors.New("File to copy does not exist")
log.Print(err)
}
return
}
// Write alignment in fasta or in phylip depending on the workflow to launch: phyml or fasttree
func writeAlign(al align.Alignment, tmpdir string, infileheader *multipart.FileHeader, workflow string) (fpath string, err error) {
var f *os.File
var wf int
if wf, err = model.WorkflowConst(workflow); err != nil {
log.Print(err)
return
}
if infileheader != nil {
fpath = filepath.Join(tmpdir, infileheader.Filename)
if f, err = os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE, 0666); err != nil {
log.Print(err)
} else {
if wf == model.WORKFLOW_PHYML_SMS {
f.WriteString(phylip.WriteAlignment(al, false))
} else {
f.WriteString(fasta.WriteAlignment(al))
}
}
defer f.Close()
} else {
err = errors.New("File to copy does not exist")
log.Print(err)
}
return
}
// Parses the two newick files in input and returns an error if the set of
// tips are different between tree in ref and all tres in boot.
//
// ref is considered as a unique tree file
// boot is a multi newick file (bootstrap trees for example)
func testSameTips(ref, boot string) (err error) {
var treereader *bufio.Reader
var treefile goio.Closer
var reftree *tree.Tree
var boottree tree.Trees
var trees <-chan tree.Trees
if treefile, treereader, err = utils.GetReader(ref); err != nil {
return
}
if reftree, err = newick.NewParser(treereader).Parse(); err != nil {
return
}
treefile.Close()
/* Read bootstrap trees */
/* File reader (plain text or gzip) */
if treefile, treereader, err = utils.GetReader(boot); err != nil {
return
}
defer treefile.Close()
trees = tutils.ReadMultiTrees(treereader, tutils.FORMAT_NEWICK)
reftree.UpdateTipIndex()
for boottree = range trees {
if boottree.Err != nil {
err = boottree.Err
return
}
boottree.Tree.UpdateTipIndex()
if err = reftree.CompareTipIndexes(boottree.Tree); err != nil {
return
}
}
return
}