-
Notifications
You must be signed in to change notification settings - Fork 21
/
processor.go
1194 lines (983 loc) · 35.1 KB
/
processor.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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package worker
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/MG-RAST/AWE/lib/conf"
"github.com/MG-RAST/AWE/lib/core"
"github.com/MG-RAST/AWE/lib/core/cwl"
"github.com/MG-RAST/AWE/lib/logger"
"github.com/MG-RAST/AWE/lib/logger/event"
"github.com/MG-RAST/golib/httpclient"
//"github.com/davecgh/go-spew/spew"
//"github.com/davecgh/go-spew/spew"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/fsouza/go-dockerclient"
)
type Shock_Dockerimage_attributes struct {
Id string `bson:"id" json:"id"` // this is docker image id, not Shock id
Name string `bson:"name" json:"name"` // docker image name
Type string `bson:"type" json:"type"` // should be "dockerimage"
BaseImageId string `bson:"base_image_id" json:"base_image_id"` // could used to reference parent image
}
type WaitContainerResult struct {
Error error
Status int
}
func processor_run(control chan int) (err error) {
workunit := <-fromMover
//if the work is not succesfully parsed in last stage, pass it into the next one immediately
if workunit.State == core.WORK_STAT_ERROR || workunit.State == core.WORK_STAT_DISCARDED {
fromProcessor <- workunit
return
}
work_id := workunit.Workunit_Unique_Identifier
var work_str string
work_str, err = work_id.String()
if err != nil {
err = fmt.Errorf("() workid.String() returned: %s", err.Error())
return
}
work_state, ok, err := workmap.Get(work_id)
if err != nil {
err = fmt.Errorf("(processor_run) workmap.Get returned: %s", err.Error())
return
}
if !ok {
logger.Error("(processor) workunit.id %s not found", work_str)
return
}
if work_state == ID_DISCARDED {
workunit.SetState(core.WORK_STAT_DISCARDED, "workmap indicates that workunit has been discarded")
fromProcessor <- workunit
//release the permit lock, for work overlap inhibitted mode only
//if !conf.WORKER_OVERLAP && core.Service != "proxy" {
// <-chanPermit
//}
return
}
workmap.Set(work_id, ID_WORKER, "processor")
var envkeys []string
_ = envkeys
wants_docker := false
if workunit.Cmd.Dockerimage != "" || workunit.Cmd.DockerPull != "" {
wants_docker = true
}
if !wants_docker {
envkeys, err = SetEnv(workunit)
if err != nil {
logger.Error("(processor) SetEnv(): workid=" + work_str + ", " + err.Error())
workunit.Notes = append(workunit.Notes, "[processor#SetEnv]"+err.Error())
workunit.SetState(core.WORK_STAT_ERROR, "see notes")
//release the permit lock, for work overlap inhibitted mode only
//if !conf.WORKER_OVERLAP && core.Service != "proxy" {
// <-chanPermit
//}
return
}
}
run_start := time.Now().Unix()
var pstat *core.WorkPerf
pstat, err = RunWorkunit(workunit)
exit_status := workunit.ExitStatus
logger.Debug(1, "(processor) ExitStatus of process: %d", exit_status)
if err != nil {
logger.Error("(processor) RunWorkunit returned error , workid=%s, %s", work_str, err.Error())
workunit.Notes = append(workunit.Notes, "[processor#RunWorkunit]"+err.Error())
if exit_status == 42 {
workunit.SetState(core.WORK_STAT_FAILED_PERMANENT, "exit_status == 42") // process told us that is an error where resubmission does not make sense.
} else {
workunit.SetState(core.WORK_STAT_ERROR, "RunWorkunit failed")
}
err = nil
} else {
logger.Debug(1, "(processor) RunWorkunit() returned without error, workid=%s", work_str)
workunit.SetState(core.WORK_STAT_COMPUTED, "")
workunit.WorkPerf.MaxMemUsage = pstat.MaxMemUsage
workunit.WorkPerf.MaxMemoryTotalRss = pstat.MaxMemoryTotalRss
workunit.WorkPerf.MaxMemoryTotalSwap = pstat.MaxMemoryTotalSwap
workunit.WorkPerf.DockerPrep = pstat.DockerPrep
}
run_end := time.Now().Unix()
computetime := run_end - run_start
workunit.WorkPerf.Runtime = computetime
workunit.ComputeTime = int(computetime)
if !wants_docker {
if len(envkeys) > 0 {
UnSetEnv(envkeys)
}
}
logger.Debug(1, "(processor) sending work to datamover")
fromProcessor <- workunit
//release the permit lock, for work overlap inhibitted mode only
//if !conf.WORKER_OVERLAP && core.Service != "proxy" {
// <-chanPermit
//}
return
}
func processor(control chan int) {
fmt.Printf("(processor) launched, client=%s\n", core.Self.Id)
defer fmt.Printf("(processor) exiting...\n")
count := 0
for {
count += 1
logger.Debug(1, "(processor) for loop count=%d", count)
if Client_mode == "offline" && count > 1 {
logger.Debug(1, "(processor) leaving")
time.Sleep(time.Second)
control <- ID_WORKER
return
}
err := processor_run(control)
if err != nil {
logger.Error("(processor) processor_run returns: %s", err.Error())
}
}
control <- ID_WORKER //we are ending
}
func RunWorkunit(workunit *core.Workunit) (pstats *core.WorkPerf, err error) {
if workunit.Cmd.Dockerimage != "" || workunit.Cmd.DockerPull != "" {
pstats, err = RunWorkunitDocker(workunit)
if err != nil {
err = fmt.Errorf("(RunWorkunit) RunWorkunitDocker returned: %s", err.Error())
return
}
} else {
pstats, err = RunWorkunitDirect(workunit)
if err != nil {
err = fmt.Errorf("(RunWorkunit) RunWorkunitDirect returned: %s", err.Error())
return
}
}
if workunit.CWL_workunit != nil {
work_path, xerr := workunit.Path()
if xerr != nil {
err = xerr
return
}
stdout_file := work_path + "/" + conf.STDOUT_FILENAME
// wait for awe_stdout to be available
//for true {
// f, file_err := os.OpenFile(stdout_file, syscall.O_RDWR, 0660) // For write access.
// if file_err != nil {
// f.Close()
// break
// }
// time.Sleep(time.Second)
// fmt.Printf("waiting for %s ...\n", stdout_file)
//}
file, e := ioutil.ReadFile(stdout_file)
if e != nil {
err = fmt.Errorf("(RunWorkunit) Could read output of cwl-runner: %s", e.Error())
return
}
var tool_results interface{}
err = json.Unmarshal(file, &tool_results)
if err != nil {
err = fmt.Errorf("(RunWorkunit) Could not parse json output of cwl-runner: %s", err.Error())
fmt.Println(string(file[:]))
return
}
result_doc, xerr := cwl.NewJob_document(tool_results)
if xerr != nil {
//spew.Dump(tool_results)
err = fmt.Errorf("(RunWorkunit) NewJob_document returned: %s", xerr.Error())
return
}
//fmt.Println("CWL-runner receipt:")
//spew.Dump(result_doc)
workunit.CWL_workunit.Outputs = result_doc
}
return
}
func RunWorkunitDocker(workunit *core.Workunit) (pstats *core.WorkPerf, err error) {
pstats = new(core.WorkPerf)
pstats.MaxMemUsage = -1
pstats.MaxMemoryTotalRss = -1
pstats.MaxMemoryTotalSwap = -1
args := workunit.Cmd.ParsedArgs
//change cwd to the workunit's working directory
if err := workunit.CDworkpath(); err != nil {
err = fmt.Errorf("(RunWorkunitDocker) CDworkpath returned: %s", err.Error())
return nil, err
}
docker_preparation_start := time.Now().Unix()
commandName := workunit.Cmd.Name
use_wrapper_script := false
work_path, err := workunit.Path()
if err != nil {
err = fmt.Errorf("(RunWorkunitDocker) workunit.Path() returned: %s", err.Error())
return
}
wrapper_script_filename := "awe_workunit_wrapper.sh"
wrapper_script_filename_host := path.Join(work_path, wrapper_script_filename)
wrapper_script_filename_docker := path.Join(conf.DOCKER_WORK_DIR, wrapper_script_filename)
if len(workunit.Cmd.Cmd_script) > 0 {
use_wrapper_script = true
// create wrapper script
//conf.DOCKER_WORK_DIR
var wrapper_content_string = "#!/bin/bash\n" + strings.Join(workunit.Cmd.Cmd_script, "\n") + "\n"
logger.Debug(1, "write wrapper script: %s\n%s", wrapper_script_filename_host, strings.Join(workunit.Cmd.Cmd_script, ", "))
var wrapper_content_bytes = []byte(wrapper_content_string)
err = ioutil.WriteFile(wrapper_script_filename_host, wrapper_content_bytes, 0755) // not executable: 0644
if err != nil {
err = fmt.Errorf("(RunWorkunitDocker) error writing wrapper script, err=%s", err.Error())
return
}
}
//cmd := exec.Command(commandName, args...)
container_name := "AWE_workunit_" + DockerizeName(conf.CLIENT_NAME)
if workunit.Cmd.Dockerimage != "" {
logger.Debug(1, "using Dockerimage: %s", workunit.Cmd.Dockerimage)
} else if workunit.Cmd.DockerPull != "" {
logger.Debug(1, "using DockerPull: %s", workunit.Cmd.DockerPull)
} else {
err = fmt.Errorf("(RunWorkunitDocker) Error Dockerimage/DockerPull string empty")
return
}
dockerimage_repo := ""
dockerimage_tag := ""
if workunit.Cmd.Dockerimage != "" {
dockerimage_repo, dockerimage_tag, err = SplitDockerimageName(workunit.Cmd.Dockerimage)
if err != nil {
err = fmt.Errorf("(RunWorkunitDocker) A SplitDockerimageName returned: %s", err.Error())
return
}
}
if workunit.Cmd.DockerPull != "" {
dockerimage_repo, dockerimage_tag, err = SplitDockerimageName(workunit.Cmd.DockerPull)
if err != nil {
err = fmt.Errorf("(RunWorkunitDocker) B SplitDockerimageName returned: %s", err.Error())
return
}
}
Dockerimage_normalized := dockerimage_repo + ":" + dockerimage_tag
logger.Debug(3, "Dockerimage_normalized: %s", Dockerimage_normalized)
use_docker_api := true
if conf.DOCKER_BINARY != "API" {
use_docker_api = false
}
var client *docker.Client = nil
if use_docker_api {
logger.Debug(1, "Using docker API...")
client, err = docker.NewClient(conf.DOCKER_SOCKET)
if err != nil {
err = fmt.Errorf("(RunWorkunitDocker) error creating docker client: %s", err.Error())
return
}
} else {
logger.Debug(1, "Using docker docker binary...")
}
//imgs, _ := client.ListImages(false)
//for _, img := range imgs {
// spew.Dump(img)
//}
// delete any old AWE_container
err = RemoveOldAWEContainers(client, container_name)
if err != nil {
err = fmt.Errorf("(RunWorkunitDocker) RemoveOldAWEContainers returned: %s", err.Error())
return nil, err
}
//var node *core.ShockNode = nil
// find image in repo (e.g. extract docker image id)
dockerimage_id := ""
if workunit.Cmd.Dockerimage != "" {
node, dockerimage_download_url, xerr := findDockerImageInShock(Dockerimage_normalized, workunit.Info.DataToken)
if xerr != nil {
err = fmt.Errorf("Error getting docker url, err=%s", xerr.Error())
return
}
// TODO attr_json, _ := json.Marshal(node.Attributes) might be better
node_attr_map, ok := node.Attributes.(map[string]interface{})
if !ok {
err = fmt.Errorf("(1) could not type assert Shock_Dockerimage_attributes, Dockerimage=%s", Dockerimage_normalized)
return
}
dockerimage_id, ok = node_attr_map["id"].(string)
if !ok {
err = fmt.Errorf("(2) could not type assert Shock_Dockerimage_attributes, Dockerimage=%s", Dockerimage_normalized)
return
}
logger.Debug(3, "dockerimage_id: %s", dockerimage_id)
if dockerimage_id == "" {
err = fmt.Errorf("Id of Dockerimage=%s not found", Dockerimage_normalized)
return
}
logger.Debug(1, "using dockerimage id %s instead of name %s ", dockerimage_id, Dockerimage_normalized)
// *** find/inspect image
var image *docker.Image
image, err = InspectImage(client, dockerimage_id)
if err != nil {
logger.Debug(1, "docker image %s is not yet in local repository", Dockerimage_normalized)
err = nil
image_retrieval := "load" // TODO only load is guaraneed to workunit
//image_retrieval := "pull"
switch {
case image_retrieval == "load":
{ // for images that have been saved
logger.Debug(1, "Loading image %s", dockerimage_download_url)
err = dockerLoadImage(client, dockerimage_download_url, workunit.Info.DataToken)
if err != nil {
err = fmt.Errorf("Docker image was not correctly loaded, err=%s", err.Error())
return
}
}
case image_retrieval == "import":
{ // for containers that have been exported
logger.Debug(1, "Importing image %s", Dockerimage_normalized)
xerr := dockerImportImage(client, Dockerimage_normalized, workunit.Info.DataToken)
if xerr != nil {
err = fmt.Errorf("Docker image was not correctly imported, err=%s", xerr.Error())
return
}
}
case image_retrieval == "build":
{ // to create image from Dockerfile
logger.Debug(1, "Building image %s", Dockerimage_normalized)
xerr := dockerBuildImage(client, Dockerimage_normalized)
if xerr != nil {
err = fmt.Errorf("Docker image was not correctly built, err=%s", xerr.Error())
return
}
}
case image_retrieval == "pull":
{ // pull from docker hub
logger.Debug(1, "Pulling image %s", Dockerimage_normalized)
var buf bytes.Buffer
pio := docker.PullImageOptions{Repository: Dockerimage_normalized, OutputStream: &buf}
xerr := client.PullImage(pio, docker.AuthConfiguration{})
logger.Debug(3, "docker pull response: ", buf.String())
if xerr != nil {
err = fmt.Errorf("Docker image was not correctly pulled, err=%s", xerr.Error())
return
}
}
}
// example urls
// find image : http://shock.metagenomics.anl.gov/node/?query&docker=1&tag=wgerlach/bowtie2:2.2.0
// view node: http://shock.metagenomics.anl.gov/node/ed0a6b20-c535-40d7-92e8-754bb8b6b48f
// download http://shock.metagenomics.anl.gov/node/ed0a6b20-c535-40d7-92e8-754bb8b6b48f?download
// last test
if dockerimage_id != "" {
image, err = InspectImage(client, dockerimage_id)
if err != nil {
err = fmt.Errorf("(InspectImage) Docker image (%s , %s) was not correctly imported or built, err=%s", Dockerimage_normalized, dockerimage_id, err.Error())
return
}
} else {
image, err = InspectImage(client, Dockerimage_normalized)
if xerr != nil {
err = fmt.Errorf("(InspectImage) Docker image (%s) was not correctly imported or built, err=%s", Dockerimage_normalized, err.Error())
return
}
}
} else {
logger.Debug(1, "docker image %s is already in local repository", Dockerimage_normalized)
}
if dockerimage_id != image.ID {
err = fmt.Errorf("error: dockerimage_id != image.ID, %s != %s (%s)", dockerimage_id, image.ID, Dockerimage_normalized)
return
}
// tag image to make debugging easier
tag_opts := docker.TagImageOptions{Repo: dockerimage_repo, Tag: dockerimage_tag}
err = TagImage(client, dockerimage_id, tag_opts)
if err != nil {
logger.Error("warning: tagging of image %s with %s failed, err:", dockerimage_id, Dockerimage_normalized, err.Error())
}
} else if workunit.Cmd.DockerPull != "" {
if false {
logger.Debug(1, "Pulling image %s from Docker Hub", Dockerimage_normalized)
var buf bytes.Buffer
pio := docker.PullImageOptions{Repository: Dockerimage_normalized, OutputStream: &buf}
err = client.PullImage(pio, docker.AuthConfiguration{})
logger.Debug(3, "docker pull response: ", buf.String())
if err != nil {
err = fmt.Errorf("Docker image was not correctly pulled, err=%s", err.Error())
return
}
}
dockerimage_id = workunit.Cmd.DockerPull
}
if dockerimage_id == "" {
err = fmt.Errorf("dockerimage_id empty")
return
}
// collect environment
var docker_environment []string
docker_environment_string := "" // this is only for the debug output
for key, val := range workunit.Cmd.Environ.Public {
env_pair := key + "=" + val
docker_environment = append(docker_environment, env_pair)
docker_environment_string += " --env=" + env_pair
}
if workunit.Cmd.HasPrivateEnv {
logger.Debug(3, "HasPrivateEnv true")
private_envs, err := FetchPrivateEnvByWorkId(workunit.Id)
if err != nil {
return nil, err
}
for key, val := range private_envs {
env_pair := key + "=" + val
docker_environment = append(docker_environment, env_pair)
docker_environment_string += " -e " + env_pair
}
} else {
logger.Debug(3, "HasPrivateEnv false")
}
stdout_file := path.Join(conf.DOCKER_WORK_DIR, conf.STDOUT_FILENAME)
stderr_file := path.Join(conf.DOCKER_WORK_DIR, conf.STDERR_FILENAME)
pipe_output := fmt.Sprintf(" 2> %s 1> %s", stderr_file, stdout_file)
bash_command := ""
if use_wrapper_script {
//bash_command = fmt.Sprint("/bin/bash", " ", wrapper_script_filename_docker, " ", pipe_output) // bash for wrapper script
bash_command = fmt.Sprint(wrapper_script_filename_docker, " ", pipe_output)
} else {
bash_command = fmt.Sprintf("%s %s %s", commandName, strings.Join(args, " "), pipe_output)
//bash_command = fmt.Sprintf("uname -a %s", pipe_output)
var wrapper_content_string = "#!/bin/bash\n" + bash_command + "\n"
logger.Debug(1, "write wrapper script: %s\n%s", wrapper_script_filename_host, bash_command)
var wrapper_content_bytes = []byte(wrapper_content_string)
err = ioutil.WriteFile(wrapper_script_filename_host, wrapper_content_bytes, 0755) // not executable: 0644
if err != nil {
err = fmt.Errorf("error writing wrapper script, err=%s", err.Error())
return
}
//time.Sleep(time.Second * 3000)
bash_command = wrapper_script_filename_docker
}
//bash_command = fmt.Sprintf("sleep 3 ; uname -a ; ./awe_qc.pl -format my_file_format.075 -out_prefix my_job_id.075 -assembled 1 -filter_options my_filter_options -proc 8 -input Ebin3.fa; uname -a 2> %s 1> %s", conf.STDERR_FILENAME, conf.STDOUT_FILENAME)
logger.Debug(1, fmt.Sprint("bash_command: ", bash_command))
// example: "/bin/bash", "-c", "bowtie2 -h 2> awe_stderr.txt 1> awe_stdout.txt"
//container_cmd := []string{"/bin/bash", "-c", bash_command} // TODO remove bash if possible, but is needed for piping
container_cmd := []string{bash_command}
//var empty_struct struct{}
bindstr_workdir := work_path + "/:" + conf.DOCKER_WORK_DIR
logger.Debug(1, "bindstr_workdir: "+bindstr_workdir)
var bindarray = []string{}
// only mount predata if it is actually used
//fake_predata := ""
bindstr_predata := ""
volume_str := ""
if len(workunit.Predata) > 0 {
predata_directory := path.Join(conf.DATA_PATH, "predata")
bindstr_predata = predata_directory + "/:" + conf.DOCKER_WORKUNIT_PREDATA_DIR + ":ro"
bindarray = []string{bindstr_workdir, bindstr_predata} //old version
volume_str = "--volume=" + bindstr_workdir + " --volume=" + bindstr_predata
} else {
bindarray = []string{bindstr_workdir}
volume_str = "--volume=" + bindstr_workdir
}
logger.Debug(1, "volume_str: "+volume_str)
// version for docker command line
docker_commandline_create := []string{
// "-t" would be required if I want to attach to the container later, check again documentation if needed
"--name=" + container_name,
"--workdir=" + conf.DOCKER_WORK_DIR,
volume_str, // for workdir and optionally predata
}
if docker_environment_string != "" {
docker_commandline_create = append(docker_commandline_create, docker_environment_string)
}
// version for docker API
config := docker.Config{Image: dockerimage_id,
WorkingDir: conf.DOCKER_WORK_DIR,
AttachStdout: true,
AttachStderr: true,
AttachStdin: false,
Cmd: container_cmd,
Volumes: map[string]struct{}{conf.DOCKER_WORK_DIR: struct{}{}}, // old version
//Volumes: map[string]struct{}{bindstr_workdir: struct{}{}},
Env: docker_environment,
}
if len(workunit.Predata) > 0 {
config.Volumes[bindstr_predata] = struct{}{}
}
docker_commandline_create = append(docker_commandline_create, dockerimage_id) //
docker_commandline_create = append(docker_commandline_create, container_cmd...) // argument to the "docker create" command
opts := docker.CreateContainerOptions{Name: container_name, Config: &config, HostConfig: &docker.HostConfig{Binds: bindarray}}
// note: docker binary mounts on creation, while docker API mounts on start of container
container_id := ""
// *** create container
logger.Debug(1, "creating docker container %s from image %s (%s)", container_name, Dockerimage_normalized, dockerimage_id)
if client != nil {
container_obj, xerr := client.CreateContainer(opts)
if xerr == nil {
container_id = container_obj.ID
} else {
err = fmt.Errorf("error creating container, err=%s", xerr.Error())
return
}
} else {
container_id, err = CreateContainer(docker_commandline_create)
if err != nil {
err = fmt.Errorf("error creating container, err=%s", err.Error())
return
}
}
logger.Debug(3, "Container created.")
if container_id == "" {
err = fmt.Errorf("error creating container, container_id is empty")
return
}
logger.Debug(1, "created docker container with ID: %s", container_id)
// *** start container
fake_docker_cmd := "sudo docker run -t -i --name test " + volume_str + " " + docker_environment_string + " --workdir=" + conf.DOCKER_WORK_DIR + " " + dockerimage_id + " " + strings.Join(container_cmd, " ")
logger.Debug(1, "fake_docker_cmd ("+Dockerimage_normalized+"): "+fake_docker_cmd)
logger.Debug(1, "starting docker container...")
docker_preparation_end := time.Now().Unix()
pstats.DockerPrep = docker_preparation_end - docker_preparation_start
logger.Debug(1, "DockerPrep time in seconds: %d", pstats.DockerPrep)
if client != nil {
//err = client.StartContainer(container_id, &docker.HostConfig{Binds: bindarray}) // weired, seems to be needed
err = client.StartContainer(container_id, nil)
//err = client.StartContainer(container_id, &docker.HostConfig{})
} else {
err = StartContainer(container_id, volume_str)
}
if err != nil {
err = fmt.Errorf("error starting container, id=%s, err=%s", container_id, err.Error())
return
}
logger.Debug(3, "Container started.")
defer func(container_id string) {
// *** clean up
// ** kill container
var err_kill error
if client != nil {
err_kill = client.KillContainer(docker.KillContainerOptions{ID: container_id})
} else {
err_kill = KillContainer(container_id)
}
if err_kill != nil {
logger.Debug(3, "(deferred func) (clean-up after running container) could not kill container id=%s, err=%s", container_id, err_kill.Error())
}
}(container_id)
if client != nil {
cont, err := client.InspectContainer(container_id)
if err != nil {
logger.Error("error inspecting container=%s, err=%s", container_id, err.Error())
}
logger.Debug(3, "Container status: %s", cont.State.Status)
inspect_filename := path.Join(work_path, "container_inspect.json")
b_inspect, _ := json.MarshalIndent(cont, "", " ")
err = ioutil.WriteFile(inspect_filename, b_inspect, 0666)
if err != nil {
fmt.Errorf("error writing inspect file for container=%s, err=%s", container_id, err.Error())
} else {
logger.Debug(1, "wrote %s for container %s", inspect_filename, container_id)
}
}
// wait for container to finish
done := make(chan WaitContainerResult)
go func() {
//time.Sleep(300 * time.Second)
var errwait error
var status int = -1
if client != nil {
status, errwait = client.WaitContainer(container_id)
} else {
status, errwait = WaitContainer(container_id)
}
cresult := WaitContainerResult{errwait, status}
done <- cresult // inform main function
if conf.MEM_CHECK_INTERVAL != 0 {
done <- cresult // inform memory checker
}
}()
var MaxMem int64 = -1
var max_memory_total_rss int64 = -1
var max_memory_total_swap int64 = -1
memory_stat_filename := ""
if conf.MEM_CHECK_INTERVAL != 0 {
// documentation: https://docs.docker.com/articles/runmetrics/
// e.g. ubuntu: /sys/fs/cgroup/memory/docker/[ID]/memory.stat
// coreos: /sys/fs/cgroup/memory/system.slice/docker-[ID].scope/memory.stat
memory_stat_filename = strings.Replace(conf.CGROUP_MEMORY_DOCKER_DIR, "[ID]", container_id, -1)
if _, err := os.Stat(memory_stat_filename); os.IsNotExist(err) {
logger.Error("warning: memory measurement requested, but no memory.stat found: %s" + memory_stat_filename)
memory_stat_filename = ""
}
}
if conf.MEM_CHECK_INTERVAL != 0 && memory_stat_filename != "" {
go func() { // memory checker
for {
select {
case cresult := <-done:
workunit.ExitStatus = cresult.Status
if cresult.Error != nil {
logger.Error("channel done returned error: " + cresult.Error.Error())
}
return
default:
}
var memory_total_rss int64 = -1
var memory_total_swap int64 = -1
memory_stat_file, err_mem := os.Open(memory_stat_filename)
if err_mem != nil {
logger.Error("warning: error opening memory_stat_file file:" + err_mem.Error())
time.Sleep(conf.MEM_CHECK_INTERVAL)
continue
}
// Closes the file when we leave the scope of the current function,
// this makes sure we never forget to close the file if the
// function can exit in multiple places.
memory_stat_file_scanner := bufio.NewScanner(memory_stat_file)
memory_total_rss_read := false
memory_total_swap_read := false
// scanner.Scan() advances to the next token returning false if an error was encountered
for memory_stat_file_scanner.Scan() {
line := memory_stat_file_scanner.Text()
if strings.HasPrefix(line, "total_rss ") { // TODO what is total_rss_huge
//logger.Debug(1, fmt.Sprint("inspecting container with memory line=", line))
memory_total_rss, err = strconv.ParseInt(strings.TrimPrefix(line, "total_rss "), 10, 64)
if err != nil {
memory_total_rss = -1
}
memory_total_rss_read = true
} else if strings.HasPrefix(line, "total_swap ") { // TODO what is total_rss_huge
//logger.Debug(1, fmt.Sprint("inspecting container with memory line=", line))
memory_total_swap, err = strconv.ParseInt(strings.TrimPrefix(line, "total_swap "), 10, 64)
if err != nil {
memory_total_swap = -1
}
memory_total_swap_read = true
} else {
continue
}
if memory_total_rss_read && memory_total_swap_read { // we found all information we need, leave the loop
break
}
}
// When finished scanning if any error other than io.EOF occured
// it will be returned by scanner.Err().
if err := memory_stat_file_scanner.Err(); err != nil {
logger.Error("warning: could no read memory usage from cgroups=%s", memory_stat_file_scanner.Err())
//err = nil
} else {
// RSS maxium
if memory_total_rss >= 0 && memory_total_rss > max_memory_total_rss {
max_memory_total_rss = memory_total_rss
}
// SWAP maximum
if memory_total_swap >= 0 && memory_total_swap > max_memory_total_swap {
max_memory_total_swap = memory_total_swap
}
// RSS+SWAP maximum
if memory_total_rss >= 0 && memory_total_swap >= 0 {
memory_combined := memory_total_rss + memory_total_swap
if memory_combined > MaxMem {
MaxMem = memory_combined
}
}
logger.Debug(1, fmt.Sprintf("memory: rss=%d, swap=%d, max_rss=%d max_swap=%d max_combined=%d",
memory_total_rss, memory_total_swap, max_memory_total_rss, max_memory_total_swap, MaxMem))
}
memory_stat_file.Close() // defer does not work in for loop !
//time.Sleep(5 * time.Second)
time.Sleep(conf.MEM_CHECK_INTERVAL)
}
}()
} else {
logger.Debug(1, "memory checking disabled")
}
cresult := WaitContainerResult{nil, -1}
select {
case <-chankill:
logger.Debug(1, "chankill, try to kill container %s... ", container_id)
if client != nil {
err = client.KillContainer(docker.KillContainerOptions{ID: container_id})
} else {
err = KillContainer(container_id)
}
if err != nil {
return nil, errors.New(fmt.Sprintf("(chankill) error killing container id=%s, err=%s", container_id, err.Error()))
}
<-done // allow goroutine to exit
return nil, errors.New("process killed as requested from chankill")
case cresult = <-done:
workunit.ExitStatus = cresult.Status
logger.Debug(3, "(1)docker wait returned with status %d", cresult.Status)
if cresult.Error != nil {
return nil, fmt.Errorf("dockerWait=%s, status=%d, err=%s", commandName, cresult.Status, cresult.Error.Error())
}
if cresult.Status != 0 {
logger.Debug(3, "WaitContainer returned non-zero status=%d", cresult.Status)
return nil, fmt.Errorf("error WaitContainer returned non-zero status=%d", cresult.Status)
}
}
logger.Debug(1, fmt.Sprint("pstats.MaxMemUsage: ", pstats.MaxMemUsage))
pstats.MaxMemUsage = MaxMem
pstats.MaxMemoryTotalRss = max_memory_total_rss
pstats.MaxMemoryTotalSwap = max_memory_total_swap
logger.Debug(1, fmt.Sprint("pstats.MaxMemUsage: ", pstats.MaxMemUsage))
return
}
func RunWorkunitDirect(workunit *core.Workunit) (pstats *core.WorkPerf, err error) {
var args []string
if len(workunit.Cmd.ArgsArray) > 0 {
args = workunit.Cmd.ArgsArray
} else {
args = workunit.Cmd.ParsedArgs
}
//change cwd to the workunit's working directory
if err := workunit.CDworkpath(); err != nil {
return nil, err
}
commandName := workunit.Cmd.Name
if commandName == "" {
err = fmt.Errorf("error: command name is empty")
return
}
cmd := exec.Command(commandName, args...)
msg := fmt.Sprintf("(RunWorkunitDirect) worker: start cmd=%s, args=%v", commandName, args)
//fmt.Println(msg)
logger.Debug(1, msg)
logger.Event(event.WORK_START, "workid="+workunit.Id,
"cmd="+commandName,
fmt.Sprintf("args=%v", args))
var stdout, stderr io.ReadCloser
if conf.PRINT_APP_MSG {
stdout, err = cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err = cmd.StderrPipe()
if err != nil {
return nil, err
}
}
work_path, xerr := workunit.Path()
if xerr != nil {
err = xerr
return
}
logger.Debug(3, "(RunWorkunitDirect) Using workpath: %s", work_path)
stdoutFilePath := fmt.Sprintf("%s/%s", work_path, conf.STDOUT_FILENAME)
stderrFilePath := fmt.Sprintf("%s/%s", work_path, conf.STDERR_FILENAME)
outfile, err := os.Create(stdoutFilePath)
defer outfile.Close()
errfile, err := os.Create(stderrFilePath)
defer errfile.Close()
out_writer := bufio.NewWriter(outfile)
defer out_writer.Flush()
err_writer := bufio.NewWriter(errfile)
defer err_writer.Flush()
if conf.PRINT_APP_MSG {
go io.Copy(out_writer, stdout)
go io.Copy(err_writer, stderr)
}
if err = cmd.Start(); err != nil {
err = fmt.Errorf("start_cmd=%s, err=%s", commandName, err.Error())
return
}
var MaxMem uint64 = 0
MaxMemChan := make(chan uint64)
done := make(chan error)
memcheck_done := make(chan bool)
go func() {
done <- cmd.Wait()
memcheck_done <- true
}()
mem_check_interval_here := conf.MEM_CHECK_INTERVAL
if mem_check_interval_here == 0 {
mem_check_interval_here = 10 * time.Second
}
go func() {
mstats := new(runtime.MemStats)
runtime.ReadMemStats(mstats)
_MaxMem := mstats.Alloc
MaxMemChan <- mstats.Alloc
time.Sleep(2 * time.Second)
for {
select {
default:
mstats := new(runtime.MemStats)
runtime.ReadMemStats(mstats)
if mstats.Alloc > _MaxMem {
MaxMemChan <- mstats.Alloc
}
time.Sleep(mem_check_interval_here)
case <-memcheck_done:
return
}
}