-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorborus.go
More file actions
executable file
·5083 lines (4246 loc) · 156 KB
/
orborus.go
File metadata and controls
executable file
·5083 lines (4246 loc) · 156 KB
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 main
/*
Orborus exists to listen for new jobs from Shuffle. This is to run workflows, pipelines, and other tasks.
*/
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/shuffle/shuffle-shared"
"github.com/shirou/gopsutil/v3/process"
"math/rand"
//"os/signal"
//"syscall"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/go-connections/nat"
//"github.com/docker/docker/api/types/filters"
dockerclient "github.com/docker/docker/client"
uuid "github.com/satori/go.uuid"
//"github.com/mackerelio/go-osstat/disk"
//"github.com/mackerelio/go-osstat/memory"
//"github.com/shirou/gopsutil/cpu"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
)
// Starts jobs in bulk, so this could be increased or decreased based on who the user is
var sleepTime = 2
// Making it work on low-end machines even during busy times :)
// May cause some things to run slowly
var maxConcurrency = 25
// Timeout if something rashes
var workerTimeoutEnv = os.Getenv("SHUFFLE_ORBORUS_EXECUTION_TIMEOUT")
var concurrencyEnv = os.Getenv("SHUFFLE_ORBORUS_EXECUTION_CONCURRENCY")
var appSdkVersion = os.Getenv("SHUFFLE_APP_SDK_VERSION")
var workerVersion = os.Getenv("SHUFFLE_WORKER_VERSION")
var newWorkerImage = os.Getenv("SHUFFLE_WORKER_IMAGE")
var dockerSwarmBridgeMTU = os.Getenv("SHUFFLE_SWARM_BRIDGE_DEFAULT_MTU")
var dockerSwarmBridgeInterface = os.Getenv("SHUFFLE_SWARM_BRIDGE_DEFAULT_INTERFACE")
var maxCPUPercent = 90
// Kubernetes settings
var isKubernetes = os.Getenv("IS_KUBERNETES")
var kubernetesNamespace = os.Getenv("KUBERNETES_NAMESPACE")
var workerServiceAccountName = os.Getenv("SHUFFLE_WORKER_SERVICE_ACCOUNT_NAME")
var workerPodSecurityContext = os.Getenv("SHUFFLE_WORKER_POD_SECURITY_CONTEXT")
var workerContainerSecurityContext = os.Getenv("SHUFFLE_WORKER_CONTAINER_SECURITY_CONTEXT")
var appServiceAccountName = os.Getenv("SHUFFLE_APP_SERVICE_ACCOUNT_NAME")
var appPodSecurityContext = os.Getenv("SHUFFLE_APP_POD_SECURITY_CONTEXT")
var appContainerSecurityContext = os.Getenv("SHUFFLE_APP_CONTAINER_SECURITY_CONTEXT")
var debug = os.Getenv("DEBUG") == "true"
// var baseimagename = "docker.pkg.github.com/shuffle/shuffle"
// var baseimagename = "ghcr.io/frikky"
// var baseimagename = "shuffle/shuffle"
var baseimageregistry = os.Getenv("SHUFFLE_BASE_IMAGE_REGISTRY")
var baseimagename = os.Getenv("SHUFFLE_BASE_IMAGE_NAME")
//var baseimagetagsuffix = os.Getenv("SHUFFLE_BASE_IMAGE_TAG_SUFFIX")
// Used for cloud with auth. Onprem in certain cases too.
var auth = os.Getenv("AUTH")
var org = os.Getenv("ORG")
// var orgId = os.Getenv("ORG_ID")
var baseUrl = os.Getenv("BASE_URL")
var workerServerUrl = os.Getenv("SHUFFLE_WORKER_SERVER_URL")
var environment = os.Getenv("ENVIRONMENT_NAME")
var dockerApiVersion = os.Getenv("DOCKER_API_VERSION")
var runningMode = strings.ToLower(os.Getenv("RUNNING_MODE"))
var cleanupEnv = strings.ToLower(os.Getenv("CLEANUP"))
var timezone = os.Getenv("TZ")
var containerName = os.Getenv("ORBORUS_CONTAINER_NAME")
var swarmConfig = os.Getenv("SHUFFLE_SWARM_CONFIG")
var swarmNetworkName = os.Getenv("SHUFFLE_SWARM_NETWORK_NAME")
var orborusLabel = os.Getenv("SHUFFLE_ORBORUS_LABEL")
var memcached = os.Getenv("SHUFFLE_MEMCACHED")
var queuePerMinute = os.Getenv("SHUFFLE_EXECUTION_PER_MINIUTE")
var queuePerMinuteInt int
// Used to download file categories. Not required since 2.1.1
var pipelineApikey = ""
var pipelineUrl = os.Getenv("SHUFFLE_PIPELINE_URL")
var executionIds = []string{}
var pipelines = []shuffle.PipelineInfo{}
var namespacemade = false // For K8s
var skipPipelineMount = false
var tenzirDisabled = false
var dockercli *dockerclient.Client
var containerId string
var executionCount = 0
var orborusUuid = os.Getenv("SHUFFLE_ORBORUS_UUID")
var imagedownloadTimeout = time.Second * 300
var window = shuffle.NewTimeWindow(1 * time.Minute)
func init() {
var err error
// Look for argc/argv and map environment variables
sensorMode := false
for _, arg := range os.Args {
if !strings.HasPrefix(arg, "--") {
continue
}
// Split away =
value := ""
if strings.Contains(arg, "=") {
newArg := strings.Split(arg, "=")[0]
value = strings.Split(arg, "=")[1]
arg = newArg
} else {
continue
}
if len(value) == 0 {
continue
}
parsedArg := strings.TrimPrefix(arg, "--")
parsedArg = strings.ReplaceAll(strings.ToUpper(parsedArg), " ", "_")
if !strings.HasPrefix(parsedArg, "SHUFFLE_") {
parsedArg = "SHUFFLE_" + parsedArg
}
if parsedArg == "SHUFFLE_SENSOR_MODE" {
parsedArg = "SHUFFLE_AGENT_SENSOR_MODE"
} else if parsedArg == "SHUFFLE_AGENT_MODE" {
parsedArg = "SHUFFLE_AGENT_SENSOR_MODE"
}
if parsedArg == "SHUFFLE_AGENT_SENSOR_MODE" && strings.ToLower(value) == "true" {
sensorMode = true
}
os.Setenv(parsedArg, value)
}
if sensorMode {
log.Printf("[INFO] Enabling sensormode (init check)")
for _, arg := range os.Args {
if !strings.HasPrefix(arg, "--") {
continue
}
// Split away =
value := ""
if strings.Contains(arg, "=") {
newArg := strings.Split(arg, "=")[0]
value = strings.Split(arg, "=")[1]
arg = newArg
} else {
continue
}
if len(value) == 0 {
continue
}
arg = strings.TrimPrefix(arg, "--")
if arg == "queue" {
os.Setenv("ENVIRONMENT_NAME", value)
environment = value
} else if arg == "auth" {
os.Setenv("AUTH", value)
auth = value
} else if arg == "org_id" {
os.Setenv("ORG", value)
org = value
} else if arg == "base_url" {
os.Setenv("BASE_URL", value)
baseUrl = value
}
}
} else {
// dockercli, err = dockerclient.NewEnvClient()
dockercli, dockerApiVersion, err = shuffle.GetDockerClient()
if err != nil {
log.Printf("Unable to create docker client: %s", err)
}
if os.Getenv("SHUFFLE_EC2_INSTANCE") == "true" {
log.Printf("[INFO] Detected AWS EC2 instance. Setting up Docker Swarm with AWS optimizations.")
containers, err := dockercli.ContainerList(context.Background(), container.ListOptions{})
if err == nil {
for _, container := range containers {
if strings.Contains(container.Image, "shuffle-orborus") {
if len(container.Names) != 0 {
if strings.Contains(container.Names[0], "shuffle-orborus") {
containerName = container.Names[0]
containerName = strings.TrimPrefix(containerName, "/")
os.Setenv("ORBORUS_CONTAINER_NAME", containerName)
log.Printf("[DEBUG] Found orborus container name: %s", containerName)
break
}
}
}
}
} else {
log.Printf("[ERROR] Failed to find orborus container: %s", err)
}
}
getThisContainerId()
if len(pipelineApikey) == 0 {
if len(os.Getenv("SHUFFLE_AUTHORIZATION")) > 0 {
log.Printf("[DEBUG] No pipeline API key found. Overriding with api key from SHUFFLE_AUTHORIZATION")
pipelineApikey = os.Getenv("SHUFFLE_AUTHORIZATION")
os.Setenv("SHUFFLE_PIPELINE_AUTH", pipelineApikey)
}
}
}
}
// form id of current running container
func getThisContainerId() {
fCol := ""
// some adjusting based on current running mode
switch runningMode {
case "kubernetes":
// cgroup will be like:
// 11:net_cls,net_prio:/kubepods/besteffort/podf132b44d-cfcf-43f7-9906-79f58e268333/851466f8b5ed5aa0f265b1c95c6d2bafbc51a38dd5c5a1621b6e586572150009
fCol = "5"
log.Printf("[INFO] Running containerized in Kubernetes!")
case "docker":
// cgroup will be like:
// 12:perf_event:/docker/0f06810364f52a2cd6e80bfba27419cb8a29758a204cd676388f4913bb366f2b
fCol = "3"
log.Printf("[INFO] Running containerized in Docker!")
default:
fCol = "3" // for backward-compatibility with production
log.Printf("[WARNING] RUNNING_MODE not set - defaulting to Docker (NOT Kubernetes).")
}
if fCol != "" {
cmd := fmt.Sprintf("cat /proc/self/cgroup | grep memory | tail -1 | cut -d/ -f%s | grep -o -E '[0-9A-z]{64}'", fCol)
out, err := exec.Command("bash", "-c", cmd).Output()
if err == nil {
containerId = strings.TrimSpace(string(out))
log.Printf("[DEBUG] Set containerId network to %s", containerId)
// cgroup error. Use fallback strategy below.
// https://github.com/moby/moby/issues/7015
//log.Printf("Checking if %s is in %s", ".scope", string(out))
if strings.Contains(string(out), ".scope") {
log.Printf("[DEBUG] ContainerId contains scope. setting to empty.")
containerId = ""
//docker-76c537e9a4b7c7233011f5d70e6b7f2d600b6413ac58a96519b8dca7a3f7117a.scope
}
} else {
log.Printf("[WARNING] Failed getting container ID: %s", err)
}
}
if containerId == "" {
if containerName != "" {
containerId = containerName
log.Printf("[INFO] Falling back to ORBORUS_CONTAINER_NAME as container ID")
} else {
containerId = "shuffle-orborus"
log.Printf(`[WARNING] ORBORUS_CONTAINER_NAME env is not set. Falling back to default name "%s" as container ID. This may cause issues on the same server`, containerId)
}
}
log.Printf(`[INFO] Started with containerId "%s"`, containerId)
}
func skipCheckInCleanup(name string) bool {
return strings.HasPrefix(name, "backend") ||
strings.HasPrefix(name, "shuffle-backend") ||
strings.HasPrefix(name, "frontend") ||
strings.HasPrefix(name, "shuffle-frontend") ||
strings.HasPrefix(name, "orborus") ||
strings.HasPrefix(name, "shuffle-orborus") ||
strings.HasPrefix(name, "opensearch") ||
strings.HasPrefix(name, "shuffle-opensearch") ||
strings.HasPrefix(name, "memcached") ||
strings.HasPrefix(name, "shuffle-memcached")
}
func cleanupExistingNodes(ctx context.Context) error {
if cleanupEnv != "true" {
log.Printf("[INFO] Skipping cleanup of existing workers as CLEANUP is NOT set to true. Swarm actions are being auto-discovered during executions then instead.")
return nil
}
if isKubernetes == "true" {
// Cleanup all workers created by orborus and all apps created by workers.
if kubernetesNamespace == "" {
kubernetesNamespace = "default"
}
clientset, _, err := shuffle.GetKubernetesClient()
if err != nil {
log.Printf("[ERROR] Error getting kubernetes client:", err)
return err
}
// Delete all services
services, err := clientset.CoreV1().Services(kubernetesNamespace).List(context.Background(), metav1.ListOptions{
LabelSelector: "app.kubernetes.io/name in (shuffle-worker, shuffle-app),app.kubernetes.io/managed-by in (shuffle-orborus, shuffle-worker)",
})
if err != nil {
log.Printf("[ERROR] Failed listing services: %s", err)
return err
}
for _, service := range services.Items {
err := clientset.CoreV1().Services(kubernetesNamespace).Delete(context.Background(), service.Name, metav1.DeleteOptions{})
if err != nil {
log.Printf("[ERROR] Failed deleting service %s: %s", service.Name, err)
}
}
deployments, err := clientset.AppsV1().Deployments(kubernetesNamespace).List(context.Background(), metav1.ListOptions{
LabelSelector: "app.kubernetes.io/name in (shuffle-worker, shuffle-app),app.kubernetes.io/managed-by in (shuffle-orborus, shuffle-worker)",
})
if err != nil {
log.Printf("[ERROR] Failed listing deployments: %s", err)
return err
}
for _, deployment := range deployments.Items {
err := clientset.AppsV1().Deployments(kubernetesNamespace).Delete(context.Background(), deployment.Name, metav1.DeleteOptions{})
if err != nil {
log.Printf("[ERROR] Failed deleting deployment %s: %s", deployment.Name, err)
}
}
log.Printf("[INFO] Cleaned up all services and deployments in namespace %s. Waiting 10 seconds for cleanup to reflect", kubernetesNamespace)
time.Sleep(10 * time.Second)
return nil
}
serviceListOptions := types.ServiceListOptions{}
services, err := dockercli.ServiceList(
context.Background(),
serviceListOptions,
)
if err != nil {
log.Printf("[DEBUG] Failed finding containers: %s", err)
return err
}
//log.Printf("\n\nFound %d contaienrs", len(services))
for _, service := range services {
//portFound := false
//for _, endpoint := range service.Spec.EndpointSpec.Ports {
// if strings.Contains(endpoint.Name, "port") {
// //portFound = true
// }
//}
if strings.Contains(service.Spec.Annotations.Name, "opensearch") {
continue
}
if strings.Contains(service.Spec.TaskTemplate.ContainerSpec.Image, "shuffle") {
if !strings.Contains(service.Spec.TaskTemplate.ContainerSpec.Image, "shuffle-frontend") &&
!strings.Contains(service.Spec.TaskTemplate.ContainerSpec.Image, "shuffle-backend") &&
!strings.Contains(service.Spec.TaskTemplate.ContainerSpec.Image, "shuffle-orborus") {
err = dockercli.ServiceRemove(ctx, service.ID)
if err != nil {
log.Printf("[DEBUG] Failed to remove service %s", service.Spec.Annotations.Name)
} else {
log.Printf("[DEBUG] Removed service %#v", service.Spec.TaskTemplate.ContainerSpec.Image)
}
}
}
}
return nil
}
func deployServiceWorkers(image string) {
log.Printf("[DEBUG] Validating deployment of workers as services IF swarmConfig = run (value: %#v)", swarmConfig)
if swarmConfig != "run" && swarmConfig != "swarm" {
log.Printf("[DEBUG] Skipping deployment of workers as services as swarmConfig is not set to run or swarm. Value: %#v", swarmConfig)
return
}
ctx := context.Background()
// Looks for and cleans up all existing items in swarm we can't re-use (Shuffle only)
// frikky@debian:~/git/shuffle/functions/onprem/worker$ docker service create --replicas 5 --name shuffle-workers --env SHUFFLE_SWARM_CONFIG=run --publish published=33333,target=33333 ghcr.io/shuffle/shuffle-worker:nightly
// Get a list of network interfaces
interfaces, err := net.Interfaces()
if err != nil {
log.Printf("[ERROR] Failed to get network interfaces: %s", err)
}
mtu := 1500
if len(dockerSwarmBridgeMTU) == 0 {
mtu, err = strconv.Atoi(dockerSwarmBridgeMTU) // by default
if err != nil {
if debug {
log.Printf("[DEBUG] Failed to convert the default MTU to int: %s. Using 1500 instead. Input: %s", err, dockerSwarmBridgeMTU)
}
mtu = 1500
}
}
bridgeName := dockerSwarmBridgeInterface
if bridgeName == "" {
bridgeName = "eth0"
}
// Check if there is at least one interface
if len(interfaces) < 2 {
// this assumes that the machine should have at least 2 network
// interfaces. If not, we will use the default MTU.
// interface 1 is the loopback interface
// interface 2 is eth0, The eth0 interface inside a
// Docker container corresponds to the virtual Ethernet
// interface that connects the container to the docker0
log.Printf("[ERROR] Failed to get enough network interfaces")
} else {
// Get the preferred interface
for _, iface := range interfaces {
if strings.Contains(iface.Name, bridgeName) {
targetInterface := iface
mtu = targetInterface.MTU
log.Printf("[INFO] Using MTU %d from interface %s", mtu, targetInterface.Name)
break
}
}
}
// Create the network options with the specified MTU
options := make(map[string]string)
options["com.docker.network.driver.mtu"] = fmt.Sprintf("%d", mtu)
ingressOptions := network.CreateOptions{
Driver: "overlay",
Attachable: false,
Ingress: true,
IPAM: &network.IPAM{
Driver: "default",
Config: []network.IPAMConfig{
network.IPAMConfig{
Subnet: "10.225.225.0/24",
Gateway: "10.225.225.1",
},
},
},
}
_, err = dockercli.NetworkCreate(
ctx,
"ingress",
ingressOptions,
)
if err != nil {
log.Printf("[WARNING] Ingress network may already exist: %s", err)
}
//docker network create --driver=overlay workers
// Specific subnet?
networkName := "shuffle_swarm_executions"
if len(swarmNetworkName) > 0 {
networkName = swarmNetworkName
}
networkCreateOptions := network.CreateOptions{
Driver: "overlay",
Options: options,
Attachable: true,
Ingress: false,
IPAM: &network.IPAM{
Driver: "default",
Config: []network.IPAMConfig{
network.IPAMConfig{
Subnet: "10.224.224.0/24",
Gateway: "10.224.224.1",
},
},
},
}
_, err = dockercli.NetworkCreate(
ctx,
networkName,
networkCreateOptions,
)
if err != nil {
if strings.Contains(fmt.Sprintf("%s", err), "already exists") {
// Try patching for attachable
if debug {
log.Printf("[DEBUG] Network %s already exists", networkName)
}
} else {
log.Printf("[DEBUG] Failed to create network %s for workers: %s. This is not critical, and containers will still be added", networkName, err)
}
}
networkID := ""
// find network ID
networks, err := dockercli.NetworkList(ctx, network.ListOptions{})
if err == nil {
for _, net := range networks {
if net.Name == networkName {
if net.Scope == "swarm" {
log.Printf("[DEBUG] Found swarm-scoped network: %s (%s)", networkName, net.ID)
networkID = net.ID
} else {
log.Printf("[WARNING] Network %s exists but is not swarm scoped (scope=%s)", networkName, net.Scope)
}
break
}
}
}
/*
isMemcachedRunning, err := checkMemcached(ctx, dockercli)
if err != nil {
log.Printf("[ERROR] Failed checking memcached: %s", err)
}
if isMemcachedRunning == false {
log.Printf("[ERROR] Memcached is not running. Will try to deploy it.")
deployMemcached(dockercli)
}
ip := "shuffle-cache"
if len(os.Getenv("SHUFFLE_MEMCACHED")) == 0 {
os.Setenv("SHUFFLE_MEMCACHED", fmt.Sprintf("%s:11211", ip))
}
*/
if networkID == "" {
log.Printf("[ERROR] Network %s does not exist", networkName)
networkID = networkName
}
defaultNetworkAttach := false
if containerId != "" {
log.Printf("[DEBUG] Should connect orborus container to worker network as it's running in Docker with name %#v!", containerId)
// https://pkg.go.dev/github.com/docker/docker@v20.10.12+incompatible/api/types/network#EndpointSettings
networkConfig := &network.EndpointSettings{}
err := dockercli.NetworkConnect(ctx, networkID, containerId, networkConfig)
if err != nil {
log.Printf("[ERROR] Failed connecting Orborus to docker network %s: %s", networkName, err)
}
if len(containerId) == 64 && baseUrl == "http://shuffle-backend:5001" {
log.Printf("[WARNING] Network MAY not work due to backend being %s and container length 64. Will try to attach shuffle_shuffle network", baseUrl)
defaultNetworkAttach = true
}
}
if len(os.Getenv("DOCKER_HOST")) > 0 {
log.Printf("[DEBUG] Deploying docker socket proxy to the network %s as the DOCKER_HOST variable is set", networkName)
listOptions := container.ListOptions{
All: true,
}
containers, err := dockercli.ContainerList(ctx, listOptions)
if err == nil {
for _, container := range containers {
if strings.Contains(strings.ToLower(container.Image), "docker-socket-proxy") {
networkConfig := &network.EndpointSettings{}
err := dockercli.NetworkConnect(ctx, networkID, container.ID, networkConfig)
if err != nil {
log.Printf("[ERROR] Failed connecting Docker socket proxy to docker network %s: %s", networkName, err)
} else {
log.Printf("[INFO] Attached the docker socket proxy to the execution network")
}
break
}
}
} else {
log.Printf("[ERROR] Failed listing containers when deploying socket proxy on swarm: %s", err)
}
//} else {
// log.Printf("[ERROR] Failed listing and finding the right image for docker socket proxy: %s", err)
//}
}
// Running 2 by default instead of 1. Higher scale mechanisms - es
replicas := uint64(1)
scaleReplicas := os.Getenv("SHUFFLE_SCALE_REPLICAS")
if len(scaleReplicas) > 0 {
tmpInt, err := strconv.Atoi(scaleReplicas)
if err != nil {
log.Printf("[ERROR] %s is not a valid number for replication", scaleReplicas)
} else {
replicas = uint64(tmpInt)
}
log.Printf("[DEBUG] SHUFFLE_SCALE_REPLICAS set to value %#v. Trying to overwrite default (%d/node)", scaleReplicas, replicas)
}
innerContainerName := fmt.Sprintf("shuffle-workers")
cnt, err := findActiveSwarmNodes()
if err != nil {
log.Printf("[ERROR] Failed to find active swarm nodes: %s. Defaulting to 1", err)
}
nodeCount := uint64(1)
if cnt > 0 {
nodeCount = uint64(cnt)
}
appReplicas := os.Getenv("SHUFFLE_APP_REPLICAS")
appReplicaCnt := 2
if len(appReplicas) > 0 {
newCnt, err := strconv.Atoi(appReplicas)
if err != nil {
log.Printf("[ERROR] %s is not a valid number for SHUFFLE_APP_REPLICAS", appReplicas)
} else {
appReplicaCnt = newCnt
}
}
log.Printf("[DEBUG] Found %d node(s) to replicate over. Defaulting to 1 IF we can't auto-discover them.", cnt)
// FIXME: From September 2025 - This is set back to 1, as this doesn't really reflect how scale works at all. It is just confusing, and makes number larger/smaller "arbitrarily" instead of using default docker scale
nodeCount = 1
replicatedJobs := uint64(replicas * nodeCount)
log.Printf("[DEBUG] Deploying %d container(s) for worker with swarm to each node. Service name: %s. Image: %s", replicas, innerContainerName, image)
if timezone == "" {
timezone = "Europe/Amsterdam"
}
// FIXME: May not need ingress ports. Could use internal services and DNS of swarm itself
// https://github.com/moby/moby/blob/e2f740de442bac52b280bc485a3ca5b31567d938/api/types/swarm/service.go#L46
serviceSpec := swarm.ServiceSpec{
Annotations: swarm.Annotations{
Name: innerContainerName,
Labels: map[string]string{},
},
Mode: swarm.ServiceMode{
Replicated: &swarm.ReplicatedService{
Replicas: &replicatedJobs,
},
},
Networks: []swarm.NetworkAttachmentConfig{
swarm.NetworkAttachmentConfig{
Target: networkID,
},
swarm.NetworkAttachmentConfig{
Target: "ingress",
},
},
EndpointSpec: &swarm.EndpointSpec{
Mode: "vip",
Ports: []swarm.PortConfig{
swarm.PortConfig{
Protocol: swarm.PortConfigProtocolTCP,
PublishMode: swarm.PortConfigPublishModeIngress,
Name: "worker-port",
PublishedPort: 33333,
TargetPort: 33333,
},
},
},
TaskTemplate: swarm.TaskSpec{
Resources: &swarm.ResourceRequirements{
Reservations: &swarm.Resources{},
},
LogDriver: &swarm.Driver{
Name: "json-file",
Options: map[string]string{
"max-size": "10m",
},
},
ContainerSpec: &swarm.ContainerSpec{
Image: image,
Env: []string{
fmt.Sprintf("SHUFFLE_SWARM_CONFIG=%s", os.Getenv("SHUFFLE_SWARM_CONFIG")),
fmt.Sprintf("SHUFFLE_SWARM_NETWORK_NAME=%s", networkName),
fmt.Sprintf("SHUFFLE_APP_REPLICAS=%d", appReplicaCnt),
fmt.Sprintf("SHUFFLE_LOGS_DISABLED=%s", os.Getenv("SHUFFLE_LOGS_DISABLED")),
fmt.Sprintf("DEBUG_MEMORY=%s", os.Getenv("DEBUG_MEMORY")),
fmt.Sprintf("SHUFFLE_APP_SDK_TIMEOUT=%s", os.Getenv("SHUFFLE_APP_SDK_TIMEOUT")),
fmt.Sprintf("SHUFFLE_MAX_SWARM_NODES=%s", os.Getenv("SHUFFLE_MAX_SWARM_NODES")),
fmt.Sprintf("SHUFFLE_BASE_IMAGE_NAME=%s", os.Getenv("SHUFFLE_BASE_IMAGE_NAME")),
fmt.Sprintf("SHUFFLE_APP_REQUEST_TIMEOUT=%s", os.Getenv("SHUFFLE_APP_REQUEST_TIMEOUT")),
},
//Hosts: []string{
// innerContainerName,
//},
},
RestartPolicy: &swarm.RestartPolicy{
Condition: swarm.RestartPolicyConditionOnFailure,
},
Placement: &swarm.Placement{
Constraints: []string{},
},
},
}
if defaultNetworkAttach == true || strings.ToLower(os.Getenv("SHUFFLE_DEFAULT_NETWORK_ATTACH")) == "true" {
targetName := "shuffle_shuffle"
isAttachable := false
networks, err := dockercli.NetworkList(ctx, network.ListOptions{})
if err == nil {
for _, net := range networks {
if net.Name == targetName {
if net.Scope == "swarm" {
log.Printf("[DEBUG] Found swarm-scoped network: %s", targetName)
isAttachable = true
} else {
log.Printf("[WARNING] Network %s exist but is not swarm scoped (scope=%s)", targetName, net.Scope)
}
break
}
}
}
if isAttachable {
log.Printf("[DEBUG] Adding network attach for network %s to worker in swarm", targetName)
serviceSpec.Networks = append(serviceSpec.Networks, swarm.NetworkAttachmentConfig{
Target: targetName,
})
// FIXM: Remove this if deployment fails?
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("SHUFFLE_SWARM_OTHER_NETWORK=%s", targetName))
}
}
if dockerApiVersion != "" {
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("DOCKER_API_VERSION=%s", dockerApiVersion))
}
if len(os.Getenv("SHUFFLE_SCALE_REPLICAS")) > 0 {
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("SHUFFLE_SCALE_REPLICAS=%s", os.Getenv("SHUFFLE_SCALE_REPLICAS")))
}
if len(os.Getenv("SHUFFLE_MEMCACHED")) > 0 {
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("SHUFFLE_MEMCACHED=%s", os.Getenv("SHUFFLE_MEMCACHED")))
}
if strings.ToLower(os.Getenv("SHUFFLE_PASS_WORKER_PROXY")) == "true" {
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("HTTP_PROXY=%s", os.Getenv("HTTP_PROXY")))
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("HTTPS_PROXY=%s", os.Getenv("HTTPS_PROXY")))
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("NO_PROXY=%s", os.Getenv("NO_PROXY")))
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("no_proxy=%s", os.Getenv("no_proxy")))
}
if len(workerServerUrl) > 0 {
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("SHUFFLE_WORKER_SERVER_URL=%s", os.Getenv("SHUFFLE_WORKER_SERVER_URL")))
}
// Handles backend
if len(os.Getenv("BASE_URL")) > 0 {
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("BASE_URL=%s", os.Getenv("BASE_URL")))
}
if len(os.Getenv("SHUFFLE_CLOUDRUN_URL")) > 0 {
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("SHUFFLE_CLOUDRUN_URL=%s", os.Getenv("SHUFFLE_CLOUDRUN_URL")))
}
if len(os.Getenv("SHUFFLE_AUTO_IMAGE_DOWNLOAD")) > 0 {
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("SHUFFLE_AUTO_IMAGE_DOWNLOAD=%s", os.Getenv("SHUFFLE_AUTO_IMAGE_DOWNLOAD")))
}
if len(os.Getenv("DOCKER_HOST")) > 0 {
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("DOCKER_HOST=%s", os.Getenv("DOCKER_HOST")))
} else {
if runtime.GOOS == "windows" {
serviceSpec.TaskTemplate.ContainerSpec.Mounts = []mount.Mount{
mount.Mount{
Source: `\\.\pipe\docker_engine`,
Target: `\\.\pipe\docker_engine`,
Type: mount.TypeBind,
},
}
} else {
serviceSpec.TaskTemplate.ContainerSpec.Mounts = []mount.Mount{
mount.Mount{
Source: "/var/run/docker.sock",
Target: "/var/run/docker.sock",
Type: mount.TypeBind,
},
}
}
}
// Look for SHUFFLE_VOLUME_BINDS
if len(os.Getenv("SHUFFLE_VOLUME_BINDS")) > 0 {
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("SHUFFLE_VOLUME_BINDS=%s", os.Getenv("SHUFFLE_VOLUME_BINDS")))
}
overrideHttpProxy := os.Getenv("SHUFFLE_INTERNAL_HTTP_PROXY")
overrideHttpsProxy := os.Getenv("SHUFFLE_INTERNAL_HTTPS_PROXY")
if len(overrideHttpProxy) > 0 {
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("SHUFFLE_INTERNAL_HTTP_PROXY=%s", overrideHttpProxy))
}
if len(overrideHttpsProxy) > 0 {
serviceSpec.TaskTemplate.ContainerSpec.Env = append(serviceSpec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("SHUFFLE_INTERNAL_HTTPS_PROXY=%s", overrideHttpsProxy))
}
serviceOptions := types.ServiceCreateOptions{}
_, err = dockercli.ServiceCreate(
ctx,
serviceSpec,
serviceOptions,
)
// Force deploy if it's not disabled
deployTenzirNode()
if err == nil {
log.Printf("[DEBUG] Successfully deployed workers with %d replica(s) on %d node(s)", replicas, cnt)
// wait for service to be ready
time.Sleep(time.Duration(rand.Intn(4)+1) * time.Second)
//log.Printf("[DEBUG] Servicecreate request: %#v %#v", service, err)
// patch service network
// this is an edgecase that we noticed on docker version 29
// and API version 1.44
services, serr := dockercli.ServiceList(ctx, types.ServiceListOptions{})
if serr == nil {
for _, svc := range services {
if svc.Spec.Annotations.Name == innerContainerName {
log.Printf("[DEBUG] Found service %s (%s) — patching network attach", innerContainerName, svc.ID)
spec := svc.Spec
spec.TaskTemplate.Networks = append(spec.TaskTemplate.Networks, swarm.NetworkAttachmentConfig{
Target: networkID,
})
_, uerr := dockercli.ServiceUpdate(ctx, svc.ID, svc.Version, spec, types.ServiceUpdateOptions{})
if uerr != nil {
log.Printf("[WARNING] Failed to patch service %s with network %s: %v", innerContainerName, networkID, uerr)
} else {
log.Printf("[INFO] Successfully attached network %s to service %s", networkID, innerContainerName)
}
break
}
}
} else {
log.Printf("[WARNING] Failed to list services for patching network attach: %v", serr)
}
} else {
if !strings.Contains(fmt.Sprintf("%s", err), "Already Exists") && !strings.Contains(fmt.Sprintf("%s", err), "is already in use by service") {
log.Printf("[ERROR] Failed making service: %s", err)
if strings.Contains(fmt.Sprintf("%s", err), "networks scoped to the swarm can be used") {
log.Printf("[WARNING] Swarm network attachment failed, retrying without shuffle_shuffle")
var updatedNetworks []swarm.NetworkAttachmentConfig
for _, net := range serviceSpec.Networks {
if net.Target != "shuffle_shuffle" {
updatedNetworks = append(updatedNetworks, net)
}
}
serviceSpec.Networks = updatedNetworks
var updatedEnv []string
for _, env := range serviceSpec.TaskTemplate.ContainerSpec.Env {
if !strings.HasPrefix(env, "SHUFFLE_SWARM_OTHER_NETWORK=") {
updatedEnv = append(updatedEnv, env)
}
}
serviceSpec.TaskTemplate.ContainerSpec.Env = updatedEnv
serviceOptions := types.ServiceCreateOptions{}
_, err = dockercli.ServiceCreate(
ctx,
serviceSpec,
serviceOptions,
)
if err != nil {
log.Printf("[ERROR] Failed to deploy service even without shuffle_shuffle network: %s", err)
}
}
} else {
log.Printf("[WARNING] Failed deploying workers: %s", err)
if len(serviceSpec.Networks) > 1 {
serviceSpec.Networks = []swarm.NetworkAttachmentConfig{
swarm.NetworkAttachmentConfig{
Target: "shuffle_shuffle",
},
}
_, _ = dockercli.ServiceCreate(
ctx,
serviceSpec,
serviceOptions,
)
}
}
}
}
// Deploys the worker with the current available environments
// https://docs.docker.com/engine/api/sdk/examples/
func buildEnvVars(envMap map[string]string) []corev1.EnvVar {
var envVars []corev1.EnvVar
for key, value := range envMap {
envVars = append(envVars, corev1.EnvVar{Name: key, Value: value})
}
return envVars
}
func buildResourcesFromEnv() corev1.ResourceRequirements {
requests := corev1.ResourceList{}
limits := corev1.ResourceList{}
type item struct {
env string
resourceName corev1.ResourceName
resourceList corev1.ResourceList
}
items := []item{
// kubernetes requests
{env: "SHUFFLE_WORKER_CPU_REQUEST", resourceName: corev1.ResourceCPU, resourceList: requests},
{env: "SHUFFLE_WORKER_MEMORY_REQUEST", resourceName: corev1.ResourceMemory, resourceList: requests},
{env: "SHUFFLE_WORKER_EPHEMERAL_STORAGE_REQUEST", resourceName: corev1.ResourceEphemeralStorage, resourceList: requests},
// kubernetes limits
{env: "SHUFFLE_WORKER_CPU_LIMIT", resourceName: corev1.ResourceCPU, resourceList: limits},
{env: "SHUFFLE_WORKER_MEMORY_LIMIT", resourceName: corev1.ResourceMemory, resourceList: limits},
{env: "SHUFFLE_WORKER_EPHEMERAL_STORAGE_LIMIT", resourceName: corev1.ResourceEphemeralStorage, resourceList: limits},
}
for _, it := range items {
if value := strings.TrimSpace(os.Getenv(it.env)); value != "" {
if quantity, err := resource.ParseQuantity(value); err == nil {
it.resourceList[it.resourceName] = quantity
} else {
log.Printf("[WARNING] Cannot parse %s=%q as resource quantity: %v", it.env, value, err)
}
}
}
rr := corev1.ResourceRequirements{}
if len(requests) > 0 {
rr.Requests = requests
}
if len(limits) > 0 {
rr.Limits = limits
}
return rr