-
Notifications
You must be signed in to change notification settings - Fork 21
/
cqmgr.go
1231 lines (1035 loc) · 31.4 KB
/
cqmgr.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 (
"errors"
"fmt"
"github.com/MG-RAST/AWE/lib/conf"
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"
//"github.com/davecgh/go-spew/spew"
"encoding/json"
"os"
"runtime"
"runtime/pprof"
"strings"
"time"
"gopkg.in/mgo.v2/bson"
)
// CQMgr this struct is embedded in ServerMgr
type CQMgr struct {
clientMap ClientMap
workQueue *WorkQueue
suspendQueue bool
coReq chan CheckoutRequest //workunit checkout request (WorkController -> qmgr.Handler)
feedback chan Notice //workunit execution feedback (WorkController -> qmgr.Handler)
coSem chan int //semaphore for checkout (mutual exclusion between different clients)
}
// FilterWorkStats _
type FilterWorkStats struct {
Total int
SkipWork int
WrongClientgroup int
WrongApp int
}
//--------mgr methods-------
// ClientHandle _
func (qm *CQMgr) ClientHandle() {
// this code is not beeing used
}
//--------accessor methods-------
// GetClientMap _
func (qm *CQMgr) GetClientMap() *ClientMap {
return &qm.clientMap
}
// AddClient _
func (qm *CQMgr) AddClient(client *Client, lock bool) (err error) {
err = qm.clientMap.Add(client, lock)
return
}
// GetClient _
func (qm *CQMgr) GetClient(id string, lockClientMap bool) (client *Client, ok bool, err error) {
return qm.clientMap.Get(id, lockClientMap)
}
// RemoveClient lock is for clientmap
func (qm *CQMgr) RemoveClient(id string, lock bool) (err error) {
client, ok, err := qm.clientMap.Get(id, true)
if err != nil {
return
}
if !ok {
err = fmt.Errorf("Client %s not found", id)
return
}
//now client must be gone as tag set to false 30 seconds ago and no heartbeat received thereafter
logger.Event(event.CLIENT_UNREGISTER, "clientid="+client.ID)
//requeue unfinished workunits associated with the failed client
err = qm.ReQueueWorkunitByClient(client, true)
if err != nil {
logger.Error("(CheckClient) %s", err.Error())
}
err = qm.clientMap.Delete(id, lock)
return
}
//func (qm *CQMgr) DeleteClient(client *Client) (err error) {
// err = qm.ClientStatusChange(client, CLIENT_STAT_DELETED, true)
// return
//}
//func (qm *CQMgr) DeleteClientById(id string) (err error) {
// err = qm.ClientIdStatusChange(id, CLIENT_STAT_DELETED, true)
// return
//}
// func (qm *CQMgr) ClientIdStatusChange_deprecated(id string, new_status string, clientWriteLock bool) (err error) {
// client, ok, err := qm.clientMap.Get(id, true)
// if err != nil {
// return
// }
// if ok {
// //err = client.Set_Status(new_status, clientWriteLock)
// return
// }
// returnerrors.New(e.ClientNotFound)
//}
// ClientStatusChangeDeprecated _
func (qm *CQMgr) ClientStatusChangeDeprecated(client *Client, newStatus string, clientWriteLock bool) (err error) {
//client.Set_Status(new_status, clientWriteLock)
return
}
// HasClient _
func (qm *CQMgr) HasClient(id string, lockClientMap bool) (has bool, err error) {
_, ok, err := qm.clientMap.Get(id, lockClientMap)
if err != nil {
return
}
if ok {
has = true
} else {
has = false
}
return
}
// ListClients _
func (qm *CQMgr) ListClients() (ids []string, err error) {
//qm.clientMap.RLock()
//defer qm.clientMap.RUnlock()
//for id, _ := range qm.clientMap {
// ids = append(ids, id)
//}
return qm.clientMap.GetClientIds()
}
//--------client methods-------
//CheckClient _
func (qm *CQMgr) CheckClient(client *Client) (ok bool, err error) {
ok = true
err = client.LockNamed("ClientChecker")
if err != nil {
return
}
defer client.Unlock()
logger.Debug(3, "(CheckClient) client: %s", client.ID)
if client.Tag == true {
// *** Client is active
client.Online = true
logger.Debug(3, "(CheckClient) client %s active", client.ID)
client.Tag = false
totalMinutes := int(time.Now().Sub(client.RegTime).Minutes())
hours := totalMinutes / 60
minutes := totalMinutes % 60
client.ServeTime = fmt.Sprintf("%dh%dm", hours, minutes)
//spew.Dump(client)
currentWork, xerr := client.WorkerState.CurrentWork.Get_list(false)
if xerr != nil {
logger.Error("(CheckClient) Get_current_work: %s", xerr.Error())
return
}
logger.Debug(3, "(CheckClient) client %s has %d workunits", client.ID, len(currentWork))
for _, workID := range currentWork {
var workidStr string
workidStr, err = workID.String()
if err != nil {
return
}
logger.Debug(3, "(CheckClient) client %s has work %s", client.ID, workidStr)
work, ok, zerr := qm.workQueue.all.Get(workID)
if zerr != nil {
logger.Warning("(CheckClient) failed getting work %s from workQueue: %s", workidStr, zerr.Error())
continue
}
if !ok {
logger.Error("(CheckClient) work %s not in workQueue", workidStr) // this could happen wehen server was restarted but worker does not know yet
continue
}
logger.Debug(3, "(CheckClient) work.State: %s", work.State)
if work.State == WORK_STAT_RESERVED {
qm.workQueue.StatusChange(workID, work, WORK_STAT_CHECKOUT, "")
}
}
} else {
client.Online = false
ok = false
}
return
}
// ClientChecker _
func (qm *CQMgr) ClientChecker() {
logger.Info("(ClientChecker) starting")
if conf.CPUPROFILE != "" {
f, err := os.Create(conf.CPUPROFILE)
if err != nil {
logger.Error(err.Error())
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
for {
time.Sleep(30 * time.Second)
if conf.MEMPROFILE != "" {
f, err := os.Create(conf.MEMPROFILE)
if err != nil {
logger.Error("could not create memory profile: %s", err.Error())
}
runtime.GC() // get up-to-date statistics
if err := pprof.WriteHeapProfile(f); err != nil {
logger.Error("could not write memory profile: %s", err.Error())
}
f.Close()
}
logger.Debug(3, "(ClientChecker) time to update client list....")
deleteClients := []string{}
clientList, xerr := qm.clientMap.GetClients() // this uses a list of pointers to prevent long locking of the CLientMap
if xerr != nil {
logger.Error("(ClientChecker) GetClients: %s", xerr.Error())
continue
}
logger.Debug(3, "(ClientChecker) check %d clients", len(clientList))
for _, client := range clientList {
ok, xerr := qm.CheckClient(client)
if xerr != nil {
logger.Error("(ClientChecker) CheckClient: %s", xerr.Error())
continue
}
if !ok {
deleteClients = append(deleteClients, client.ID)
}
}
// Now delete clients
if len(deleteClients) > 0 {
qm.DeleteClients(deleteClients)
}
}
}
// DeleteClients _
func (qm *CQMgr) DeleteClients(deleteClients []string) {
for _, clientID := range deleteClients {
qm.RemoveClient(clientID, true)
}
}
// ClientHeartBeat this is invoked on server side when clients sends heartbeat
func (qm *CQMgr) ClientHeartBeat(id string, cg *ClientGroup, workerstate WorkerState) (hbmsg HeartbeatInstructions, err error) {
hbmsg = make(map[string]string, 1)
client, ok, xerr := qm.GetClient(id, true)
if xerr != nil {
err = xerr
return
}
if !ok {
err = errors.New(e.ClientNotFound)
return
}
err = client.LockNamed("ClientHeartBeat")
if err != nil {
return
}
defer client.Unlock()
// If the name of the clientgroup (from auth token) does not match the name in the client retrieved, throw an error
if cg != nil && client.Group != cg.Name {
return nil, errors.New(e.ClientGroupBadName)
}
client.Tag = true
err = client.SetOnline(true, false)
if err != nil {
return
}
workerstate.CurrentWork.FillMap() // fix struct by moving values from Data array into internal map (was not exported)
client.WorkerState = workerstate // TODO could do a comparsion with assigned state here
_ = client.UpdateStatus(false)
logger.Debug(3, "HeartBeatFrom: client %s", id)
//get suspended workunit that need the client to discard
currentWork, xerr := client.CurrentWork.Get_list(false)
discard := []string{}
for _, workID := range currentWork {
var work *Workunit
work, ok, err = qm.workQueue.all.Get(workID)
if err != nil {
return
}
if !ok {
workIDSstr, _ := workID.String()
// server does not know about the work the client id working on
logger.Error("(ClientHeartBeat) Client was working on unknown workunit. Told him to discard.")
discard = append(discard, workIDSstr)
continue
}
if work.State == WORK_STAT_SUSPEND {
discard = append(discard, work.Id)
}
}
if len(discard) > 0 {
hbmsg["discard"] = strings.Join(discard, ",")
}
//if client.Status == CLIENT_STAT_DELETED {
// hbmsg["stop"] = id
//}
hbmsg["server-uuid"] = ServerUUID
return
}
// RegisterNewClient This can be a new client or an old client that re-registers
func (qm *CQMgr) RegisterNewClient(files FormFiles, cg *ClientGroup) (client *Client, err error) {
logger.Debug(3, "RegisterNewClient called")
if _, ok := files["profile"]; ok {
client, err = NewProfileClient(files["profile"].Path)
os.Remove(files["profile"].Path)
if err != nil {
err = fmt.Errorf("NewProfileClient returned: %s", err.Error())
return
}
} else {
err = fmt.Errorf("Profile file not provided")
return
//client = NewClient()
}
err = client.LockNamed("RegisterNewClient")
if err != nil {
return
}
clientGroup := client.Group
clientID, _ := client.GetID(false)
client.Unlock()
// If clientgroup is nil at this point, create a publicly owned clientgroup, with the provided group name (if one doesn't exist with the same name)
if cg == nil {
// See if clientgroup already exists with this name
// If it does and it does not have "public" execution rights, throw error
// If it doesn't, create one owned by public, and continue with client registration
// Otherwise proceed with client registration.
cg, _ = LoadClientGroupByName(clientGroup)
if cg != nil {
rights := cg.ACL.Check("public")
if rights["execute"] == false {
err = errors.New("Clientgroup with the group specified by your client exists, but you cannot register with it, without clientgroup token")
return
}
} else {
u := &user.User{Uuid: "public"}
cg, err = CreateClientGroup(clientGroup, u)
if err != nil {
err = fmt.Errorf("CreateClientGroup returned: %s", err.Error())
return nil, err
}
}
}
// If the name of the clientgroup (from auth token) does not match the name in the client profile, throw an error
if cg != nil && clientGroup != cg.Name {
return nil, errors.New(e.ClientGroupBadName)
}
// check if client is already known
var oldClient *Client
var oldClientExists bool
oldClient, oldClientExists, err = qm.GetClient(clientID, true)
if err != nil {
return
}
if oldClientExists {
// copy values from new client to old client
oldClient.CurrentWork = client.CurrentWork
oldClient.Tag = true
// new client struct will be deleted afterwards
} else {
client.Tag = true
err = qm.AddClient(client, true)
if err != nil {
return
}
}
return
}
// GetClientByUser _
func (qm *CQMgr) GetClientByUser(id string, u *user.User) (client *Client, err error) {
// Get all clientgroups that user owns or that are publicly owned, or all if user is admin
q := bson.M{}
clientgroups := new(ClientGroups)
dbFindClientGroups(q, clientgroups)
filteredClientGroups := map[string]bool{}
for _, cg := range *clientgroups {
if (u.Uuid != "public" && (cg.ACL.Owner == u.Uuid || u.Admin == true || cg.ACL.Owner == "public")) ||
(u.Uuid == "public" && conf.CLIENT_AUTH_REQ == false && cg.ACL.Owner == "public") {
filteredClientGroups[cg.Name] = true
}
}
client, ok, err := qm.GetClient(id, true)
if err != nil {
return
}
if ok {
if val, exists := filteredClientGroups[client.Group]; exists == true || val == true {
return client, nil
}
}
return nil, errors.New(e.ClientNotFound)
}
// GetAllClientsByUser _
func (qm *CQMgr) GetAllClientsByUser(u *user.User) (clients []*Client, err error) {
// Get all clientgroups that user owns or that are publicly owned, or all if user is admin
q := bson.M{}
clientgroups := new(ClientGroups)
dbFindClientGroups(q, clientgroups)
filteredClientGroups := map[string]bool{}
for _, cg := range *clientgroups {
rights := cg.ACL.Check(u.Uuid)
if (u.Uuid != "public" && (cg.ACL.Owner == u.Uuid || rights["read"] == true || u.Admin == true || cg.ACL.Owner == "public")) ||
(u.Uuid == "public" && conf.CLIENT_AUTH_REQ == false && cg.ACL.Owner == "public") {
filteredClientGroups[cg.Name] = true
}
}
allClients, err := qm.clientMap.GetClients()
if err != nil {
return
}
for _, client := range allClients {
if val, exists := filteredClientGroups[client.Group]; exists == true && val == true {
clients = append(clients, client)
}
}
return
}
// func (qm *CQMgr) DeleteClientByUser(id string, u *user.User) (err error) {
// // Get all clientgroups that user owns or that are publicly owned, or all if user is admin
// q := bson.M{}
// clientgroups := new(ClientGroups)
// dbFindClientGroups(q, clientgroups)
// filteredClientGroups := map[string]bool{}
// for _, cg := range *clientgroups {
// if (u.Uuid != "public" && (cg.ACL.Owner == u.Uuid || u.Admin == true || cg.ACL.Owner == "public")) ||
// (u.Uuid == "public" && conf.CLIENT_AUTH_REQ == false && cg.ACL.Owner == "public") {
// filteredClientGroups[cg.Name] = true
// }
// }
//
// client, ok, err := qm.GetClient(id, true)
// if err != nil {
// return
// }
// if ok {
// if val, exists := filteredClientGroups[client.Group]; exists == true && val == true {
// err = qm.DeleteClient(client)
// return
// }
// return errors.New(e.UnAuth)
// }
// return errors.New(e.ClientNotFound)
// }
// SuspendClient use id OR client
func (qm *CQMgr) SuspendClient(id string, client *Client, reason string, clientWriteLock bool) (err error) {
if client == nil {
var ok bool
client, ok, err = qm.GetClient(id, true)
if err != nil {
return
}
if !ok {
err = errors.New(e.ClientNotFound)
return
}
}
if clientWriteLock {
err = client.LockNamed("SuspendClient")
if err != nil {
return
}
defer client.Unlock()
}
isSuspended, err := client.GetSuspended(false)
if err != nil {
return
}
if isSuspended {
err = errors.New(e.ClientNotActive)
return
}
client.Suspend(reason, false)
err = qm.ReQueueWorkunitByClient(client, false)
if err != nil {
return
}
return
}
// SuspendAllClients _
func (qm *CQMgr) SuspendAllClients(reason string) (count int, err error) {
clients, err := qm.ListClients()
if err != nil {
return
}
for _, id := range clients {
if err := qm.SuspendClient(id, nil, reason, true); err == nil {
count++
}
}
return
}
// SuspendClientByUser _
func (qm *CQMgr) SuspendClientByUser(id string, u *user.User, reason string) (err error) {
// Get all clientgroups that user owns or that are publicly owned, or all if user is admin
q := bson.M{}
clientgroups := new(ClientGroups)
dbFindClientGroups(q, clientgroups)
filteredClientGroups := map[string]bool{}
for _, cg := range *clientgroups {
if (u.Uuid != "public" && (cg.ACL.Owner == u.Uuid || u.Admin == true || cg.ACL.Owner == "public")) ||
(u.Uuid == "public" && conf.CLIENT_AUTH_REQ == false && cg.ACL.Owner == "public") {
filteredClientGroups[cg.Name] = true
}
}
client, ok, err := qm.GetClient(id, true)
if err != nil {
return
}
if ok {
err = errors.New(e.ClientNotFound)
return
}
val, exists := filteredClientGroups[client.Group]
if exists == true && val == true {
err = qm.SuspendClient("", client, reason, true)
if err != nil {
return
}
}
return errors.New(e.UnAuth)
}
// SuspendAllClientsByUser _
func (qm *CQMgr) SuspendAllClientsByUser(u *user.User, reason string) (count int, err error) {
// Get all clientgroups that user owns or that are publicly owned, or all if user is admin
q := bson.M{}
clientgroups := new(ClientGroups)
dbFindClientGroups(q, clientgroups)
filteredClientGroups := map[string]bool{}
for _, cg := range *clientgroups {
if (u.Uuid != "public" && (cg.ACL.Owner == u.Uuid || u.Admin == true || cg.ACL.Owner == "public")) ||
(u.Uuid == "public" && conf.CLIENT_AUTH_REQ == false && cg.ACL.Owner == "public") {
filteredClientGroups[cg.Name] = true
}
}
clients, err := qm.clientMap.GetClients()
if err != nil {
return
}
for _, client := range clients {
isSuspended, xerr := client.GetSuspended(true)
if xerr != nil {
err = xerr
return
}
group, xerr := client.GetGroup(true)
if xerr != nil {
return
}
if val, exists := filteredClientGroups[group]; exists == true && val == true && isSuspended {
err = qm.SuspendClient("", client, reason, true)
if err != nil {
return
}
count++
}
}
return
}
// ResumeClient _
func (qm *CQMgr) ResumeClient(id string) (err error) {
client, ok, err := qm.GetClient(id, true)
if err != nil {
return
}
if !ok {
return errors.New(e.ClientNotFound)
}
err = client.Resume(true)
if err != nil {
return
}
return
}
// ResumeClientByUser _
func (qm *CQMgr) ResumeClientByUser(id string, u *user.User) (err error) {
// Get all clientgroups that user owns or that are publicly owned, or all if user is admin
q := bson.M{}
clientgroups := new(ClientGroups)
dbFindClientGroups(q, clientgroups)
filteredClientGroups := map[string]bool{}
for _, cg := range *clientgroups {
if (u.Uuid != "public" && (cg.ACL.Owner == u.Uuid || u.Admin == true || cg.ACL.Owner == "public")) ||
(u.Uuid == "public" && conf.CLIENT_AUTH_REQ == false && cg.ACL.Owner == "public") {
filteredClientGroups[cg.Name] = true
}
}
client, ok, err := qm.GetClient(id, true)
if err != nil {
return
}
if !ok {
return errors.New(e.ClientNotFound)
}
if val, exists := filteredClientGroups[client.Group]; exists == true && val == true {
err = client.Resume(true)
if err != nil {
return
}
return
}
return errors.New(e.UnAuth)
}
// ResumeSuspendedClients _
func (qm *CQMgr) ResumeSuspendedClients() (count int, err error) {
clients, err := qm.clientMap.GetClients()
if err != nil {
return
}
for _, client := range clients {
isSuspended, xerr := client.GetSuspended(true)
if xerr != nil {
err = xerr
return
}
if isSuspended {
//qm.ClientStatusChange(client.ID, CLIENT_STAT_ACTIVE_IDLE)
err = client.Resume(true)
if err != nil {
return
}
count++
}
}
return
}
// ResumeSuspendedClientsByUser _
func (qm *CQMgr) ResumeSuspendedClientsByUser(u *user.User) (count int) {
// Get all clientgroups that user owns or that are publicly owned, or all if user is admin
q := bson.M{}
clientgroups := new(ClientGroups)
dbFindClientGroups(q, clientgroups)
filteredClientGroups := map[string]bool{}
for _, cg := range *clientgroups {
if (u.Uuid != "public" && (cg.ACL.Owner == u.Uuid || u.Admin == true || cg.ACL.Owner == "public")) ||
(u.Uuid == "public" && conf.CLIENT_AUTH_REQ == false && cg.ACL.Owner == "public") {
filteredClientGroups[cg.Name] = true
}
}
clients, err := qm.clientMap.GetClients()
if err != nil {
return
}
for _, client := range clients {
isSuspended, xerr := client.GetSuspended(true)
if xerr != nil {
err = xerr
return
}
if !isSuspended {
continue
}
group, err := client.GetGroup(true)
val, exists := filteredClientGroups[group]
if exists == true && val == true {
err = client.Resume(true)
if err != nil {
return
}
count++
}
}
return count
}
// UpdateSubClients _
func (qm *CQMgr) UpdateSubClients(id string, count int) (err error) {
client, ok, err := qm.GetClient(id, true)
if err != nil {
return
}
if ok {
client.SubClients = count
}
return
}
// UpdateSubClientsByUser _
func (qm *CQMgr) UpdateSubClientsByUser(id string, count int, u *user.User) {
// Get all clientgroups that user owns or that are publicly owned, or all if user is admin
q := bson.M{}
clientgroups := new(ClientGroups)
dbFindClientGroups(q, clientgroups)
filteredClientGroups := map[string]bool{}
for _, cg := range *clientgroups {
if (u.Uuid != "public" && (cg.ACL.Owner == u.Uuid || u.Admin == true || cg.ACL.Owner == "public")) ||
(u.Uuid == "public" && conf.CLIENT_AUTH_REQ == false && cg.ACL.Owner == "public") {
filteredClientGroups[cg.Name] = true
}
}
client, ok, err := qm.GetClient(id, true)
if err != nil {
return
}
if ok {
if val, exists := filteredClientGroups[client.Group]; exists == true && val == true {
client.SubClients = count
}
}
}
//--------end client methods-------
//-------start of workunit methods---
// CheckoutWorkunits _
func (qm *CQMgr) CheckoutWorkunits(reqPolicy string, clientID string, client *Client, availableBytes int64, num int) (workunits []*Workunit, err error) {
logger.Debug(3, "run CheckoutWorkunits for client %s", clientID)
//precheck if the client is registered
//client, hasClient, err := qm.GetClient(client_id, true)
//if err != nil {
// return
//}
//if !hasClient {
// return nil, errors.New(e.ClientNotFound)
//}
err = client.LockNamed("CheckoutWorkunits serving " + clientID)
if err != nil {
return
}
//status := client.Status
responseChannel := client.coAckChannel
workLength, _ := client.CurrentWork.Length(false)
client.Unlock()
if workLength > 0 {
logger.Error("Client %s wants to checkout work, but still has work: workLength=%d", clientID, workLength)
return nil, errors.New(e.ClientBusy)
}
isSuspended, err := client.GetSuspended(true)
if err != nil {
return
}
if isSuspended {
err = errors.New(e.ClientSuspended)
return
}
//if status == CLIENT_STAT_DELETED {
// qm.RemoveClient(client_id, false)
// return nil, errors.New(e.ClientDeleted)
//}
//req := CoReq{policy: req_policy, fromclient: client_id, available: available_bytes, count: num, response: client.coAckChannel}
req := CheckoutRequest{policy: reqPolicy, fromclient: clientID, available: availableBytes, count: num, response: responseChannel}
logger.Debug(3, "(CheckoutWorkunits) %s qm.coReq <- req", clientID)
// request workunit
//err = qm.requestQueue.Push(&req)
//if err != nil {
// logger.Error("Work request by client %s rejected, request queue is full", client_id)
// err = fmt.Errorf("Too many work requests - Please try again later")
// return
//}
select {
case qm.coReq <- req:
default:
logger.Error("Work request by client %s rejected, request queue is full", clientID)
err = fmt.Errorf("Too many work requests - Please try again later")
return
}
logger.Debug(3, "(CheckoutWorkunits) %s client.Get_Ack()", clientID)
//ack := <-qm.coAck
var ack CoAck
// get workunit
lock, err := client.RLockNamed("CheckoutWorkunits waiting for ack, clientID: " + clientID)
if err != nil {
return
}
ack, err = client.GetAck()
client.RUnlockNamed(lock)
logger.Debug(3, "(CheckoutWorkunits) %s got ack", clientID)
if err != nil {
return
}
logger.Debug(3, "(CheckoutWorkunits) %s got ack", clientID)
if ack.err != nil {
logger.Debug(3, "(CheckoutWorkunits) %s ack.err: %s", clientID, ack.err.Error())
return ack.workunits, ack.err
}
addedWork := 0
for _, work := range ack.workunits {
workID := work.Workunit_Unique_Identifier
//work_id, xerr := work.Workunit_Unique_Identifier// New_Workunit_Unique_Identifier_FromString(work.Id)
//if xerr != nil {
// return
//}
err = client.AssignedWork.Add(workID)
if err != nil {
return
}
addedWork++
}
//if added_work > 0 && status == CLIENT_STAT_ACTIVE_IDLE {
// client.Set_Status(CLIENT_STAT_ACTIVE_BUSY, true)
//}
logger.Debug(3, "(CheckoutWorkunits) %s finished", clientID)
return ack.workunits, ack.err
}
// GetWorkByID _
func (qm *CQMgr) GetWorkByID(id Workunit_Unique_Identifier) (workunit *Workunit, err error) {
workunit, ok, err := qm.workQueue.Get(id)
if err != nil {
return
}
if !ok {
var workStr string
workStr, err = id.String()
if err != nil {
err = fmt.Errorf("() workid.String() returned: %s", err.Error())
return
}
err = fmt.Errorf("no workunit found with id %s", workStr)
}
return
}
// NotifyWorkStatus _
func (qm *CQMgr) NotifyWorkStatus(notice Notice) {
qm.feedback <- notice
return
}
// when popWorks is called, the client should already be locked
func (qm *CQMgr) popWorks(req CheckoutRequest) (clientSpecificWorkunits []*Workunit, err error) {
clientID := req.fromclient
client, ok, err := qm.clientMap.Get(clientID, true) // locks the clientmap
if err != nil {
return
}
if !ok {
err = fmt.Errorf("(popWorks) Client %s not found", clientID)
return
}
logger.Debug(3, "(popWorks) starting for client: %s", clientID)
filtered, stats, err := qm.filterWorkByClient(client)
if err != nil {
err = fmt.Errorf("(popWorks) filterWorkByClient returned: %s", err.Error())
return
}
if len(filtered) == 0 {
var statJSONByte []byte
statJSONByte, err = json.Marshal(stats)
if err != nil {
statJSONByte = []byte("failed")
}
clientGroup := ""
clientGroup, err = client.GetGroup(false)
if err != nil {
clientGroup = ""
}
logger.Error("(popWorks) filterWorkByClient returned no workunits for client %s (%s), stats: %s", clientID, clientGroup, statJSONByte)
err = errors.New(e.NoEligibleWorkunitFound)
return
}
clientSpecificWorkunits, err = qm.workQueue.selectWorkunits(filtered, req.policy, req.available, req.count)
if err != nil {
err = fmt.Errorf("(popWorks) selectWorkunits returned: %s", err.Error())
return
}
//get workunits successfully, put them into coWorkMap
for _, work := range clientSpecificWorkunits {