-
Notifications
You must be signed in to change notification settings - Fork 21
/
servermgr.go
6074 lines (5050 loc) · 167 KB
/
servermgr.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 core
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/MG-RAST/AWE/lib/conf"
"github.com/MG-RAST/AWE/lib/core/cwl"
e "github.com/MG-RAST/AWE/lib/errors"
"github.com/MG-RAST/AWE/lib/logger"
"github.com/MG-RAST/AWE/lib/logger/event"
"github.com/MG-RAST/AWE/lib/user"
shock "github.com/MG-RAST/go-shock-client"
"github.com/davecgh/go-spew/spew"
"github.com/robertkrimen/otto"
"gopkg.in/mgo.v2/bson"
)
type jQueueShow struct {
Active map[string]*JobPerf `bson:"active" json:"active"`
Suspend map[string]bool `bson:"suspend" json:"suspend"`
}
// ServerMgr _
type ServerMgr struct {
CQMgr
queueLock sync.Mutex //only update one at a time
lastUpdate time.Time
lastUpdateLock sync.RWMutex
TaskMap TaskMap
ajLock sync.RWMutex
actJobs map[string]*JobPerf
}
// NewServerMgr _
func NewServerMgr() *ServerMgr {
return &ServerMgr{
CQMgr: CQMgr{
clientMap: *NewClientMap(),
workQueue: NewWorkQueue(),
suspendQueue: false,
coReq: make(chan CheckoutRequest, conf.COREQ_LENGTH), // number of clients that wait in queue to get a workunit. If queue is full, other client will be rejected and have to come back later again
feedback: make(chan Notice),
coSem: make(chan int, 1), //non-blocking buffered channel
},
lastUpdate: time.Now().Add(time.Second * -30),
TaskMap: *NewTaskMap(),
actJobs: map[string]*JobPerf{},
}
}
//--------mgr methods-------
// Lock _
func (qm *ServerMgr) Lock() {}
// Unlock _
func (qm *ServerMgr) Unlock() {}
// RLock _
func (qm *ServerMgr) RLock() {}
// RUnlock _
func (qm *ServerMgr) RUnlock() {}
// UpdateQueueLoop _
func (qm *ServerMgr) UpdateQueueLoop() {
// TODO this may not be dynamic enough for small amounts of workunits, as they always have to wait
var err error
for {
err = qm.updateWorkflowInstancesMap()
if err != nil {
logger.Error("(UpdateQueueLoop) updateWorkflowInstancesMap() returned: %s", err.Error())
err = nil
}
// *** task ***
logTimes := false
start := time.Now()
err = qm.updateQueue(logTimes)
if err != nil {
logger.Error("(UpdateQueueLoop) updateQueue returned: %s", err.Error())
err = nil
}
elapsed := time.Since(start) // type Duration
elapsedSeconds := elapsed.Seconds() // type float64
var sleeptime time.Duration
if elapsedSeconds <= 1 {
sleeptime = 1 * time.Second // wait at least 1 second
} else if elapsedSeconds > 5 && elapsedSeconds < 30 {
sleeptime = elapsed
} else {
sleeptime = 30 * time.Second // wait at most 30 seconds
}
logger.Debug(3, "(UpdateQueueLoop) elapsed: %s (sleeping for %s)", elapsed, sleeptime)
time.Sleep(sleeptime)
}
}
func (qm *ServerMgr) Is_WI_ready(job *Job, wi *WorkflowInstance) (ready bool, reason string, err error) {
logger.Debug(3, "(Is_WI_ready) start")
if wi.Inputs != nil {
ready = true
return
}
cwl_workflow := wi.Workflow
if cwl_workflow == nil {
err = fmt.Errorf("Is_WI_ready wi.Workflow==nil")
return
}
//fmt.Println("cwl_workflow.Inputs:")
//spew.Dump(cwl_workflow.Inputs)
//fmt.Println("wi.LocalID: " + wi.LocalID)
parentWorkflowInstanceName := path.Dir(wi.LocalID)
if parentWorkflowInstanceName == "." {
return
}
logger.Debug(3, "(Is_WI_ready) non-main")
//fmt.Println("parentWorkflowInstanceName: " + parentWorkflowInstanceName)
var parentWorkflowInstance *WorkflowInstance
var ok bool
parentWorkflowInstance, ok, err = job.GetWorkflowInstance(parentWorkflowInstanceName, true)
if err != nil {
err = fmt.Errorf("(Is_WI_ready) job.GetWorkflowInstance returned: %s", err.Error())
return
}
if !ok {
err = fmt.Errorf("(Is_WI_ready) parent workflow_instance %s not found", parentWorkflowInstanceName)
return
}
_ = parentWorkflowInstance
_ = ok
parent_step := wi.ParentStep
if parent_step == nil {
err = fmt.Errorf("(Is_WI_ready) wi.ParentStep==nil")
return
}
parent_workflow_input_map := parentWorkflowInstance.Inputs.GetMap()
context := job.WorkflowContext
ready, reason, err = qm.areSourceGeneratorsReady(parent_step, job, parentWorkflowInstance)
if err != nil {
err = fmt.Errorf("(Is_WI_ready) areSourceGeneratorsReady returned: %s", err.Error())
return
}
if !ready {
return
}
// err = qm.GetDependencies(job, parentWorkflowInstance, parent_workflow_input_map, step, context)
// if err != nil {
// err = fmt.Errorf("(Is_WI_ready) GetDependencies returned: %s", err.Error())
// }
// panic("done")
//var workunit_input_map map[string]cwl.CWLType
var workunit_input_map cwl.JobDocMap
workunit_input_map, ok, reason, err = qm.GetStepInputObjects(job, parentWorkflowInstance, parent_workflow_input_map, parent_step, context, "Is_WI_ready")
if err != nil {
err = fmt.Errorf("(Is_WI_ready) GetStepInputObjects returned: %s", err.Error())
return
}
//fmt.Println("workunit_input_map:")
//spew.Dump(workunit_input_map)
var workunit_input_array cwl.Job_document
workunit_input_array, err = workunit_input_map.GetArray()
wi.Inputs = workunit_input_array
ready = true
return
}
func (qm *ServerMgr) updateWorkflowInstancesMapTask(wi *WorkflowInstance) (err error) {
wi_local_id := wi.LocalID
wiState, _ := wi.GetState(true)
logger.Debug(3, "(updateWorkflowInstancesMapTask) start: %s state: %s", wi.LocalID, wiState)
if wiState == WIStatePending {
jobid := wi.JobID
//workflow_def_str := wi.Workflow_Definition
var job *Job
job, err = GetJob(jobid)
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) GetJob failed: %s", err.Error())
return
}
context := job.WorkflowContext
// get workflow
var cwl_workflow *cwl.Workflow
if wi.Workflow == nil {
cwl_workflow, err = wi.GetWorkflow(context)
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) GetWorkflow failed: %s", err.Error())
return
}
if cwl_workflow == nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) a) cwl_workflow == nil")
return
}
wi.Workflow = cwl_workflow
} else {
cwl_workflow = wi.Workflow
}
if cwl_workflow == nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) b) cwl_workflow == nil")
return
}
if cwl_workflow.Steps == nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) cwl_workflow.Steps == nil")
return
}
// check if workflow_instance is ready
var ready bool
var reason string
ready, reason, err = qm.Is_WI_ready(job, wi)
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) qm.Is_WI_ready returned: %s", err.Error())
return
}
if !ready {
logger.Debug(3, "(updateWorkflowInstancesMapTask) Wi is not ready, reason: %s", reason)
return
}
// for each step create Task or Subworkflow
if len(wi.Tasks) > 0 {
spew.Dump(wi.Tasks)
panic("wi already has tasks " + wi_local_id)
}
//subworkflow_str := []string{}
for i, _ := range cwl_workflow.Steps {
step := &cwl_workflow.Steps[i]
stepname_base := path.Base(step.Id)
//steps_str = append(steps_str, wi_local_id+"/"+stepname_base)
var process interface{}
process, _, err = step.GetProcess(context)
switch process.(type) {
case *cwl.CommandLineTool, *cwl.ExpressionTool:
fmt.Printf("(updateWorkflowInstancesMapTask) Creating (CommandLine/Expression) %s\n", wi_local_id+"/"+stepname_base)
var awe_task *Task
awe_task, err = NewTask(job, wi_local_id, stepname_base)
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) NewTask returned: %s", err.Error())
return
}
if len(step.Scatter) > 0 {
awe_task.TaskType = TASK_TYPE_SCATTER
} else {
awe_task.TaskType = TASK_TYPE_NORMAL
}
awe_task.WorkflowStep = step
_, err = awe_task.Init(job, jobid)
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) awe_task.Init returned: %s", err.Error())
return
}
logger.Debug(3, "(updateWorkflowInstancesMapTask) adding %s to workflow_instance", awe_task.TaskName)
err = wi.AddTask(job, awe_task, DbSyncTrue, true)
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) wi.AddTask returned: %s", err.Error())
return
}
err = qm.TaskMap.Add(awe_task, "updateWorkflowInstancesMapTask")
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) qm.TaskMap.Add returned: %s", err.Error())
return
}
//panic("got CommandLineTool")
// create Task
//case *cwl.ExpressionTool:
// fmt.Println("(updateWorkflowInstancesMapTask) ExpressionTool")
//create Task
case *cwl.Workflow:
//subworkflow_str = append(subworkflow_str, wi_local_id+"/"+stepname_base)
// create new WorkflowInstance
subworkflow, ok := process.(*cwl.Workflow)
if !ok {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) cannot cast to *cwl.Workflow")
return
}
subworkflow_id := subworkflow.GetID()
fmt.Printf("(updateWorkflowInstancesMapTask) Creating Workflow %s\n", subworkflow_id)
new_wi_name := wi_local_id + "/" + stepname_base
// TODO assign inputs
//var workflow_inputs cwl.Job_document
//panic("creating new subworkflow " + new_wi_name)
var new_wi *WorkflowInstance
new_wi, err = NewWorkflowInstance(new_wi_name, jobid, subworkflow_id, job, wi.LocalID)
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) NewWorkflowInstance returned: %s", err.Error())
return
}
new_wi.Workflow = subworkflow
new_wi.ParentStep = step
//new_wi.SetState(WIStatePending, "db_sync_no", false) // updateWorkflowInstancesMapTask
//AddWorkflowInstance sets steat to WIStatePending
err = job.AddWorkflowInstance(new_wi, DbSyncTrue, true) // updateWorkflowInstancesMapTask
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) job.AddWorkflowInstance returned: %s", err.Error())
return
}
newWIUniqueID, _ := new_wi.GetID(true)
err = GlobalWorkflowInstanceMap.Add(newWIUniqueID, new_wi)
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) GlobalWorkflowInstanceMap.Add returned: %s", err.Error())
return
}
err = wi.AddSubworkflow(job, new_wi.LocalID, true)
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) wi.AddSubworkflow returned: %s", err.Error())
return
}
default:
err = fmt.Errorf("(updateWorkflowInstancesMapTask) type unknown: %s", reflect.TypeOf(process))
return
}
//spew.Dump(cwl_workflow.Steps[i])
}
//wi.Subworkflows = subworkflow_str
// pending -> ready
err = wi.SetState(WIStateReady, DbSyncTrue, true)
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) wi.SetState returned: %s", err.Error())
return
}
//spew.Dump(wi)
//fmt.Printf("SHOULD BE READY NOW (%p)\n", wi)
if wi.Inputs != nil && len(wi.Inputs) > 0 {
//panic("found something...")
var tasks []*Task
tasks, err = wi.GetTasks(true)
if err != nil {
return
}
err = qm.EnqueueTasks(tasks)
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) EnqueueTasks returned: %s", err.Error())
return
}
}
err = wi.SetState(WIStateQueued, DbSyncTrue, true)
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) SetState returned: %s", err.Error())
return
}
// update job state
if wi_local_id == "#main" {
job_state, _ := job.GetState(true)
if job_state == JOB_STAT_INIT {
err = job.SetState(JOB_STAT_QUEUED, []string{JOB_STAT_INIT})
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMapTask) job.SetState returned: %s", err.Error())
return
}
}
}
}
return
}
func (qm *ServerMgr) updateWorkflowInstancesMap() (err error) {
var wis []*WorkflowInstance
wis, err = GlobalWorkflowInstanceMap.GetWorkflowInstances()
if err != nil {
err = fmt.Errorf("(updateWorkflowInstancesMap) ")
return
}
var last_error error
error_count := 0
for i, _ := range wis {
wi := wis[i]
err = qm.updateWorkflowInstancesMapTask(wi)
if err != nil {
last_error = err
error_count += 1
err = nil
}
}
if error_count > 0 {
err = fmt.Errorf("(updateWorkflowInstancesMap) %d errors, last error message: %s", error_count, last_error.Error())
return
}
return
}
func (qm *ServerMgr) ClientHandle() {
logger.Info("(ServerMgr ClientHandle) starting")
count := 0
time.Sleep(3 * time.Second)
for {
//select {
//case coReq := <-qm.coReq
//logger.Debug(3, "(ServerMgr ClientHandle) try to pull work request")
//coReq, err := qm.requestQueue.Pull()
//for err != nil {
// time.Sleep(50 * time.Millisecond) // give clients time to put in requests or get a response
// time.Sleep(3 * time.Second)
// coReq, err = qm.requestQueue.Pull()
// logger.Debug(3, "(ServerMgr ClientHandle) waiting")
//}
//logger.Debug(3, "(ServerMgr ClientHandle) got work request")
coReq := <-qm.coReq //written to in cqmgr.go
count += 1
request_start_time := time.Now()
logger.Debug(3, "(ServerMgr ClientHandle) workunit checkout request received from client %s, Req=%v", coReq.fromclient, coReq)
ok, err := qm.CQMgr.clientMap.Has(coReq.fromclient, true)
if err != nil {
logger.Warning("(ServerMgr ClientHandle) Could not get lock for client %s (%s)", coReq.fromclient, err.Error())
continue
}
if !ok {
logger.Error("(ServerMgr ClientHandle) Client %s not found. (It probably left in the mean-time)", coReq.fromclient)
continue
}
var ack CoAck
if qm.suspendQueue {
// queue is suspended, return suspend error
ack = CoAck{workunits: nil, err: errors.New(e.QueueSuspend)}
logger.Debug(3, "(ServerMgr ClientHandle %s) nowworkunit: e.QueueSuspend", coReq.fromclient)
} else {
logger.Debug(3, "(ServerMgr ClientHandle %s) popWorks", coReq.fromclient)
works, err := qm.popWorks(coReq)
if err != nil {
logger.Debug(3, "(ServerMgr ClientHandle) popWorks returned error: %s", err.Error())
}
logger.Debug(3, "(ServerMgr ClientHandle %s) popWorks done", coReq.fromclient)
if err == nil {
logger.Debug(3, "(ServerMgr ClientHandle %s) UpdateJobTaskToInProgress", coReq.fromclient)
qm.UpdateJobTaskToInProgress(works)
logger.Debug(3, "(ServerMgr ClientHandle %s) UpdateJobTaskToInProgress done", coReq.fromclient)
}
ack = CoAck{workunits: works, err: err}
if len(works) > 0 {
wu := works[0]
logger.Debug(3, "(ServerMgr ClientHandle %s) workunit: %s", coReq.fromclient, wu.Id)
} else {
logger.Debug(3, "(ServerMgr ClientHandle %s) works is empty", coReq.fromclient)
}
}
logger.Debug(3, "(ServerMgr ClientHandle %s) send response now", coReq.fromclient)
start_time := time.Now()
timer := time.NewTimer(20 * time.Second)
select {
case coReq.response <- ack:
logger.Debug(3, "(ServerMgr ClientHandle %s) send response (maybe workunit) to client via response channel", coReq.fromclient)
case <-timer.C:
elapsed_time := time.Since(start_time)
logger.Error("(ServerMgr ClientHandle %s) timed out after %s ", coReq.fromclient, elapsed_time)
continue
}
logger.Debug(3, "(ServerMgr ClientHandle %s) done", coReq.fromclient)
if count%100 == 0 { // use modulo to reduce number of log messages
request_time_elapsed := time.Since(request_start_time)
logger.Info("(ServerMgr ClientHandle) Responding to work request took %s", request_time_elapsed)
}
}
}
func (qm *ServerMgr) NoticeHandle() {
logger.Info("(ServerMgr NoticeHandle) starting")
for {
notice := <-qm.feedback
id, err := notice.ID.String()
if err != nil {
logger.Error("(NoticeHandle) notice.ID invalid: " + err.Error())
err = nil
continue
}
logger.Debug(3, "(ServerMgr NoticeHandle) got notice: workid=%s, status=%s, clientid=%s", id, notice.Status, notice.WorkerID)
//fmt.Printf("Notice:")
//spew.Dump(notice)
err = qm.handleNoticeWorkDelivered(notice)
if err != nil {
err = fmt.Errorf("(NoticeHandle): %s", err.Error())
logger.Error(err.Error())
//fmt.Println(err.Error())
}
}
}
//--------queue status methods-------
func (qm *ServerMgr) SuspendQueue() {
qm.suspendQueue = true
}
func (qm *ServerMgr) ResumeQueue() {
qm.suspendQueue = false
}
func (qm *ServerMgr) QueueStatus() string {
if qm.suspendQueue {
return "suspended"
} else {
return "running"
}
}
func (qm *ServerMgr) GetQueue(name string) interface{} {
if name == "job" {
suspended_jobs := qm.GetSuspendJobs()
return jQueueShow{qm.actJobs, suspended_jobs}
}
if name == "task" {
tasks, err := qm.TaskMap.GetTasks()
if err != nil {
return err
}
return tasks
}
if name == "workall" {
workunits, err := qm.workQueue.all.GetWorkunits()
if err != nil {
return err
}
return workunits
}
if name == "workqueue" {
workunits, err := qm.workQueue.Queue.GetWorkunits()
if err != nil {
return err
}
return workunits
}
if name == "workcheckout" {
workunits, err := qm.workQueue.Checkout.GetWorkunits()
if err != nil {
return err
}
return workunits
}
if name == "worksuspend" {
workunits, err := qm.workQueue.Suspend.GetWorkunits()
if err != nil {
return err
}
return workunits
}
if name == "client" {
return &qm.clientMap
}
return nil
}
//--------suspend job accessor methods-------
func (qm *ServerMgr) lenSusJobs() (l int) {
l = 0
jobs, _ := JM.Get_List(true) // TODO error handling
for i := range jobs {
job := jobs[i]
state, _ := job.GetState(true)
if state == JOB_STAT_SUSPEND {
l += 1
}
}
//qm.sjLock.RLock()
//l = len(qm.susJobs)
//qm.sjLock.RUnlock()
return
}
//func (qm *ServerMgr) putSusJob(id string) {
// qm.sjLock.Lock()
// qm.susJobs[id] = true
// qm.sjLock.Unlock()
//}
func (qm *ServerMgr) GetSuspendJobs() (sjobs map[string]bool) {
jobs, _ := JM.Get_List(true) // TODO error handling
sjobs = make(map[string]bool)
for i := range jobs {
job := jobs[i]
state, _ := job.GetState(true) // TODO error handling
if state == JOB_STAT_SUSPEND {
id, _ := job.GetId(true)
sjobs[id] = true
}
}
// qm.sjLock.RLock()
// defer qm.sjLock.RUnlock()
// sjobs = make(map[string]bool)
// for id, _ := range qm.susJobs {
// sjobs[id] = true
// }
return
}
//func (qm *ServerMgr) removeSusJob(id string) {
// qm.sjLock.Lock()
// delete(qm.susJobs, id)
// qm.sjLock.Unlock()
//}
func (qm *ServerMgr) isSusJob(id string) (has bool) {
job, err := GetJob(id)
if err != nil {
return
}
job_state, err := job.GetState(true)
if err != nil {
return
}
has = false
if job_state == JOB_STAT_COMPLETED {
has = true
}
return
// qm.sjLock.RLock()
// defer qm.sjLock.RUnlock()
// if _, ok := qm.susJobs[id]; ok {
// has = true
// } else {
// has = false
// }
// return
}
//--------active job accessor methods-------
func (qm *ServerMgr) copyJobPerf(a *JobPerf) (b *JobPerf) {
b = new(JobPerf)
*b = *a
return
}
func (qm *ServerMgr) lenActJobs() (l int) {
qm.ajLock.RLock()
l = len(qm.actJobs)
qm.ajLock.RUnlock()
return
}
func (qm *ServerMgr) putActJob(jperf *JobPerf) {
qm.ajLock.Lock()
qm.actJobs[jperf.Id] = jperf
qm.ajLock.Unlock()
}
func (qm *ServerMgr) getActJob(id string) (*JobPerf, bool) {
qm.ajLock.RLock()
defer qm.ajLock.RUnlock()
if jobperf, ok := qm.actJobs[id]; ok {
copy := qm.copyJobPerf(jobperf)
return copy, true
}
return nil, false
}
func (qm *ServerMgr) GetActiveJobs() (ajobs map[string]bool) {
qm.ajLock.RLock()
defer qm.ajLock.RUnlock()
ajobs = make(map[string]bool)
for id, _ := range qm.actJobs {
ajobs[id] = true
}
return
}
func (qm *ServerMgr) removeActJob(id string) {
qm.ajLock.Lock()
delete(qm.actJobs, id)
qm.ajLock.Unlock()
}
func (qm *ServerMgr) isActJob(id string) (ok bool) {
qm.ajLock.RLock()
defer qm.ajLock.RUnlock()
_, ok = qm.actJobs[id]
return
}
//--------server methods-------
//poll ready tasks and push into workQueue
func (qm *ServerMgr) updateQueue(logTimes bool) (err error) {
logger.Debug(3, "(updateQueue) wait for lock")
qm.queueLock.Lock()
defer qm.queueLock.Unlock()
logger.Debug(3, "(updateQueue) starting")
var tasks []*Task
tasks, err = qm.TaskMap.GetTasks()
if err != nil {
return
}
if len(tasks) > 0 {
task := tasks[0]
job_id := task.JobId
job, _ := GetJob(job_id)
job_state, _ := job.GetState(true)
fmt.Printf("*** job *** %s %s\n", job_id, job_state)
for wi_id, _ := range job.WorkflowInstancesMap {
wi := job.WorkflowInstancesMap[wi_id]
wiState, _ := wi.GetState(true)
fmt.Printf("WorkflowInstance: %s (%s) remain: %d\n", wi_id, wiState, wi.RemainSteps)
var wi_tasks []*Task
wi_tasks, err = wi.GetTasks(true)
if err != nil {
return
}
if len(wi_tasks) > 0 {
for j, _ := range wi_tasks {
task := wi_tasks[j]
fmt.Printf(" Task %d: %s (wf: %s, state %s)\n", j, task.Id, task.WorkflowInstanceId, task.State)
}
} else {
fmt.Printf(" no tasks\n")
}
if len(wi_tasks) > 20 {
panic("too many tasks!")
}
for _, sw := range wi.Subworkflows {
fmt.Printf(" Subworkflow: %s\n", sw)
}
}
}
logger.Debug(3, "(updateQueue) range tasks (%d)", len(tasks))
threads := 20
size, _ := qm.TaskMap.Len()
loopStart := time.Now()
logger.Debug(3, "(updateQueue) starting loop through TaskMap; threads: %d, TaskMap.Len: %d", threads, size)
taskChan := make(chan *Task, size)
queueChan := make(chan bool, size)
for w := 1; w <= threads; w++ {
go qm.updateQueueWorker(w, logTimes, taskChan, queueChan)
}
total := 0
for _, task := range tasks {
taskIDStr, _ := task.String()
logger.Debug(3, "(updateQueue) sending task to QueueWorkers: %s", taskIDStr)
total += 1
taskChan <- task
}
close(taskChan)
queue := 0
for i := 1; i <= size; i++ {
q := <-queueChan
if q {
queue += 1
}
}
close(queueChan)
logger.Debug(3, "(updateQueue) completed loop through TaskMap; # processed: %d, queued: %d, took %s", total, queue, time.Since(loopStart))
logger.Debug(3, "(updateQueue) range qm.workQueue.Clean()")
for _, workunit := range qm.workQueue.Clean() {
id := workunit.Id
job_id := workunit.JobId
task_id := workunit.TaskName
jerror := &JobError{
WorkFailed: id,
TaskFailed: task_id,
ServerNotes: "workunit is nil",
Status: JOB_STAT_SUSPEND,
}
if err = qm.SuspendJob(job_id, jerror); err != nil {
logger.Error("(updateQueue:SuspendJob) job_id=%s; err=%s", job_id, err.Error())
}
logger.Error("(updateQueue) workunit %s is nil, suspending job %s", id, job_id)
}
logger.Debug(3, "(updateQueue) ending")
return
}
func (qm *ServerMgr) updateQueueWorker(id int, logTimes bool, taskChan <-chan *Task, queueChan chan<- bool) {
var taskSlow time.Duration = 1 * time.Second
for task := range taskChan {
taskStart := time.Now()
taskIDStr, _ := task.String()
isQueued, times, err := qm.updateQueueTask(task, logTimes)
if err != nil {
logger.Error("(updateQueue) updateQueueTask task: %s error: %s", taskIDStr, err.Error())
}
if logTimes {
taskTime := time.Since(taskStart)
message := fmt.Sprintf("(updateQueue) thread %d processed task: %s, took: %s, is queued %t", id, taskIDStr, taskTime, isQueued)
if taskTime > taskSlow {
message += fmt.Sprintf(", times: %+v", times)
}
logger.Info(message)
}
queueChan <- isQueued
}
}
func (qm *ServerMgr) updateQueueTask(task *Task, logTimes bool) (isQueued bool, times map[string]time.Duration, err error) {
var task_id Task_Unique_Identifier
task_id, err = task.GetId("updateQueueTask")
if err != nil {
return
}
taskIDStr, _ := task_id.String()
var task_state string
task_state, err = task.GetState()
if err != nil {
return
}
switch task_state {
case TASK_STAT_READY:
logger.Debug(3, "(updateQueueTask) task %s already has state %s, continue with enqueuing", taskIDStr, task_state)
case TASK_STAT_INIT, TASK_STAT_PENDING:
logger.Debug(3, "(updateQueueTask) task %s has state %s, first check if ready", taskIDStr, task_state)
var task_ready bool
var reason string
startIsReady := time.Now()
if logTimes {
times = make(map[string]time.Duration)
}
task_ready, reason, err = qm.isTaskReady(task_id, task)
if logTimes {
times["isTaskReady"] = time.Since(startIsReady)
}
if err != nil {
err = fmt.Errorf("(updateQueueTask) qm.isTaskReady returned: %s", err.Error())
return
}
if !task_ready {
task.NotReadyReason = reason
logger.Debug(3, "(updateQueueTask) task not ready (%s): qm.isTaskReady returned reason: %s", taskIDStr, reason)
return
}
// get new state
task_state, err = task.GetState()
if err != nil {
return
}
default:
logger.Debug(3, "(updateQueueTask) skipping task %s , it has state %s", taskIDStr, task_state)
return
}
logger.Debug(3, "(updateQueueTask) task: %s (state: %s, added by %s)", taskIDStr, task_state, task.Comment)
// task_ready
if task_state != TASK_STAT_READY {
err = fmt.Errorf("(updateQueueTask) task is not rerady !???!?")
return
}
logger.Debug(3, "(updateQueueTask) task %s is ready now, continue to enqueuing", taskIDStr)
var job_id string
job_id, err = task.GetJobId()
if err != nil {