-
Notifications
You must be signed in to change notification settings - Fork 23
/
plugin.go
1274 lines (1098 loc) · 39.1 KB
/
plugin.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
/*
* === This file is part of ALICE O² ===
*
* Copyright 2021 CERN and copyright holders of ALICE O².
* Author: Teo Mrnjavac <teo.mrnjavac@cern.ch>
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
* In applying this license CERN does not waive the privileges and
* immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
//go:generate protoc --go_out=. --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative --go-grpc_out=require_unimplemented_servers=false:. protos/dcs.proto
package dcs
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"strconv"
"strings"
"time"
"github.com/AliceO2Group/Control/common/logger/infologger"
"github.com/AliceO2Group/Control/common/runtype"
"github.com/AliceO2Group/Control/common/utils/uid"
"github.com/AliceO2Group/Control/core/environment"
"github.com/AliceO2Group/Control/core/integration"
dcspb "github.com/AliceO2Group/Control/core/integration/dcs/protos"
"github.com/AliceO2Group/Control/core/workflow/callable"
"github.com/imdario/mergo"
"github.com/spf13/viper"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
)
const (
DCS_DIAL_TIMEOUT = 2 * time.Hour
DCS_GENERAL_OP_TIMEOUT = 45 * time.Second
)
type Plugin struct {
dcsHost string
dcsPort int
dcsClient *RpcClient
pendingEORs map[string] /*envId*/ int64
}
type DCSDetectors []dcspb.Detector
func NewPlugin(endpoint string) integration.Plugin {
u, err := url.Parse(endpoint)
if err != nil {
log.WithField("endpoint", endpoint).
WithError(err).
Error("bad service endpoint")
return nil
}
portNumber, _ := strconv.Atoi(u.Port())
return &Plugin{
dcsHost: u.Hostname(),
dcsPort: portNumber,
dcsClient: nil,
pendingEORs: make(map[string]int64),
}
}
func (p *Plugin) GetName() string {
return "dcs"
}
func (p *Plugin) GetPrettyName() string {
return "DCS"
}
func (p *Plugin) GetEndpoint() string {
return viper.GetString("dcsServiceEndpoint")
}
func (p *Plugin) GetConnectionState() string {
if p == nil || p.dcsClient == nil {
return "UNKNOWN"
}
return p.dcsClient.conn.GetState().String()
}
func (p *Plugin) GetData(_ []any) string {
if p == nil || p.dcsClient == nil {
return ""
}
environmentIds := environment.ManagerInstance().Ids()
outMap := make(map[string]interface{})
outMap["partitions"] = p.partitionStatesForEnvs(environmentIds)
out, err := json.Marshal(outMap)
if err != nil {
return ""
}
return string(out[:])
}
func (p *Plugin) GetEnvironmentsData(environmentIds []uid.ID) map[uid.ID]string {
if p == nil || p.dcsClient == nil {
return nil
}
out := p.partitionStatesForEnvs(environmentIds)
return out
}
func (p *Plugin) GetEnvironmentsShortData(environmentIds []uid.ID) map[uid.ID]string {
return p.GetEnvironmentsData(environmentIds)
}
func (p *Plugin) partitionStatesForEnvs(envIds []uid.ID) map[uid.ID]string {
out := make(map[uid.ID]string)
for _, envId := range envIds {
if _, ok := p.pendingEORs[envId.String()]; ok {
out[envId] = "SOR SUCCESSFUL"
}
}
return out
}
func (p *Plugin) Init(instanceId string) error {
if p.dcsClient == nil {
cxt, cancel := context.WithCancel(context.Background())
p.dcsClient = NewClient(cxt, cancel, viper.GetString("dcsServiceEndpoint"))
if p.dcsClient == nil {
return fmt.Errorf("failed to connect to DCS service on %s", viper.GetString("dcsServiceEndpoint"))
}
in := &dcspb.SubscriptionRequest{
InstanceId: instanceId,
}
evStream, err := p.dcsClient.Subscribe(context.Background(), in, grpc.EmptyCallOption{})
if err != nil {
return fmt.Errorf("failed to subscribe to DCS service on %s, possible network issue or DCS gateway malfunction", viper.GetString("dcsServiceEndpoint"))
}
go func() {
for {
for {
if evStream == nil {
break
}
ev, streamErr := evStream.Recv()
if streamErr == io.EOF {
log.Info("unexpected EOF from DCS service, possible DCS gateway malfunction")
break
}
if streamErr != nil {
log.WithError(streamErr).
Error("stream error or bad event from DCS service, dropping stream")
time.Sleep(3 * time.Second)
break
}
log.WithField("event", ev.String()).Debug("received DCS event")
}
log.WithField("endpoint", viper.GetString("dcsServiceEndpoint")).
Info("DCS stream dropped, attempting reconnect")
evStream, err = p.dcsClient.Subscribe(context.Background(), in, grpc.EmptyCallOption{})
if err != nil {
log.WithField("endpoint", viper.GetString("dcsServiceEndpoint")).
WithError(err).
Warnf("failed to resubscribe to DCS service, possible network issue or DCS gateway malfunction")
time.Sleep(3 * time.Second)
} else {
log.WithField("endpoint", viper.GetString("dcsServiceEndpoint")).
WithField("level", infologger.IL_Support).
Info("successfully resubscribed to DCS service")
}
}
}()
}
if p.dcsClient == nil {
return fmt.Errorf("failed to start DCS client on %s", viper.GetString("dcsServiceEndpoint"))
}
log.Debug("DCS plugin initialized")
return nil
}
func (p *Plugin) ObjectStack(_ map[string]string, _ map[string]string) (stack map[string]interface{}) {
stack = make(map[string]interface{})
return stack
}
func (p *Plugin) CallStack(data interface{}) (stack map[string]interface{}) {
call, callOk := data.(*callable.Call)
if !callOk {
return
}
varStack := call.VarStack
envId, envOk := varStack["environment_id"]
if !envOk {
log.WithField("call", "PrepareForRun").
Error("cannot acquire environment ID")
return
}
stack = make(map[string]interface{})
stack["PrepareForRun"] = func() (out string) { // must formally return string even when we return nothing
var err error
callFailedStr := "DCS PrepareForRun call failed"
dcsDetectorsParam, ok := varStack["dcs_detectors"]
if !ok {
log.WithField("partition", envId).
WithField("call", "PrepareForRun").
Debug("empty DCS detectors list provided")
dcsDetectorsParam = "[\"NULL_DETECTOR\"]"
}
dcsDetectors, err := p.parseDetectors(dcsDetectorsParam)
if err != nil {
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("partition", envId).
WithField("call", "PrepareForRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
log.WithField("partition", envId).
WithField("level", infologger.IL_Ops).
Infof("performing DCS PFR for detectors: %s", strings.Join(dcsDetectors.EcsDetectorsSlice(), " "))
parameters, ok := varStack["dcs_sor_parameters"]
if !ok {
log.WithField("partition", envId).
WithField("call", "PrepareForRun").
Debug("no DCS SOR parameters set")
parameters = "{}"
}
argMap := make(map[string]string)
bytes := []byte(parameters)
err = json.Unmarshal(bytes, &argMap)
if err != nil {
err = fmt.Errorf("error processing DCS SOR parameters: %w", err)
log.WithError(err).
WithField("partition", envId).
WithField("level", infologger.IL_Ops).
WithField("call", "PrepareForRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
rt := dcspb.RunType_TECHNICAL
runTypeS, ok := varStack["run_type"]
if ok {
// a detector is defined in the var stack
// so we convert from the provided string to the correct enum value in common/runtype
intRt, err := runtype.RunTypeString(runTypeS)
if err == nil {
if intRt == runtype.COSMICS {
// special case for COSMICS runs: there is no DCS run type for it, so we send PHYSICS
rt = dcspb.RunType_PHYSICS
} else {
// the runType was correctly matched to the common/runtype enum, but since the DCS enum is
// kept compatible, we can directly convert the runtype.RunType to a dcspb.RunType enum value
rt = dcspb.RunType(intRt)
}
}
}
// Preparing the per-detector request payload
in := dcspb.PfrRequest{
RunType: rt,
PartitionId: envId,
Detectors: make([]*dcspb.DetectorOperationRequest, len(dcsDetectors)),
}
for i, dcsDet := range dcsDetectors {
ecsDet := dcsToEcsDetector(dcsDet)
perDetectorParameters, okParam := varStack[strings.ToLower(ecsDet)+"_dcs_sor_parameters"]
if !okParam {
log.WithField("partition", envId).
WithField("call", "PrepareForRun").
Debug("empty DCS detectors list provided")
perDetectorParameters = "{}"
}
detectorArgMap := make(map[string]string)
bytes = []byte(perDetectorParameters)
err = json.Unmarshal(bytes, &detectorArgMap)
if err != nil {
err = fmt.Errorf("error processing %s DCS SOR parameter map: %w", ecsDet, err)
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("partition", envId).
WithField("call", "PrepareForRun").
WithField("detector", ecsDet).
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
// Per-detector parameters override any general dcs_sor_parameters
err = mergo.Merge(&detectorArgMap, argMap)
if err != nil {
err = fmt.Errorf("error processing %s DCS SOR general parameters override: %w", dcsDet.String(), err)
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("partition", envId).
WithField("call", "PrepareForRun").
WithField("detector", ecsDet).
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
// We parse the consolidated per-detector payload for any defaultable parameters with value "default"
detectorArgMap = resolveDefaults(detectorArgMap, varStack, ecsDet,
log.WithField("partition", envId).
WithField("call", "PrepareForRun").
WithField("detector", ecsDet))
in.Detectors[i] = &dcspb.DetectorOperationRequest{
Detector: dcsDet,
ExtraParameters: detectorArgMap,
}
}
if p.dcsClient == nil {
err = fmt.Errorf("DCS plugin not initialized, PrepareForRun impossible")
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("endpoint", viper.GetString("dcsServiceEndpoint")).
WithField("partition", envId).
WithField("call", "PrepareForRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
if p.dcsClient.GetConnState() == connectivity.Shutdown {
err = fmt.Errorf("DCS client connection not available, PrepareForRun impossible")
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("endpoint", viper.GetString("dcsServiceEndpoint")).
WithField("partition", envId).
WithField("call", "PrepareForRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
var stream dcspb.Configurator_StartOfRunClient
timeout := callable.AcquireTimeout(DCS_GENERAL_OP_TIMEOUT, varStack, "PFR", envId)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
detectorStatusMap := make(map[dcspb.Detector]dcspb.DetectorState)
for _, v := range dcsDetectors {
detectorStatusMap[v] = dcspb.DetectorState_NULL_STATE
}
// Point of no return
// The gRPC call below is expected to return immediately, with any actual responses arriving subsequently via
// the response stream.
// Regardless of DCS SOR success or failure, once the StartOfRun call returns, an EndOfRun **must** be enqueued
// for later, either during STOP_ACTIVITY or cleanup.
stream, err = p.dcsClient.PrepareForRun(ctx, &in, grpc.EmptyCallOption{})
if err != nil {
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("endpoint", viper.GetString("dcsServiceEndpoint")).
WithField("partition", envId).
WithField("call", "PrepareForRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
var dcsEvent *dcspb.RunEvent
for {
if ctx.Err() != nil {
err = fmt.Errorf("DCS PrepareForRun context timed out (%s), any future DCS events are ignored", timeout.String())
break
}
dcsEvent, err = stream.Recv()
if errors.Is(err, io.EOF) { // correct stream termination
log.WithField("partition", envId).
Debug("DCS PFR event stream was closed from the DCS side (EOF)")
break // no more data
}
if errors.Is(err, context.DeadlineExceeded) {
log.WithError(err).
WithField("partition", envId).
WithField("timeout", timeout.String()).
Debug("DCS PFR timed out")
err = fmt.Errorf("DCS PFR timed out after %s: %w", timeout.String(), err)
break
}
if err != nil { // stream termination in case of general error
log.WithError(err).
WithField("partition", envId).
Warn("bad DCS PFR event received, any future DCS events are ignored")
break
}
if dcsEvent == nil {
log.WithField("partition", envId).
Warn("nil DCS PFR event received, skipping to next DCS event")
continue
}
if dcsEvent.GetState() == dcspb.DetectorState_SOR_FAILURE {
ecsDet := dcsToEcsDetector(dcsEvent.GetDetector())
logErr := fmt.Errorf("%s PFR failure event from DCS", ecsDet)
if err != nil {
logErr = fmt.Errorf("%v : %v", err, logErr)
}
log.WithError(logErr).
WithField("event", dcsEvent).
WithField("detector", ecsDet).
WithField("level", infologger.IL_Ops).
WithField("endpoint", viper.GetString("dcsServiceEndpoint")).
WithField("partition", envId).
WithField("call", "PrepareForRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = logErr.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
detectorStatusMap[dcsEvent.GetDetector()] = dcsEvent.GetState()
if dcsEvent.GetState() == dcspb.DetectorState_RUN_OK {
if dcsEvent.GetDetector() == dcspb.Detector_DCS {
log.WithField("event", dcsEvent).
WithField("partition", envId).
WithField("level", infologger.IL_Support).
Debug("DCS PFR completed successfully")
break
} else {
ecsDet := dcsToEcsDetector(dcsEvent.GetDetector())
log.WithField("partition", envId).
WithField("detector", ecsDet).
Debugf("DCS PFR for %s: received status %s", ecsDet, dcsEvent.GetState().String())
}
}
if dcsEvent.GetState() == dcspb.DetectorState_RUN_OK {
log.WithField("event", dcsEvent).
WithField("partition", envId).
WithField("level", infologger.IL_Support).
Info("ALIECS PFR operation : completed DCS PFR for ")
} else {
log.WithField("event", dcsEvent).
WithField("partition", envId).
WithField("level", infologger.IL_Devel).
Info("ALIECS PFR operation : processing DCS PFR for ")
}
}
dcsFailedEcsDetectors := make([]string, 0)
dcsopOk := true
for _, v := range dcsDetectors {
if detectorStatusMap[v] != dcspb.DetectorState_RUN_OK {
dcsopOk = false
dcsFailedEcsDetectors = append(dcsFailedEcsDetectors, dcsToEcsDetector(v))
}
}
if !dcsopOk {
logErr := fmt.Errorf("PFR failed for %s", strings.Join(dcsFailedEcsDetectors, ", "))
if err != nil {
if errors.Is(err, io.EOF) {
err = fmt.Errorf("DCS PFR stream unexpectedly terminated from DCS side before completion: %w", err)
}
logErr = fmt.Errorf("%v : %v", err, logErr)
}
log.WithError(logErr).
WithField("level", infologger.IL_Ops).
WithField("endpoint", viper.GetString("dcsServiceEndpoint")).
WithField("partition", envId).
WithField("call", "PrepareForRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = logErr.Error()
call.VarStack["__call_error"] = callFailedStr
}
return
}
stack["StartOfRun"] = func() (out string) { // must formally return string even when we return nothing
var err error
callFailedStr := "DCS StartOfRun call failed"
rn := varStack["run_number"]
var runNumber64 int64
runNumber64, err = strconv.ParseInt(rn, 10, 32)
if err != nil {
log.WithField("partition", envId).
WithField("call", "StartOfRun").
WithError(err).
Error("cannot acquire run number for DCS SOR")
}
dcsDetectorsParam, ok := varStack["dcs_detectors"]
if !ok {
log.WithField("partition", envId).
WithField("call", "StartOfRun").
WithField("run", runNumber64).
Debug("empty DCS detectors list provided")
dcsDetectorsParam = "[\"NULL_DETECTOR\"]"
}
dcsDetectors, err := p.parseDetectors(dcsDetectorsParam)
if err != nil {
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("partition", envId).
WithField("call", "StartOfRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
log.WithField("partition", envId).
WithField("level", infologger.IL_Ops).
WithField("run", runNumber64).
Infof("performing DCS SOR for detectors: %s", strings.Join(dcsDetectors.EcsDetectorsSlice(), " "))
parameters, ok := varStack["dcs_sor_parameters"]
if !ok {
log.WithField("partition", envId).
WithField("call", "StartOfRun").
Debug("no DCS SOR parameters set")
parameters = "{}"
}
argMap := make(map[string]string)
bytes := []byte(parameters)
err = json.Unmarshal(bytes, &argMap)
if err != nil {
err = fmt.Errorf("error processing DCS SOR parameters: %w", err)
log.WithError(err).
WithField("partition", envId).
WithField("level", infologger.IL_Ops).
WithField("call", "StartOfRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
rt := dcspb.RunType_TECHNICAL
runTypeS, ok := varStack["run_type"]
if ok {
// a detector is defined in the var stack
// so we convert from the provided string to the correct enum value in common/runtype
intRt, err := runtype.RunTypeString(runTypeS)
if err == nil {
if intRt == runtype.COSMICS {
// special case for COSMICS runs: there is no DCS run type for it, so we send PHYSICS
rt = dcspb.RunType_PHYSICS
} else {
// the runType was correctly matched to the common/runtype enum, but since the DCS enum is
// kept compatible, we can directly convert the runtype.RunType to a dcspb.RunType enum value
rt = dcspb.RunType(intRt)
}
}
}
// Preparing the per-detector request payload
in := dcspb.SorRequest{
RunType: rt,
RunNumber: int32(runNumber64),
Detectors: make([]*dcspb.DetectorOperationRequest, len(dcsDetectors)),
}
for i, dcsDet := range dcsDetectors {
ecsDet := dcsToEcsDetector(dcsDet)
perDetectorParameters, okParam := varStack[strings.ToLower(ecsDet)+"_dcs_sor_parameters"]
if !okParam {
log.WithField("partition", envId).
WithField("run", runNumber64).
WithField("call", "StartOfRun").
Debug("empty DCS detectors list provided")
perDetectorParameters = "{}"
}
detectorArgMap := make(map[string]string)
bytes := []byte(perDetectorParameters)
err = json.Unmarshal(bytes, &detectorArgMap)
if err != nil {
err = fmt.Errorf("error processing %s DCS SOR parameter map: %w", ecsDet, err)
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("partition", envId).
WithField("call", "StartOfRun").
WithField("detector", ecsDet).
WithField("run", runNumber64).
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
// Per-detector parameters override any general dcs_sor_parameters
err = mergo.Merge(&detectorArgMap, argMap)
if err != nil {
err = fmt.Errorf("error processing %s DCS SOR general parameters override: %w", dcsDet.String(), err)
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("partition", envId).
WithField("call", "StartOfRun").
WithField("detector", ecsDet).
WithField("run", runNumber64).
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
// We parse the consolidated per-detector payload for any defaultable parameters with value "default"
detectorArgMap = resolveDefaults(detectorArgMap, varStack, ecsDet,
log.WithField("partition", envId).
WithField("call", "StartOfRun").
WithField("detector", ecsDet).
WithField("run", runNumber64))
in.Detectors[i] = &dcspb.DetectorOperationRequest{
Detector: dcsDet,
ExtraParameters: detectorArgMap,
}
}
if p.dcsClient == nil {
err = fmt.Errorf("DCS plugin not initialized, StartOfRun impossible")
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("endpoint", viper.GetString("dcsServiceEndpoint")).
WithField("run", runNumber64).
WithField("partition", envId).
WithField("call", "StartOfRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
if p.dcsClient.GetConnState() == connectivity.Shutdown {
err = fmt.Errorf("DCS client connection not available, StartOfRun impossible")
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("endpoint", viper.GetString("dcsServiceEndpoint")).
WithField("run", runNumber64).
WithField("partition", envId).
WithField("call", "StartOfRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
var stream dcspb.Configurator_StartOfRunClient
timeout := callable.AcquireTimeout(DCS_GENERAL_OP_TIMEOUT, varStack, "SOR", envId)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
detectorStatusMap := make(map[dcspb.Detector]dcspb.DetectorState)
for _, v := range dcsDetectors {
detectorStatusMap[v] = dcspb.DetectorState_NULL_STATE
}
// Point of no return
// The gRPC call below is expected to return immediately, with any actual responses arriving subsequently via
// the response stream.
// Regardless of DCS SOR success or failure, once the StartOfRun call returns, an EndOfRun **must** be enqueued
// for later, either during STOP_ACTIVITY or cleanup.
stream, err = p.dcsClient.StartOfRun(ctx, &in, grpc.EmptyCallOption{})
if err != nil {
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("endpoint", viper.GetString("dcsServiceEndpoint")).
WithField("run", runNumber64).
WithField("partition", envId).
WithField("call", "StartOfRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
p.pendingEORs[envId] = runNumber64 // make sure the corresponding EOR runs sooner or later
var dcsEvent *dcspb.RunEvent
for {
if ctx.Err() != nil {
err = fmt.Errorf("DCS StartOfRun context timed out (%s), any future DCS events are ignored", timeout.String())
break
}
dcsEvent, err = stream.Recv()
if errors.Is(err, io.EOF) { // correct stream termination
log.WithField("partition", envId).
WithField("run", runNumber64).
Debug("DCS SOR event stream was closed from the DCS side (EOF)")
break // no more data
}
if errors.Is(err, context.DeadlineExceeded) {
log.WithError(err).
WithField("partition", envId).
WithField("run", runNumber64).
WithField("timeout", timeout.String()).
Debug("DCS SOR timed out")
err = fmt.Errorf("DCS SOR timed out after %s: %w", timeout.String(), err)
break
}
if err != nil { // stream termination in case of general error
log.WithError(err).
WithField("partition", envId).
WithField("run", runNumber64).
Warn("bad DCS SOR event received, any future DCS events are ignored")
break
}
if dcsEvent == nil {
log.WithField("partition", envId).
WithField("run", runNumber64).
Warn("nil DCS SOR event received, skipping to next DCS event")
continue
}
if dcsEvent.GetState() == dcspb.DetectorState_SOR_FAILURE {
ecsDet := dcsToEcsDetector(dcsEvent.GetDetector())
logErr := fmt.Errorf("%s SOR failure event from DCS", ecsDet)
if err != nil {
logErr = fmt.Errorf("%v : %v", err, logErr)
}
log.WithError(logErr).
WithField("event", dcsEvent).
WithField("detector", ecsDet).
WithField("level", infologger.IL_Ops).
WithField("endpoint", viper.GetString("dcsServiceEndpoint")).
WithField("run", runNumber64).
WithField("partition", envId).
WithField("call", "StartOfRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = logErr.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
detectorStatusMap[dcsEvent.GetDetector()] = dcsEvent.GetState()
if dcsEvent.GetState() == dcspb.DetectorState_RUN_OK {
if dcsEvent.GetDetector() == dcspb.Detector_DCS {
log.WithField("event", dcsEvent).
WithField("partition", envId).
WithField("run", runNumber64).
WithField("level", infologger.IL_Support).
Debug("DCS SOR completed successfully")
p.pendingEORs[envId] = runNumber64
break
} else {
ecsDet := dcsToEcsDetector(dcsEvent.GetDetector())
log.WithField("partition", envId).
WithField("run", runNumber64).
WithField("detector", ecsDet).
Debugf("DCS SOR for %s: received status %s", ecsDet, dcsEvent.GetState().String())
}
}
if dcsEvent.GetState() == dcspb.DetectorState_RUN_OK {
log.WithField("event", dcsEvent).
WithField("partition", envId).
WithField("level", infologger.IL_Support).
WithField("run", runNumber64).
Info("ALIECS SOR operation : completed DCS SOR for ")
} else {
log.WithField("event", dcsEvent).
WithField("partition", envId).
WithField("level", infologger.IL_Devel).
WithField("run", runNumber64).
Info("ALIECS SOR operation : processing DCS SOR for ")
}
}
dcsFailedEcsDetectors := make([]string, 0)
dcsopOk := true
for _, v := range dcsDetectors {
if detectorStatusMap[v] != dcspb.DetectorState_RUN_OK {
dcsopOk = false
dcsFailedEcsDetectors = append(dcsFailedEcsDetectors, dcsToEcsDetector(v))
}
}
if dcsopOk {
p.pendingEORs[envId] = runNumber64
} else {
logErr := fmt.Errorf("SOR failed for %s, DCS EOR will run anyway for this run", strings.Join(dcsFailedEcsDetectors, ", "))
if err != nil {
if errors.Is(err, io.EOF) {
err = fmt.Errorf("DCS SOR stream unexpectedly terminated from DCS side before completion: %w", err)
}
logErr = fmt.Errorf("%v : %v", err, logErr)
}
log.WithError(logErr).
WithField("level", infologger.IL_Ops).
WithField("endpoint", viper.GetString("dcsServiceEndpoint")).
WithField("run", runNumber64).
WithField("partition", envId).
WithField("call", "StartOfRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = logErr.Error()
call.VarStack["__call_error"] = callFailedStr
}
return
}
eorFunc := func(runNumber64 int64) (out string) { // must formally return string even when we return nothing
callFailedStr := "DCS EndOfRun call failed"
dcsDetectorsParam, ok := varStack["dcs_detectors"]
if !ok {
log.WithField("partition", envId).
WithField("run", runNumber64).
Debug("empty DCS detectors list provided")
dcsDetectorsParam = "[\"NULL_DETECTOR\"]"
}
dcsDetectors, err := p.parseDetectors(dcsDetectorsParam)
if err != nil {
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("partition", envId).
WithField("call", "EndOfRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
log.WithField("partition", envId).
WithField("level", infologger.IL_Ops).
WithField("run", runNumber64).
Infof("performing DCS EOR for detectors: %s", strings.Join(dcsDetectors.EcsDetectorsSlice(), " "))
parameters, ok := varStack["dcs_eor_parameters"]
if !ok {
log.WithField("partition", envId).
Debug("no DCS EOR parameters set")
parameters = "{}"
}
argMap := make(map[string]string)
bytes := []byte(parameters)
err = json.Unmarshal(bytes, &argMap)
if err != nil {
err = fmt.Errorf("error processing DCS EOR parameters: %w", err)
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("partition", envId).
WithField("call", "EndOfRun").
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
// Preparing the per-detector request payload
in := dcspb.EorRequest{
RunNumber: int32(runNumber64),
Detectors: make([]*dcspb.DetectorOperationRequest, len(dcsDetectors)),
}
for i, dcsDet := range dcsDetectors {
ecsDet := dcsToEcsDetector(dcsDet)
perDetectorParameters, okParam := varStack[strings.ToLower(ecsDet)+"_dcs_eor_parameters"]
if !okParam {
log.WithField("partition", envId).
WithField("run", runNumber64).
Debug("empty DCS detectors list provided")
perDetectorParameters = "{}"
}
detectorArgMap := make(map[string]string)
bytes := []byte(perDetectorParameters)
err = json.Unmarshal(bytes, &detectorArgMap)
if err != nil {
err = fmt.Errorf("error processing %s DCS EOR parameter map: %w", dcsDet.String(), err)
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("partition", envId).
WithField("call", "EndOfRun").
WithField("detector", ecsDet).
WithField("run", runNumber64).
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
// Per-detector parameters override any general dcs_eor_parameters
err = mergo.Merge(&detectorArgMap, argMap)
if err != nil {
err = fmt.Errorf("error processing %s DCS EOR general parameters override: %w", dcsDet.String(), err)
log.WithError(err).
WithField("level", infologger.IL_Ops).
WithField("partition", envId).
WithField("call", "EndOfRun").
WithField("detector", ecsDet).
WithField("run", runNumber64).
Error("DCS error")
call.VarStack["__call_error_reason"] = err.Error()
call.VarStack["__call_error"] = callFailedStr
return
}
in.Detectors[i] = &dcspb.DetectorOperationRequest{
Detector: dcsDet,
ExtraParameters: detectorArgMap,
}
}
if p.dcsClient == nil {
err = fmt.Errorf("DCS plugin not initialized, EndOfRun impossible")