-
Notifications
You must be signed in to change notification settings - Fork 7
/
containerManager.go
1127 lines (930 loc) · 35.2 KB
/
containerManager.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 main
import (
"context"
b64 "encoding/base64"
"encoding/json"
"errors"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"time"
libDatabox "github.com/me-box/lib-go-databox"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client"
"crypto/rand"
)
type ContainerManager struct {
cli *client.Client
ArbiterClient *libDatabox.ArbiterClient
CoreNetworkClient *CoreNetworkClient
CmgrStoreClient *libDatabox.CoreStoreClient
Request *http.Client
DATABOX_DNS_IP string
DATABOX_ROOT_CA_ID string
ZMQ_PUBLIC_KEY_ID string
ZMQ_PRIVATE_KEY_ID string
ARCH string
cmStoreURL string
Store *CMStore
Options *libDatabox.ContainerManagerOptions
AppStoreName string
CoreIUName string
CoreStoreName string
InstalledComponents map[string]string
}
// New returns a configured ContainerManager
func NewContainerManager(rootCASecretId string, zmqPublicId string, zmqPrivateId string, opt *libDatabox.ContainerManagerOptions) ContainerManager {
cli, _ := client.NewEnvClient()
request := libDatabox.NewDataboxHTTPsAPIWithPaths("/certs/containerManager.crt")
ac, err := libDatabox.NewArbiterClient("/certs/arbiterToken-container-manager", "/run/secrets/ZMQ_PUBLIC_KEY", "tcp://arbiter:4444")
libDatabox.ChkErr(err)
cnc := NewCoreNetworkClient("/certs/arbiterToken-databox-network", request)
cm := ContainerManager{
cli: cli,
ArbiterClient: ac,
CoreNetworkClient: cnc,
Request: request,
DATABOX_DNS_IP: os.Getenv("DATABOX_DNS_IP"),
DATABOX_ROOT_CA_ID: rootCASecretId,
ZMQ_PUBLIC_KEY_ID: zmqPublicId,
ZMQ_PRIVATE_KEY_ID: zmqPrivateId,
Options: opt,
AppStoreName: "app-store",
CoreIUName: "core-ui",
CoreStoreName: "core-store",
InstalledComponents: make(map[string]string),
}
if opt.Arch != "" {
cm.ARCH = "-" + opt.Arch
} else {
cm.ARCH = ""
}
return cm
}
func (cm ContainerManager) Start() {
//set debug output
libDatabox.OutputDebug(cm.Options.EnableDebugLogging)
//register with core-network
cm.CoreNetworkClient.RegisterPrivileged()
//wait for the arbiter
_, err := cm.WaitForService("arbiter", 10)
if err != nil {
libDatabox.Err("Filed to register the cm with the arbiter. " + err.Error())
}
//start the export service and register with the Arbiter
go cm.startExportService()
//register CM with arbiter - this is needed as the CM now has a store!
err = cm.ArbiterClient.RegesterDataboxComponent("container-manager", cm.ArbiterClient.ArbiterToken, libDatabox.DataboxTypeApp)
if err != nil {
libDatabox.Err("Filed to register the cm with the arbiter. " + err.Error())
}
//launch the CM store
cm.cmStoreURL = cm.launchCMStore()
//setup the cm to log to the store
cm.CmgrStoreClient = libDatabox.NewCoreStoreClient(cm.ArbiterClient, "/run/secrets/ZMQ_PUBLIC_KEY", cm.cmStoreURL, false)
//setup the cmStore
cm.Store = NewCMStore(cm.CmgrStoreClient)
//clear the saved slas if needed
if cm.Options.ClearSLAs && err == nil {
libDatabox.Info("Clearing SLA database to remove saved apps and drivers")
err = cm.Store.ClearSLADatabase()
libDatabox.ChkErr(err)
}
//Load the password from the store or create a new one
password := ""
if cm.Options.OverridePasword != "" {
libDatabox.Warn("OverridePasword used!")
password = cm.Options.OverridePasword
} else {
libDatabox.Debug("Getting password from DB")
password, err = cm.Store.LoadPassword()
libDatabox.ChkErr(err)
if password == "" {
libDatabox.Debug("Password not set genorating one")
password = cm.genoratePassword()
libDatabox.Debug("Saving new Password")
err := cm.Store.SavePassword(password)
libDatabox.ChkErr(err)
}
}
libDatabox.Info("Password=" + password)
//expose the CM API through the store before starting the UI
go CmZestAPI(&cm)
//start default drivers (driver-app-store, driver-export)
go cm.launchAppStore()
go cm.launchUI()
//start the webUI
go ServeInsecure()
go ServeSecure(&cm, password)
libDatabox.Info("Container Manager Ready and waiting")
//Reload and saved drivers and app from the cm store
libDatabox.Info("Restarting saved apps and drivers")
cm.reloadApps()
//start crash detectore
go cm.crashDetectore()
}
//Monitor docker events for crashed apps and drivers
//If an app or driver crashes restart it to fix the
//core-network registration
func (cm ContainerManager) crashDetectore() {
restartDetected := map[string]string{}
uninstallDetected := map[string]string{}
eventChan, _ := cm.cli.Events(context.Background(), types.EventsOptions{})
for {
select {
case msg := <-eventChan:
if msg.Type == "service" && msg.Action == "remove" {
libDatabox.Debug("Uninstall detected" + msg.Actor.ID)
uninstallDetected[msg.Actor.ID] = msg.Actor.ID
}
if msg.Type == "container" && msg.Action == "kill" && msg.Actor.Attributes["signal"] == "9" {
libDatabox.Debug("Restart detected")
restartDetected[msg.Actor.Attributes["name"]] = msg.Actor.Attributes["name"]
}
if msg.Type == "container" && msg.Action == "die" {
name := msg.Actor.Attributes["com.docker.swarm.service.name"]
ContName := msg.Actor.Attributes["name"]
serviceID := msg.Actor.Attributes["com.docker.swarm.service.id"]
if _, ok := restartDetected[ContName]; ok { //is it being restarted?
delete(restartDetected, ContName)
libDatabox.Debug("Not restarting " + name + " this time restart detected")
} else if _, ok := uninstallDetected[serviceID]; ok { //is it being uninstall?
delete(uninstallDetected, serviceID)
libDatabox.Debug("Not restarting " + name + " this time uninstall detected")
} else if _, ok := msg.Actor.Attributes["databox.type"]; !ok {
//Its not a databox app or driver do nothing
libDatabox.Debug("Not restarting " + name + " its not a databox app or driver")
} else { //looks looks a crash restart it
libDatabox.Warn("Crash detected for " + name)
libDatabox.Warn("Restarting " + name)
cm.Restart(name)
}
}
}
}
}
// LaunchFromSLA will start a databox app or driver with the reliant stores and grant permissions required as described in the SLA
func (cm ContainerManager) LaunchFromSLA(sla libDatabox.SLA, save bool) error {
//Make the localContainerName
localContainerName := sla.Name
//Make the requiredStoreName if needed
//TODO check store is supported!!
requiredStoreName := ""
if sla.ResourceRequirements.Store != "" {
requiredStoreName = sla.Name + "-" + sla.ResourceRequirements.Store
}
libDatabox.Info("Installing " + localContainerName)
//Create the networks and attach to the core-network.
netConf := cm.CoreNetworkClient.PreConfig(localContainerName, sla)
//start the container
var service swarm.ServiceSpec
var serviceOptions types.ServiceCreateOptions
var requiredNetworks []string
switch sla.DataboxType {
case libDatabox.DataboxTypeApp:
service, serviceOptions, requiredNetworks = cm.getAppConfig(sla, localContainerName, netConf)
case libDatabox.DataboxTypeDriver:
service, serviceOptions, requiredNetworks = cm.getDriverConfig(sla, localContainerName, netConf)
default:
return errors.New("[LaunchFromSLA] Unsupported image type")
}
pullImageIfRequired(service.TaskTemplate.ContainerSpec.Image, cm.Options.DefaultRegistry, cm.Options.DefaultRegistryHost)
//Check image is available and make some noise if its missing !!!
if !cm.imageExists(service.TaskTemplate.ContainerSpec.Image) {
return errors.New("Can't install " + localContainerName + " cant find the image " + service.TaskTemplate.ContainerSpec.Image)
}
exits, devMount := cm.getDevMountFor(localContainerName)
if exits == true {
//its a dev image mount the ContSrcPath folder in HostSrcPath
libDatabox.Info("Mounting " + devMount.ContSrcPath + " from " + localContainerName + " to " + devMount.HostSrcPath + " on the host")
//check path exists and error if its missing!
if _, err := os.Stat(devMount.HostSrcPath); err != nil {
return errors.New("Can't install " + localContainerName + ". HostSrcPath " + devMount.HostSrcPath + "not found")
}
service.TaskTemplate.ContainerSpec.Mounts = []mount.Mount{
mount.Mount{
Source: devMount.HostSrcPath,
Target: devMount.ContSrcPath,
Type: "bind",
},
}
}
//Add secrests to container
service.TaskTemplate.ContainerSpec.Secrets = cm.genorateSecrets(localContainerName, sla.DataboxType)
//If we need a store lets create one and set the needed environment variables
if requiredStoreName != "" {
service.TaskTemplate.ContainerSpec.Env = append(
service.TaskTemplate.ContainerSpec.Env,
"DATABOX_ZMQ_ENDPOINT=tcp://"+requiredStoreName+":5555",
)
service.TaskTemplate.ContainerSpec.Env = append(
service.TaskTemplate.ContainerSpec.Env,
"DATABOX_ZMQ_DEALER_ENDPOINT=tcp://"+requiredStoreName+":5556",
)
}
libDatabox.Debug("networksToConnect" + strings.Join(requiredNetworks, ","))
cm.CoreNetworkClient.ConnectEndpoints(localContainerName, requiredNetworks)
//do this after the networks are configured
if requiredStoreName != "" {
cm.launchStore(sla.ResourceRequirements.Store, requiredStoreName, netConf)
cm.WaitForService(requiredStoreName, 10)
}
cm.addPermissionsFromSLA(sla)
_, err := cm.cli.ServiceCreate(context.Background(), service, serviceOptions)
if err != nil {
libDatabox.Err("[Error launching] " + localContainerName + " " + err.Error())
return err
}
if save {
//save the sla for persistence over restarts
err = cm.Store.SaveSLA(sla)
libDatabox.ChkErr(err)
}
//keep track of installed components
cm.InstalledComponents[localContainerName] = localContainerName
libDatabox.Info("Successfully installed " + sla.Name)
return nil
}
//IsInstalled Checks to see a component has been installled
func (cm *ContainerManager) IsInstalled(name string) bool {
_, ok := cm.InstalledComponents[name]
return ok
}
// getDevMountFor return the DevMount from Options.DevMounts that matches contName
// returns false if no mach is found
func (cm *ContainerManager) getDevMountFor(contName string) (bool, libDatabox.DevMount) {
for _, m := range cm.Options.DevMounts {
if m.ContName == contName {
return true, m
}
}
return false, libDatabox.DevMount{}
}
func (cm *ContainerManager) imageExists(image string) bool {
images, _ := cm.cli.ImageList(context.Background(), types.ImageListOptions{})
for _, i := range images {
for _, tag := range i.RepoTags {
if image == tag {
//we have the image
return true
}
}
}
//sorry
return false
}
// Restart will restart the databox component, app or driver by service name
func (cm ContainerManager) Restart(name string) error {
filters := filters.NewArgs()
filters.Add("label", "com.docker.swarm.service.name="+name)
contList, _ := cm.cli.ContainerList(context.Background(),
types.ContainerListOptions{
Filters: filters,
})
if len(contList) < 1 {
return errors.New("Service " + name + " not running")
}
//Stash the old container IP
oldIP := ""
for netName := range contList[0].NetworkSettings.Networks {
serviceName := strings.Replace(name, "-"+cm.CoreStoreName, "", 1)
if strings.Contains(netName, serviceName) {
oldIP = contList[0].NetworkSettings.Networks[netName].IPAMConfig.IPv4Address
libDatabox.Debug("Old IP for " + netName + " is " + oldIP)
}
}
//Stop the container then the service will start a new one
err := cm.cli.ContainerRemove(context.Background(), contList[0].ID, types.ContainerRemoveOptions{Force: true})
if err != nil {
return errors.New("Cannot remove " + name + " " + err.Error())
}
//wait for the restarted container to start
newCont, err := cm.WaitForService(name, 20)
if err != nil {
libDatabox.Warn("Failed to restart " + name + " " + err.Error())
return err
}
//found restarted container !!!
//Stash the new container IP
newIP := ""
for netName := range newCont.NetworkSettings.Networks {
serviceName := strings.Replace(name, "-"+cm.CoreStoreName, "", 1)
if strings.Contains(netName, serviceName) {
newIP = newCont.NetworkSettings.Networks[netName].IPAMConfig.IPv4Address
libDatabox.Debug("IP IP for " + netName + " is " + newIP)
}
}
return cm.CoreNetworkClient.ServiceRestart(name, oldIP, newIP)
}
// Uninstall will remove the databox app or driver by service name
func (cm ContainerManager) Uninstall(name string) error {
serFilters := filters.NewArgs()
serFilters.Add("name", name)
serList, _ := cm.cli.ServiceList(context.Background(),
types.ServiceListOptions{
Filters: serFilters,
})
if len(serList) < 1 {
return errors.New("Service " + name + " not running")
}
networkConfig, err := cm.CoreNetworkClient.NetworkOfService(serList[0], serList[0].Spec.Name)
libDatabox.ChkErr(err)
err = cm.cli.ServiceRemove(context.Background(), serList[0].ID)
libDatabox.ChkErr(err)
//remove secrets
secFilters := filters.NewArgs()
secFilters.Add("name", name)
serviceList, err := cm.cli.ServiceList(context.Background(), types.ServiceListOptions{
Filters: secFilters,
})
for _, s := range serviceList {
for _, sec := range s.Spec.TaskTemplate.ContainerSpec.Secrets {
libDatabox.Debug("Removing secrete " + sec.SecretName)
cm.cli.SecretRemove(context.Background(), sec.SecretID)
}
}
cm.CoreNetworkClient.PostUninstall(name, networkConfig)
cm.Store.DeleteSLA(name)
delete(cm.InstalledComponents, name)
return err
}
// WaitForService will wait for a container to start searching for it by service name.
// If the container is found within the timeout it will return a docker/api/types.Container and nil
// otherwise an error will be returned.
func (cm ContainerManager) WaitForService(name string, timeout int) (types.Container, error) {
libDatabox.Debug("Waiting for " + name)
filters := filters.NewArgs()
filters.Add("label", "com.docker.swarm.service.name="+name)
//wait for the restarted container to start
var contList []types.Container
loopCount := 0
for {
contList, _ = cm.cli.ContainerList(context.Background(),
types.ContainerListOptions{
Filters: filters,
})
if len(contList) > 0 {
//found something!!
//give it a bit more time
//TODO think about using /status here
time.Sleep(time.Second * 3)
break
}
time.Sleep(time.Second)
loopCount++
if loopCount > timeout {
return types.Container{}, errors.New("Service " + name + " has not restarted after " + strconv.Itoa(timeout) + " seconds !!")
}
continue
}
return contList[0], nil
}
func (cm ContainerManager) genoratePassword() string {
b := make([]byte, 24)
rand.Read(b)
pass := b64.StdEncoding.EncodeToString(b)
return pass
}
func (cm ContainerManager) reloadApps() {
slaList, err := cm.Store.GetAllSLAs()
libDatabox.ChkErr(err)
libDatabox.Debug("reloadApps slaList len=" + strconv.Itoa(len(slaList)))
//launch drivers
var waitGroup sync.WaitGroup
LaunchFromSLAandWait := func(sla libDatabox.SLA, wg *sync.WaitGroup) {
err := cm.LaunchFromSLA(sla, false)
libDatabox.ChkErr(err)
wg.Done()
}
for _, sla := range slaList {
if sla.DataboxType == libDatabox.DataboxTypeDriver {
waitGroup.Add(1)
go LaunchFromSLAandWait(sla, &waitGroup)
}
}
//wait for all drivers to install before we install tha apps
waitGroup.Wait()
//launch apps
for _, sla := range slaList {
if sla.DataboxType == libDatabox.DataboxTypeApp {
waitGroup.Add(1)
go LaunchFromSLAandWait(sla, &waitGroup)
}
}
waitGroup.Wait()
}
// launchAppStore start the app store driver
func (cm ContainerManager) launchUI() {
name := cm.CoreIUName
sla := libDatabox.SLA{
Name: name,
DockerImage: cm.Options.CoreUIImage,
DataboxType: libDatabox.DataboxTypeApp,
Datasources: []libDatabox.DataSource{
libDatabox.DataSource{
Type: "databox:func:ServiceStatus",
Required: true,
Name: "ServiceStatus",
Clientid: "CM_API_ServiceStatus",
Granularities: []string{},
Hypercat: libDatabox.HypercatItem{
ItemMetadata: []interface{}{
libDatabox.RelValPairBool{
Rel: "urn:X-databox:rels:isFunc",
Val: true,
},
libDatabox.RelValPair{
Rel: "urn:X-databox:rels:hasDatasourceid",
Val: "ServiceStatus",
},
},
Href: "tcp://container-manager-" + cm.CoreStoreName + ":5555/",
},
},
libDatabox.DataSource{
Type: "databox:func:ListAllDatasources",
Required: true,
Name: "ListAllDatasources",
Clientid: "CM_API_ListAllDatasources",
Granularities: []string{},
Hypercat: libDatabox.HypercatItem{
ItemMetadata: []interface{}{
libDatabox.RelValPairBool{
Rel: "urn:X-databox:rels:isFunc",
Val: true,
},
libDatabox.RelValPair{
Rel: "urn:X-databox:rels:hasDatasourceid",
Val: "ListAllDatasources",
},
},
Href: "tcp://container-manager-" + cm.CoreStoreName + ":5555/",
},
},
libDatabox.DataSource{
Type: "databox:container-manager:api",
Required: true,
Name: "container-manager:api",
Clientid: "CM_API",
Granularities: []string{},
Hypercat: libDatabox.HypercatItem{
ItemMetadata: []interface{}{
libDatabox.RelValPairBool{
Rel: "urn:X-databox:rels:isActuator",
Val: true,
},
libDatabox.RelValPair{
Rel: "urn:X-databox:rels:hasDatasourceid",
Val: "api",
},
},
Href: "tcp://container-manager-" + cm.CoreStoreName + ":5555/kv/api",
},
},
libDatabox.DataSource{
Type: "databox:container-manager:data",
Required: true,
Name: "container-manager:data",
Clientid: "CM_DATA",
Granularities: []string{},
Hypercat: libDatabox.HypercatItem{
ItemMetadata: []interface{}{
libDatabox.RelValPairBool{
Rel: "urn:X-databox:rels:isActuator",
Val: false,
},
libDatabox.RelValPair{
Rel: "urn:X-databox:rels:hasDatasourceid",
Val: "data",
},
},
Href: "tcp://container-manager-" + cm.CoreStoreName + ":5555/kv/data",
},
},
libDatabox.DataSource{
Type: "databox:manifests:app",
Required: true,
Name: "databox Apps",
Clientid: "APPS",
Granularities: []string{},
Hypercat: libDatabox.HypercatItem{
ItemMetadata: []interface{}{
libDatabox.RelValPair{
Rel: "urn:X-databox:rels:hasDatasourceid",
Val: "apps",
},
},
Href: "tcp://" + cm.AppStoreName + "-" + cm.CoreStoreName + ":5555/kv/apps",
},
},
libDatabox.DataSource{
Type: "databox:manifests:driver",
Required: true,
Name: "databox Drivers",
Clientid: "DRIVERS",
Granularities: []string{},
Hypercat: libDatabox.HypercatItem{
ItemMetadata: []interface{}{
libDatabox.RelValPair{
Rel: "urn:X-databox:rels:hasDatasourceid",
Val: "drivers",
},
},
Href: "tcp://" + cm.AppStoreName + "-" + cm.CoreStoreName + ":5555/kv/drivers",
},
},
libDatabox.DataSource{
Type: "databox:manifests:all",
Required: true,
Name: "databox manifests",
Clientid: "ALL",
Granularities: []string{},
Hypercat: libDatabox.HypercatItem{
ItemMetadata: []interface{}{
libDatabox.RelValPair{
Rel: "urn:X-databox:rels:hasDatasourceid",
Val: "all",
},
},
Href: "tcp://" + cm.AppStoreName + "-" + cm.CoreStoreName + ":5555" + "/kv/all",
},
},
},
}
err := cm.LaunchFromSLA(sla, false)
libDatabox.ChkErr(err)
_, err = cm.WaitForService(name, 10)
libDatabox.ChkErr(err)
}
// launchAppStore start the app store driver
func (cm ContainerManager) launchAppStore() {
name := cm.AppStoreName
sla := libDatabox.SLA{
Name: name,
DockerImage: cm.Options.AppServerImage,
DataboxType: libDatabox.DataboxTypeDriver,
ResourceRequirements: libDatabox.ResourceRequirements{
Store: cm.CoreStoreName,
},
ExternalWhitelist: []libDatabox.ExternalWhitelist{
libDatabox.ExternalWhitelist{
Urls: []string{"https://github.com", "https://www.github.com"},
Description: "Needed to access the manifests stored on github",
},
},
}
err := cm.LaunchFromSLA(sla, false)
libDatabox.ChkErr(err)
_, err = cm.WaitForService(name, 10)
libDatabox.ChkErr(err)
}
// launchCMStore start a core-store the the container manager to store its configuration
func (cm ContainerManager) launchCMStore() string {
//startCMStore
sla := libDatabox.SLA{
Name: "container-manager",
DataboxType: libDatabox.DataboxTypeDriver,
ResourceRequirements: libDatabox.ResourceRequirements{
Store: cm.CoreStoreName,
},
}
requiredStoreName := sla.Name + "-" + sla.ResourceRequirements.Store
cm.launchStore(cm.CoreStoreName, requiredStoreName, NetworkConfig{NetworkName: "databox-system-net", DNS: cm.DATABOX_DNS_IP})
cm.addPermissionsFromSLA(sla)
_, err := cm.WaitForService(requiredStoreName, 10)
libDatabox.ChkErr(err)
return "tcp://container-manager-" + cm.CoreStoreName + ":5555"
}
func (cm ContainerManager) calculateImageNameFromSLA(sla libDatabox.SLA) string {
if strings.Contains(sla.DockerImage, "/") && strings.Contains(sla.DockerImage, ":") {
//looks like a full tagged image
return sla.DockerImage
}
imageName := ""
registry := ""
version := ""
//work out the registry and image name
if sla.DockerImage != "" {
imageName = sla.DockerImage
} else {
imageName = sla.Name
}
//add the arch
imageName += cm.ARCH
//work out registry
if sla.DockerRegistry != "" {
registry = sla.DockerRegistry
} else {
registry = cm.Options.DefaultRegistry
}
//work out the image tag
if sla.DockerImageTag != "" {
version = sla.DockerImageTag
} else {
version = cm.Options.Version
}
return registry + "/" + imageName + ":" + version
}
func (cm ContainerManager) getDriverConfig(sla libDatabox.SLA, localContainerName string, netConf NetworkConfig) (swarm.ServiceSpec, types.ServiceCreateOptions, []string) {
imageName := cm.calculateImageNameFromSLA(sla)
service := constructDefaultServiceSpec(localContainerName, imageName, libDatabox.DataboxTypeDriver, cm.Options.Version, netConf)
service.Name = localContainerName
service.TaskTemplate.ContainerSpec.Env = append(service.TaskTemplate.ContainerSpec.Env, "DATABOX_STORE_URL="+cm.Options.DefaultAppStore)
return service, types.ServiceCreateOptions{}, []string{"arbiter"}
}
func (cm ContainerManager) getAppConfig(sla libDatabox.SLA, localContainerName string, netConf NetworkConfig) (swarm.ServiceSpec, types.ServiceCreateOptions, []string) {
imageName := cm.calculateImageNameFromSLA(sla)
service := constructDefaultServiceSpec(localContainerName, imageName, libDatabox.DataboxTypeApp, cm.Options.Version, netConf)
service.Name = localContainerName
//add datasource info to the env vars and create a list networks this app needs to access
requiredNetworks := map[string]string{"arbiter": "arbiter", "export-service": "export-service"}
for _, ds := range sla.Datasources {
hypercatString, _ := json.Marshal(ds.Hypercat)
service.TaskTemplate.ContainerSpec.Env = append(
service.TaskTemplate.ContainerSpec.Env,
"DATASOURCE_"+ds.Clientid+"="+string(hypercatString),
)
parsedURL, _ := url.Parse(ds.Hypercat.Href)
storeName := parsedURL.Hostname()
requiredNetworks[storeName] = storeName
}
//connect to networks
networksToConnect := []string{}
if len(requiredNetworks) > 0 {
for store := range requiredNetworks {
networksToConnect = append(networksToConnect, store)
}
}
return service, types.ServiceCreateOptions{}, networksToConnect
}
func (cm ContainerManager) launchStore(requiredStore string, requiredStoreName string, netConf NetworkConfig) string {
//Check to see if the store already exists !!
storeFilter := filters.NewArgs()
storeFilter.Add("name", requiredStoreName)
stores, _ := cm.cli.ServiceList(context.Background(), types.ServiceListOptions{Filters: storeFilter})
if len(stores) > 0 {
//we have made this before just return the requiredStoreName
return requiredStoreName
}
image := cm.Options.DefaultStoreImage
service := constructDefaultServiceSpec(requiredStoreName, image, libDatabox.DataboxTypeStore, cm.Options.Version, netConf)
service.Name = requiredStoreName
//Add secrests to store
service.TaskTemplate.ContainerSpec.Secrets = cm.genorateSecrets(requiredStoreName, libDatabox.DataboxTypeStore)
storeName := requiredStoreName
//Add mounts to store
service.TaskTemplate.ContainerSpec.Mounts = []mount.Mount{
mount.Mount{
Source: requiredStoreName,
Target: "/database",
Type: "volume",
},
}
pullImageIfRequired(service.TaskTemplate.ContainerSpec.Image, cm.Options.DefaultRegistry, cm.Options.DefaultRegistryHost)
_, err := cm.cli.ServiceCreate(context.Background(), service, types.ServiceCreateOptions{})
if err != nil {
libDatabox.Err("Launching store " + requiredStoreName + " " + err.Error())
}
return storeName
}
func (cm ContainerManager) createSecret(name string, data []byte, filename string) *swarm.SecretReference {
filters := filters.NewArgs()
filters.Add("name", name)
secrestsList, _ := cm.cli.SecretList(context.Background(), types.SecretListOptions{Filters: filters})
if len(secrestsList) > 0 {
//remove any secrets and install new one just in case
for _, s := range secrestsList {
cm.cli.SecretRemove(context.Background(), s.ID)
}
}
secret := swarm.SecretSpec{
Annotations: swarm.Annotations{
Name: name,
},
Data: data,
}
secretCreateResponse, err := cm.cli.SecretCreate(context.Background(), secret)
if err != nil {
libDatabox.Err("addSecrets createSecret " + err.Error())
}
return &swarm.SecretReference{
SecretID: secretCreateResponse.ID,
SecretName: name,
File: &swarm.SecretReferenceFileTarget{
Name: filename,
UID: "0",
GID: "0",
Mode: 0444,
},
}
}
// genorateSecrets creates, if required, all the secrets passed to the databox app drivers and stores
func (cm ContainerManager) genorateSecrets(containerName string, databoxType libDatabox.DataboxType) []*swarm.SecretReference {
secrets := []*swarm.SecretReference{}
secrets = append(secrets, &swarm.SecretReference{
SecretID: cm.DATABOX_ROOT_CA_ID,
SecretName: "DATABOX_ROOT_CA",
File: &swarm.SecretReferenceFileTarget{
Name: "DATABOX_ROOT_CA",
UID: "0",
GID: "0",
Mode: 0444,
},
})
secrets = append(secrets, &swarm.SecretReference{
SecretID: cm.ZMQ_PUBLIC_KEY_ID,
SecretName: "ZMQ_PUBLIC_KEY",
File: &swarm.SecretReferenceFileTarget{
Name: "ZMQ_PUBLIC_KEY",
UID: "0",
GID: "0",
Mode: 0444,
},
})
cert := GenCert(
"./certs/containerManager.crt", //TODO Fix this
containerName,
[]string{"127.0.0.1"},
[]string{containerName},
)
secrets = append(secrets, cm.createSecret(strings.ToUpper(containerName)+".pem", cert, "DATABOX.pem"))
rawToken := GenerateArbiterToken()
b64TokenString := b64.StdEncoding.EncodeToString(rawToken)
secrets = append(secrets, cm.createSecret(strings.ToUpper(containerName)+"_KEY", []byte(b64TokenString), "ARBITER_TOKEN"))
//update the arbiter with the containers token
libDatabox.Debug("addSecrets UpdateArbiter " + containerName + " " + b64TokenString + " " + string(databoxType))
err := cm.ArbiterClient.RegesterDataboxComponent(containerName, b64TokenString, databoxType)
if err != nil {
libDatabox.Err("Add Secrets error updating arbiter " + err.Error())
}
//Only pass the zmq private key to stores.
if databoxType == "store" {
libDatabox.Debug("[addSecrets] ZMQ_PRIVATE_KEY_ID=" + cm.ZMQ_PRIVATE_KEY_ID)
secrets = append(secrets, &swarm.SecretReference{
SecretID: cm.ZMQ_PRIVATE_KEY_ID,
SecretName: "ZMQ_SECRET_KEY",
File: &swarm.SecretReferenceFileTarget{
Name: "ZMQ_SECRET_KEY",
UID: "0",
GID: "0",
Mode: 0444,
},
})
}
return secrets
}
//addPermissionsFromSLA parses a databox SLA and updates the arbiter with the correct permissions
func (cm ContainerManager) addPermissionsFromSLA(sla libDatabox.SLA) {
var err error
localContainerName := sla.Name
//set export permissions from export-whitelist
if len(sla.ExportWhitelists) > 0 {
for _, whiteList := range sla.ExportWhitelists {
caveat := `{"destination":"` + whiteList.Url + `"}`
libDatabox.Debug("Adding Export permissions for " + localContainerName + " on " + whiteList.Url)
err = cm.addPermission(localContainerName, "export-service", "/export", "POST", caveat)
if err != nil {
libDatabox.Err("Adding write permissions for export-service " + err.Error())
}
err = cm.addPermission(localContainerName, "export-service", "/lp/export", "POST", caveat)
if err != nil {
libDatabox.Err("Adding write permissions for lp export-service " + err.Error())
}
}
}
//set export permissions from ExternalWhitelist
if sla.DataboxType == "driver" && len(sla.ExternalWhitelist) > 0 {
//TODO move this logic to the coreNetworkClient
for _, whiteList := range sla.ExternalWhitelist {
libDatabox.Debug("addPermissionsFromSla adding ExternalWhitelist for " + localContainerName + " on " + strings.Join(whiteList.Urls, ", "))
externals := []string{}
for _, u := range whiteList.Urls {
parsedURL, err := url.Parse(u)
if err != nil {
libDatabox.Warn("Error parsing url in ExternalWhitelist")
}
externals = append(externals, parsedURL.Hostname())
}
err := cm.CoreNetworkClient.ConnectEndpoints(localContainerName, externals)
libDatabox.ChkErr(err)
}
}
//set read permissions from the sla for DATASOURCES.
if sla.DataboxType == "app" && len(sla.Datasources) > 0 {
for _, ds := range sla.Datasources {
datasourceEndpoint, _ := url.Parse(ds.Hypercat.Href)
datasourceName := datasourceEndpoint.Path
libDatabox.Debug("[adding permissions for] datasource" + ds.Name)
libDatabox.Debug(ds.Name + " IsActuator " + strconv.FormatBool(libDatabox.IsActuator(ds)))
if libDatabox.IsActuator(ds) { //Deal with Actuators
libDatabox.Debug("Adding write permissions for Actuator " + datasourceName + "/* on " + datasourceEndpoint.Hostname())
err = cm.addPermission(localContainerName, datasourceEndpoint.Hostname(), datasourceName+"/*", "POST", "")