This repository has been archived by the owner on Aug 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
/
order.go
1816 lines (1627 loc) · 63.6 KB
/
order.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
// order.go
// For loading a Software Order Email and parsing the order's content
//
// Copyright 2018 SAS Institute Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package main
import (
"encoding/base64"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"archive/zip"
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"gopkg.in/yaml.v2"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/exec"
"os/user"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
// RecipeVersion format <year>.<month>.<numbered release>
const RecipeVersion = "19.06.3"
// SasViyaVersion is used to wget the corresponding sas-orchestration tool version
// example: 34 = version 3.4
const SasViyaVersion = "34"
// ConfigPath is the path to the configuration file that's used to load custom container attributes
// NOTE: this path changes to config-<deployment-type>.yml
var ConfigPath = "config-full.yml"
// SoftwareOrder is the structure to hold the order information.
type SoftwareOrder struct {
// Build arguments and flags (see order.LoadCommands for details)
BaseImage string `yaml:"Base Image "`
MirrorURL string `yaml:"Mirror URL "`
VirtualHost string `yaml:"Virtual Host "`
DockerNamespace string `yaml:"Docker Namespace "`
DockerRegistry string `yaml:"Docker Registry "`
DeploymentType string `yaml:"Deployment Type "`
Platform string `yaml:"Platform "`
ProjectName string `yaml:"Project Name "`
TagOverride string `yaml:"Tag Override "`
AddOns []string `yaml:"AddOns "`
DebugContainers []string `yaml:"Debug Containers "`
WorkerCount int `yaml:"Worker Count "`
Verbose bool `yaml:"Verbose "`
SkipMirrorValidation bool `yaml:"Skip Mirror Validation "`
SkipDockerValidation bool `yaml:"Skip Docker Validation "`
GenerateManifestsOnly bool `yaml:"Generate Manifests Only "`
SkipDockerRegistryPush bool `yaml:"Skip Docker Registry "`
// Build attributes
Log *os.File `yaml:"-"` // File handle for log path
BuildContext context.Context `yaml:"-"` // Background context
BuildOnly []string `yaml:"Build Only "` // Only build these specific containers if they're in the list of entitled containers. The 'multiple' deployment type utilizes this to build only 3 images.
Containers map[string]*Container `yaml:"-"` // Individual containers build list
Config map[string]ConfigMap `yaml:"-"` // Static values and defaults are loaded from the configmap yaml
ConfigPath string `yaml:"-"` // config-<deployment-type>.yml file for custom or static values
LogPath string `yaml:"-"` // Path to the build directory with the log file name
PlaybookPath string `yaml:"-"` // Build path + "sas_viya_playbook"
KVStore string `yaml:"-"` // Combines all vars.yaml content
RegistryAuth string `yaml:"-"` // Used to push and pull from/to a regitry
BuildPath string `yaml:"-"` // Kubernetes manifests are generated and placed into this location
CertBaseURL string `yaml:"-"` // The URL that the build containers will use to fetch their CA and entitlement certs
BuilderIP string `yaml:"-"` // IP of where images are being built to be used for generic hostname lookup for builder
BuilderPort string `yaml:"-"` // Port for serving certificate requests for builds
TimestampTag string `yaml:"Timestamp Tag "` // Allows for datetime on each temp build bfile
InDocker bool `yaml:"-"` // If we are running in a docker container
ManifestDir string `yaml:"-"` // The name of the manifest directory. "manifests" is the default
// Metrics
StartTime time.Time `yaml:"-"`
EndTime time.Time `yaml:"-"`
TotalBuildSize int64 `yaml:"-"`
DockerClient *client.Client `yaml:"-"` // Used to pull the base image and output post-build details
// License attributes from the Software Order Email (SOE)
// SAS_Viya_deployment_data.zip
// ├── ca-certificates
// │ └── SAS_CA_Certificate.pem
// ├── entitlement-certificates
// │ ├── entitlement_certificate.pem
// │ └── entitlement_certificate.pfx
// ├── license
// │ └── SASViyaV0300_XXXXXX_Linux_x86-64.txt
// │ └── SASViyaV0300_XXXXXX_XXXXXXXX_Linux_x86-64.jwt
// └── order.oom
SOEZipPath string `yaml:"-"` // Used to load licenses
OrderOOM struct {
OomFormatVersion string `json:"oomFormatVersion"`
MetaRepo struct {
URL string `json:"url"`
Rpm string `json:"rpm"`
Orderables []string `json:"orderables"`
} `json:"metaRepo"`
} `yaml:"-"`
CA []byte `yaml:"-"`
Entitlement []byte `yaml:"-"`
License []byte `yaml:"-"`
MeteredLicense []byte `yaml:"-"`
SiteDefault []byte `yaml:"-"`
}
// Registry is ror reading ~/.docker/config.json
// example:
//{
// "auths": {
// "docker.mycompany.com": {
// "auth": "Zaoiqw0==" <-- this is a base64 string
// }
// },
//}
type Registry struct {
Auths map[string]struct {
Username string `json:"username"` // Optional
Password string `json:"password"` // Optional
Auth string `json:"auth"` // Required
} `json:"auths"`
}
// ConfigMap each container has a configmap which define Docker layers.
// A static configmap.yml file is parsed and all containers
// that do not have static values are set to the defaults
type ConfigMap struct {
Ports []string `yaml:"ports"` // Default: empty
Environment []string `yaml:"environment"` // Default: empty
Secrets []string `yaml:"secrets"` // Default: empty
Roles []string `yaml:"roles"` // Additional ansible roles to run
Volumes []string `yaml:"volumes"` // Default: log:/opt/sas/viya/config/var/log
Resources struct {
Limits []string `yaml:"limits"`
Requests []string `yaml:"requests"`
} `yaml:"resources"`
}
// SetupBuildDirectory creates a unique isolated directory for the Software Order
// based on the deployment and time stamp. It also configures logging.
func (order *SoftwareOrder) SetupBuildDirectory() error {
// Create an isolated build directory with a unique timestamp
order.BuildPath = fmt.Sprintf("builds/%s-%s/", order.DeploymentType, order.TimestampTag)
if err := os.MkdirAll(order.BuildPath, 0744); err != nil {
return err
}
// Start a new build log inside the isolated build directory
order.LogPath = order.BuildPath + "/build.log"
logHandle, err := os.Create(order.LogPath)
if err != nil {
return err
}
order.Log = logHandle
// Symbolically link the most recent time stamped build directory to a shorter name
// For example, 'full-2019-04-09-13-37-40' can be referred to as simply 'full'
// Note: This is executing inside the build container, inside a mounted volume,
// therefore an os.Symlink() does not work correctly.
previousLink := "builds/" + order.DeploymentType
if _, err := os.Lstat(previousLink); err == nil {
if err := os.Remove(previousLink); err != nil {
return err
}
}
symlinkCommand := fmt.Sprintf("cd builds && ln -s %s-%s %s && cd ..",
order.DeploymentType, order.TimestampTag, order.DeploymentType)
cmd := exec.Command("sh", "-c", symlinkCommand)
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
err = cmd.Start()
if err != nil {
result, _ := ioutil.ReadAll(stderr)
return errors.New(string(result) + "\n" + err.Error())
}
err = cmd.Wait()
if err != nil {
result, _ := ioutil.ReadAll(stderr)
return errors.New(string(result) + "\n" + err.Error())
}
// A single image only uses the vars_usermods.yml. That can be used to change the
// running of the playbook that is used in creating the image. For "full" or
// "multiple" deployments, only the manifests_usermods.yml is used. It is used
// when generating manifests and not in the building of the images.
if order.DeploymentType != "single" {
if err = order.LoadUsermods("manifests_usermods.yml"); err != nil {
return err
}
} else {
if err = order.LoadUsermods("vars_usermods.yml"); err != nil {
return err
}
}
return nil
}
// NewSoftwareOrder once the SOE zip file path has been provided then load all the Software Order's details
// Note: All sub-processes of this function are essential to the build process.
// If any of these steps return an error then the entire process will be exited.
func NewSoftwareOrder() (*SoftwareOrder, error) {
order := &SoftwareOrder{}
order.StartTime = time.Now()
order.TimestampTag = string(order.StartTime.Format("2006-01-02-15-04-05"))
if len(order.TagOverride) > 0 {
order.TimestampTag = order.TagOverride
}
if err := order.LoadCommands(); err != nil {
return order, err
}
if err := order.DefineManifestDir(); err != nil {
return order, err
}
// Do not load any more Software Order values, just allow order.GenerateManifests() to be called
if order.GenerateManifestsOnly {
return order, nil
}
order.WriteLog(true, order.BuildArgumentsSummary())
// Configure a new isolated build space
if err := order.SetupBuildDirectory(); err != nil {
return order, err
}
// Determine if the binary is being run inside the sas-container-recipes-builder
order.InDocker = true
if _, err := os.Stat("/.dockerenv"); err != nil {
order.InDocker = false
}
// Point to custom configuration yaml files
order.ConfigPath = "config-full.yml"
if order.DeploymentType == "multiple" {
order.ConfigPath = "config-multiple.yml"
}
// Start a worker pool and wait for all workers to finish
workerCount := 0 // Number of goroutines started
done := make(chan int)
fail := make(chan string)
progress := make(chan string)
// In a single deployment, we do not need to generate the playbook as the playbook
// is generated by the running of the Dockerfile. The sitedefault.yml also is not
// used as that is for Consul which is only in a full deployment.
if order.DeploymentType == "full" {
workerCount++
go order.LoadSiteDefault(progress, fail, done)
}
if order.DeploymentType != "single" {
workerCount++
go order.LoadPlaybook(progress, fail, done)
}
// When doing a single-container, the LoadLicense is still needed.
// Removing it will cause a build failure around a missing host.
workerCount++
go order.LoadLicense(progress, fail, done)
workerCount++
go order.LoadDocker(progress, fail, done)
if !order.SkipDockerRegistryPush {
workerCount++
go order.LoadRegistryAuth(fail, done)
} else {
log.Println("Skipping loading Docker registry authentication ...")
}
if !order.SkipDockerValidation {
workerCount++
go order.TestRegistry(progress, fail, done)
} else {
log.Println("Skipping validating Docker registry ...")
}
doneCount := 0
for {
select {
case <-done:
doneCount++
if doneCount == workerCount {
// After the configs have been loaded then pre-build the containers and generate the manifests
err := order.Prepare()
if err != nil {
return order, err
}
return order, nil
}
case failure := <-fail:
return order, errors.New(failure)
case progress := <-progress:
order.WriteLog(true, progress)
}
}
}
// BuildArgumentsSummary gets a human readable version of the command arguments
// that were supplied to the SoftwareOrder object. This is useful for debugging.
func (order *SoftwareOrder) BuildArgumentsSummary() string {
objectAttributes, _ := yaml.Marshal(order)
output := "\n" + strings.Repeat("=", 50) + "\n"
output += "\t\tBuild Variables\n"
output += strings.Repeat("=", 50) + "\n"
output += string(objectAttributes)
output += strings.Repeat("=", 50) + "\n"
return output
}
// Look through the network interfaces and find the machine's non-loopback IP
func getIPAddr() (string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "", err
}
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String(), nil
}
}
}
return "", errors.New("No IP found for serving playbook")
}
// Serve up the entitlement and CA cert on a random port from the host so
// the contents of these files don't exist in any docker layer or history.
func (order *SoftwareOrder) Serve() {
builderIP, err := getIPAddr()
if err != nil {
panic("Could not determine hostname or host IP: " + err.Error())
}
order.BuilderIP = builderIP
listener, err := net.Listen("tcp", ":"+order.BuilderPort)
if err != nil {
panic(err)
}
// Serve only two endpoints to receive the entitlement and CA
order.WriteLog(true, fmt.Sprintf("Serving license and entitlement on sas-container-recipes-builder:%s (%s)", order.BuilderPort, order.BuilderIP))
order.CertBaseURL = fmt.Sprintf("http://sas-container-recipes-builder:%s", order.BuilderPort)
http.HandleFunc("/entitlement/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, string(order.Entitlement))
})
http.HandleFunc("/cacert/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, string(order.CA))
})
http.Serve(listener, nil)
}
// WriteLog is multiplexer for writing logs.
// Write any number of object info to the build log file and/or to standard output
func (order *SoftwareOrder) WriteLog(writeToStdout bool, contentBlocks ...interface{}) {
// Write each block to standard output
if writeToStdout {
for _, block := range contentBlocks {
log.Println(block)
}
}
// Write the filename and line number
_, fullFilePath, fileCallerLineNumber, _ := runtime.Caller(1)
filePathSections := strings.Split(fullFilePath, "/")
fileCallerName := filePathSections[len(filePathSections)-1]
order.Log.Write([]byte(fmt.Sprintf("[%s:%d] ",
fileCallerName, fileCallerLineNumber)))
// Write each interface
for _, block := range contentBlocks {
order.Log.Write([]byte(fmt.Sprintf("%v\n", block)))
}
order.Log.Write([]byte("\n"))
}
// GetIntermediateStatus returns the output of how many and which containers have been built
// out of the total number of builds.
// This is displayed after a container finishes its build process.
func (order *SoftwareOrder) GetIntermediateStatus(progress chan string) {
finishedContainers := []string{}
remainingContainers := []string{}
for _, container := range order.Containers {
if container.Status == Pushed {
finishedContainers = append(finishedContainers, container.Name)
} else if container.Status != DoNotBuild {
remainingContainers = append(remainingContainers, container.Name)
}
}
if len(remainingContainers) == 0 {
// Don't show anything once all have completed since the final build summary displays
return
}
progress <- fmt.Sprintf("Built & Pushed [ %d / %d ].\nComplete: %s\nRemaining: %s\n",
len(finishedContainers), len(finishedContainers)+len(remainingContainers),
strings.Join(finishedContainers, ", "), strings.Join(remainingContainers, ", "))
}
// DefineManifestDir looks at the manifests_usermods.yml to see what the manifest dir is.
// If nothing is defined, then "manifests" is used
func (order *SoftwareOrder) DefineManifestDir() error {
manifestdirGrepCommand := fmt.Sprintf("grep '^SAS_MANIFEST_DIR' %smanifests_usermods.yml | awk -F ': ' '{ print $2 }'", order.BuildPath)
grepResult, err := exec.Command("sh", "-c", manifestdirGrepCommand).Output()
if err != nil {
return err
}
order.ManifestDir = strings.TrimSuffix(string(grepResult), "\n")
if len(order.ManifestDir) == 0 {
order.ManifestDir = "manifests"
}
return nil
}
// LoadCommands receives flags and arguments, parse them, and load them into the order
func (order *SoftwareOrder) LoadCommands() error {
// Standard format that arguments must comply with
regexNoSpecialCharacters := regexp.MustCompile("^[_A-z0-9]*([_A-z0-9\\-\\.]*)$")
// Required arguments
license := flag.String("zip", "", "")
dockerNamespace := flag.String("docker-namespace", "", "")
dockerRegistry := flag.String("docker-registry-url", "", "")
// Optional arguments
virtualHost := flag.String("virtual-host", "myvirtualhost.mycompany.com", "")
addons := flag.String("addons", "", "")
baseImage := flag.String("base-image", "centos:7", "")
mirrorURL := flag.String("mirror-url", "https://ses.sas.download/ses/", "")
verbose := flag.Bool("verbose", false, "")
buildOnly := flag.String("build-only", "", "")
tagOverride := flag.String("tag", RecipeVersion+"-"+order.TimestampTag, "")
projectName := flag.String("project-name", "sas-viya", "")
deploymentType := flag.String("type", "single", "")
version := flag.Bool("version", false, "")
skipDockerValidation := flag.Bool("skip-docker-url-validation", false, "")
generateManifestsOnly := flag.Bool("generate-manifests-only", false, "")
builderPort := flag.String("builder-port", "1976", "")
skipDockerRegistryPush := flag.Bool("skip-docker-registry-push", false, "")
// By default detect the cpu core count and utilize all of them
defaultWorkerCount := runtime.NumCPU()
workerCount := flag.Int("workers", defaultWorkerCount, "")
// Allow for quick exit if only viewing the --version or --help
flag.Usage = func() {
usageDocPath := "docs/usage.txt"
usage, err := ioutil.ReadFile(usageDocPath)
if err != nil {
fmt.Println("Unable to find usage file " + usageDocPath)
} else {
fmt.Println(string(usage))
}
os.Exit(0)
}
flag.Parse()
if *version == true {
fmt.Println("SAS Container Recipes v" + RecipeVersion)
os.Exit(0)
}
if len(os.Args) == 1 {
flag.Usage()
}
order.Verbose = *verbose
order.SkipDockerValidation = *skipDockerValidation
order.GenerateManifestsOnly = *generateManifestsOnly
order.VirtualHost = *virtualHost
order.DockerRegistry = *dockerRegistry
order.BuilderPort = *builderPort
order.SkipDockerRegistryPush = *skipDockerRegistryPush
// Disallow all other flags except --type with --generate-manifests-only
// Note: --tag is always passed from build.sh, so will have to ignore that
if *generateManifestsOnly {
if flag.NFlag() > 3 {
err := errors.New("Only '--type(-y)' can be used with '--generate-manifests-only'.")
return err
}
if *deploymentType == "single" {
err := errors.New("Use of '--type(-y) <multiple|full>' is required with '--generate-manifests-only'.")
return err
}
}
// Make sure one cannot specify more workers than # cores available
order.WorkerCount = *workerCount
if *workerCount == 0 || *workerCount > defaultWorkerCount {
err := errors.New("invalid '--worker' count, must be less than or equal to the number of CPU cores that are free and permissible in your cgroup configuration")
return err
}
// This is a safeguard for when a user does not use quotes around a multi value argument
otherArgs := flag.Args()
if len(otherArgs) > 0 {
progressString := "WARNING: one or more arguments were not parsed. Quotes are required for multi-value arguments."
order.WriteLog(true, progressString)
}
// Always require a deployment type
if *deploymentType != "multiple" && *deploymentType != "full" && *deploymentType != "single" {
err := errors.New("a valid '--type' is required: choose between single, multiple, or full")
return err
}
order.DeploymentType = strings.ToLower(*deploymentType)
// Always require a license except to re-generate manifests
if *license == "" && !order.GenerateManifestsOnly {
err := errors.New("a software order email (SOE) '--license' file is required")
return err
}
order.SOEZipPath = *license
if !strings.HasSuffix(order.SOEZipPath, ".zip") && !order.GenerateManifestsOnly {
return errors.New("the Software Order Email (SOE) argument '--zip' must be a file with the '.zip' extension")
}
// Optional: Parse the list of addons
*addons = strings.TrimSpace(*addons)
if *addons == "" {
order.AddOns = []string{}
} else {
// Accept a list of addon names delimited by a space or a comma
spaces, _ := regexp.Compile("[ ,]+") // math spaces or commas
addonString := spaces.ReplaceAllString(strings.TrimSpace(*addons), " ")
addonList := strings.Split(addonString, " ")
for _, addon := range addonList {
addonPath := addon
// if addon does not exist at specified path, check addons/ADDON.
// If addons/ADDON does not exist, return an error
if _, err := os.Stat(addonPath); err != nil {
// Try with 'addons/'
addonPath = "addons/" + addonPath
if _, err = os.Stat(addonPath); err != nil {
return fmt.Errorf("Addon %s could not be found", addon)
}
}
if !strings.HasSuffix(addonPath, "/") {
addonPath = addonPath + "/"
}
order.AddOns = append(order.AddOns, addonPath)
}
}
// Detect the platform based on the image
order.BaseImage = *baseImage
if strings.Contains(order.BaseImage, "suse") {
order.Platform = "suse"
} else {
// By default use rpm + yum
order.Platform = "redhat"
}
// A mirror is optional, except in the case of using an opensuse base image for single container
order.MirrorURL = *mirrorURL
if len(order.MirrorURL) == 0 && order.DeploymentType == "single" && order.Platform == "suse" {
return errors.New("a --mirror-url argument is required for a base suse single container")
}
if strings.Contains(order.MirrorURL, "http://") {
fmt.Println(fmt.Sprintf(
"WARNING: the --mirror-url argument '%s' does not have TLS.", order.MirrorURL))
}
// Optional: override the standard tag format
order.TagOverride = *tagOverride
if len(order.TagOverride) > 0 && !regexNoSpecialCharacters.Match([]byte(order.TagOverride)) {
return errors.New("The --tag argument contains invalid characters. It must contain contain only A-Z, a-z, 0-9, _, ., or -")
}
// Optional: override the "sas-viya-" prefix in image names and in the deployment
order.ProjectName = *projectName
if len(order.ProjectName) > 0 && !regexNoSpecialCharacters.Match([]byte(order.ProjectName)) {
return errors.New("The --project-name argument contains invalid characters. It must contain contain only A-Z, a-z, 0-9, _, ., or -")
}
// Require a docker namespace for multi and full if the manifests are not being re-generated
if *dockerNamespace == "" && (order.DeploymentType == "multiple" || order.DeploymentType == "full") && !order.GenerateManifestsOnly {
return errors.New("a '--docker-namespace' argument is required")
}
order.DockerNamespace = *dockerNamespace
if !regexNoSpecialCharacters.Match([]byte(order.DockerNamespace)) && !order.GenerateManifestsOnly {
return errors.New("The --docker-namespace argument contains invalid characters. It must contain contain only A-Z, a-z, 0-9, _, ., or -")
}
// Require a docker registry for multi and full
if *dockerRegistry == "" && !order.GenerateManifestsOnly &&
(order.DeploymentType == "multiple" || order.DeploymentType == "full") {
return errors.New("a '--docker-registry-url' argument is required")
}
// The deployment type utilizes the order.BuildOnly list
// Note: the 'full' deployment type builds everything, omitting the --build-only argument
if order.DeploymentType == "multiple" {
order.BuildOnly = []string{"programming", "httpproxy", "sas-casserver-primary"}
}
if order.DeploymentType == "full" {
order.WriteLog(true, `
_______ ______ _____ ____ ___ __ __ _____ _ _ _____ _ _
| ____\ \/ / _ \| ____| _ \|_ _| \/ | ____| \ | |_ _|/ \ | |
| _| \ /| |_) | _| | |_) || || |\/| | _| | \| | | | / _ \ | |
| |___ / \| __/| |___| _ < | || | | | |___| |\ | | |/ ___ \| |___
|_____/_/\_\_| |_____|_| \_\___|_| |_|_____|_| \_| |_/_/ \_\_____|
`)
}
// Parse the list of buildOnly arguments
*buildOnly = strings.TrimSpace(*buildOnly)
if *buildOnly != "" {
// Accept a list of container names delimited by a space or a comma
spaceDelimList := strings.Split(*buildOnly, " ")
commaDelimList := strings.Split(*buildOnly, ",")
order.BuildOnly = spaceDelimList
if len(spaceDelimList) < len(commaDelimList) {
order.BuildOnly = commaDelimList
}
}
return nil
}
func buildWorker(id int, containers <-chan *Container, done chan<- string, progress chan string, fail chan string) {
for container := range containers {
if container.Status != Loaded {
continue
}
// Build
container.BuildStart = time.Now()
err := container.Build(progress)
if err != nil {
container.Status = Failed
fail <- container.Name + ":" + container.Tag + " container build " + err.Error()
return
}
container.BuildEnd = time.Now()
if container.Status != Failed {
container.Status = Built
}
// Get each image's size
filterArgs := filters.NewArgs()
filterArgs.Add("reference", container.GetWholeImageName())
imageInfo, err := container.SoftwareOrder.DockerClient.ImageList(container.SoftwareOrder.BuildContext,
types.ImageListOptions{Filters: filterArgs})
if err != nil {
container.SoftwareOrder.WriteLog(true, "Unable to connect to Docker client for image build sizes")
}
imageSize := imageInfo[0].Size
container.SoftwareOrder.TotalBuildSize += imageSize
container.ImageSize = imageSize
if !container.SoftwareOrder.SkipDockerRegistryPush {
// Push
container.PushStart = time.Now()
err = container.Push(progress)
if err != nil {
container.Status = Failed
fail <- container.GetWholeImageName() + " container push " + err.Error()
done <- container.Name
return
}
container.PushEnd = time.Now()
// Signal the end of the build and push processes
container.Status = Pushed
progress <- container.GetWholeImageName() + ": finished pushing image to Docker registry"
container.SoftwareOrder.GetIntermediateStatus(progress)
} else {
progress <- "Skipping pushing " + container.GetWholeImageName() + " to Docker registry"
}
done <- container.Name
}
}
// The single container deployment type has a unique
// Grab the Dockerfile stub from the utils directory and append any addons
// then do a docker build with the base image and platform build arguments
// TODO: using license in RUN layers and mounting as volume?
func getProgrammingOnlySingleContainer(order *SoftwareOrder) error {
// In the case of the sinlge container, we will define the memory for the
// order.Containers object. For non-single builds, this is done in the
// getContainers method. That method is not called in a single image build
// so we need to do the following.
order.Containers = make(map[string]*Container)
container := Container{
Name: "single-programming-only",
SoftwareOrder: order,
BaseImage: order.BaseImage,
}
dockerConnection, err := client.NewClientWithOpts(client.WithVersion(DockerAPIVersion))
if err != nil {
debugMessage := "Unable to connect to Docker daemon. Ensure Docker is installed and the service is started. "
return errors.New(debugMessage + err.Error())
}
container.DockerClient = dockerConnection
// Create the build context and add relevant files to the context
resourceDirectory := "util/programming-only-single"
err = container.CreateBuildDirectory()
if err != nil {
return err
}
container.DockerContextPath = container.SoftwareOrder.BuildPath + "sas-viya-single-programming-only/build_context.tar"
err = container.AddFileToContext(resourceDirectory+"/entrypoint", "entrypoint", []byte{})
if err != nil {
return err
}
err = container.AddFileToContext(resourceDirectory+"/replace_httpd_default_cert.sh", "replace_httpd_default_cert.sh", []byte{})
if err != nil {
return err
}
err = container.AddFileToContext(resourceDirectory+"/sas-orchestration", "sas-orchestration", []byte{})
if err != nil {
return err
}
err = container.AddFileToContext(order.BuildPath+"/vars_usermods.yml", "vars_usermods.yml", []byte{})
if err != nil {
return err
}
// TODO: the SOE should not be added to the container. Need to update the Dockerfile to utilize a license volume mount.
err = container.AddFileToContext(container.SoftwareOrder.SOEZipPath, "SAS_Viya_deployment_data.zip", []byte{})
if err != nil {
return err
}
// Add files from the addons directory to the build context
for _, addon := range order.AddOns {
err := container.AddDirectoryToContext(addon, "", "")
if err != nil {
return errors.New("Unable to place addon files into Docker context. " + err.Error())
}
}
// Add the Dockerfile to the build context
dockerfileStub, err := ioutil.ReadFile(resourceDirectory + "/Dockerfile")
if err != nil {
return err
}
dockerfile, err := appendAddonLines(container.GetName(), string(dockerfileStub), container.SoftwareOrder.DeploymentType, container.SoftwareOrder.AddOns)
if err != nil {
return err
}
err = container.AddFileToContext("", "Dockerfile", []byte(dockerfile))
if err != nil {
return err
}
// Make the software order only build the image that was created in this function
for _, item := range order.Containers {
item.Status = DoNotBuild
}
container.Status = Loaded
order.Containers[container.Name] = &container
return nil
}
// Build starts each container build concurrently and report the results
func (order *SoftwareOrder) Build() error {
// Handle single container build and output of docker run instructions
if order.DeploymentType == "single" {
err := getProgrammingOnlySingleContainer(order)
if err != nil {
return err
}
}
numberOfBuilds := 0
for _, container := range order.Containers {
if container.Status == Loaded {
numberOfBuilds++
}
}
fmt.Println("")
if numberOfBuilds == 0 {
return errors.New("The number of builds are set to zero. " +
"An error in pre-build tasks may have occurred or the " +
"Software Order entitlement does not match the deployment type.")
} else if numberOfBuilds == 1 {
// Use the singular "process" instead of "processes"
order.WriteLog(true, "Starting "+strconv.Itoa(numberOfBuilds)+" build process ... (this may take several minutes)")
} else {
// Use the plural "processes" instead of "process"
order.WriteLog(true, "Starting "+strconv.Itoa(numberOfBuilds)+" build processes ... (this may take several minutes)")
}
order.WriteLog(true, "[TIP] System resource utilization can be seen by using the `docker stats` command.")
// Concurrently start each build process
jobs := make(chan *Container, 100)
fail := make(chan string)
done := make(chan string)
progress := make(chan string)
for w := 1; w <= order.WorkerCount; w++ {
go buildWorker(w, jobs, done, progress, fail)
}
for _, container := range order.Containers {
jobs <- container
}
close(jobs)
doneCount := 0
for {
select {
case <-done:
doneCount++
if doneCount == numberOfBuilds {
order.Finish()
return nil
}
case failure := <-fail:
return errors.New(failure)
case progress := <-progress:
order.WriteLog(true, progress)
}
}
}
// Get the names of each individual host to be created
//
// Read the sas_viya_playbook directory for the "group_vars" where each
// file individually defines a host. There is one container per host.
func getContainers(order *SoftwareOrder) (map[string]*Container, error) {
containers := make(map[string]*Container)
// These values are not added to the final hostGroup list result
var ignoredContainers = [...]string{
"all", "sas-all", "CommandLine",
"sas-casserver-secondary", "sas-casserver-worker",
}
// The names inside the playbook's inventory file are mapped to hosts
inventoryBytes, err := ioutil.ReadFile(order.BuildPath + "sas_viya_playbook/" + "inventory.ini")
if err != nil {
return containers, err
}
inventory := string(inventoryBytes)
startLine := 0
startOfSection := "[sas-all:children]"
lines := strings.Split(inventory, "\n")
for index, line := range lines {
if line == startOfSection {
startLine = index
}
}
if startLine == 0 {
return containers, errors.New("Cannot find inventory.ini section with all container names")
}
for i := startLine + 1; i < len(lines); i++ {
skip := false
name := lines[i]
for _, ignored := range ignoredContainers {
if name == ignored {
skip = true
}
}
if skip || len(strings.TrimSpace(name)) == 0 {
continue
}
container := Container{
Name: strings.ToLower(name),
SoftwareOrder: order,
Status: Unknown,
BaseImage: order.BaseImage,
}
container.Tag = container.GetTag()
containers[container.Name] = &container
}
return containers, nil
}
// LoadLicense once the path to the Software Order Email (SOE) zip file has been provided then unzip it
// and load the content into the SoftwareOrder struct for use in the build process.
func (order *SoftwareOrder) LoadLicense(progress chan string, fail chan string, done chan int) {
progress <- "Reading Software Order Email Zip ..."
if _, err := os.Stat(order.SOEZipPath); os.IsNotExist(err) {
fail <- err.Error()
return
}
zipped, err := zip.OpenReader(order.SOEZipPath)
if err != nil {
fail <- "Could not read the file specified by the `--zip` argument. This must be a valid Software Order Email (SOE) zip file.\n" + err.Error()
return
}
defer zipped.Close()
// Iterate through the files in the archive and print content for each
for _, zippedFile := range zipped.File {
// Read the string content and see what file it is, then load it into the order
readCloser, err := zippedFile.Open()
if err != nil {
fail <- err.Error()
return
}
buffer := new(bytes.Buffer)
_, err = io.Copy(buffer, readCloser)
if err != nil {
fail <- err.Error()
return
}
fileBytes, err := ioutil.ReadAll(buffer)
if err != nil {
fail <- err.Error()
return
}
readCloser.Close()
if strings.Contains(zippedFile.Name, "Linux_x86-64.txt") {
order.License = fileBytes
} else if strings.Contains(zippedFile.Name, "Linux_x86-64.jwt") {
order.MeteredLicense = fileBytes
} else if strings.Contains(zippedFile.Name, "SAS_CA_Certificate.pem") {
order.CA = fileBytes
} else if strings.Contains(zippedFile.Name, "entitlement_certificate.pem") {
order.Entitlement = fileBytes
} else if strings.Contains(zippedFile.Name, "order.oom") {
err := json.Unmarshal(fileBytes, &order.OrderOOM)
if err != nil {
fail <- err.Error()
return
}
}
}
// Make sure all required files were loaded into the order
if len(order.License) == 0 || len(order.MeteredLicense) == 0 || len(order.CA) == 0 || len(order.Entitlement) == 0 {
fail <- "Unable to parse all content from SOE zip"
return
}
go order.Serve()
progress <- "Finished reading Software Order Email"
done <- 1
}
// LoadDocker ensures the Docker client is accessible and pull the specified base image from Docker Hub
func (order *SoftwareOrder) LoadDocker(progress chan string, fail chan string, done chan int) {
// Make sure Docker is able to connect
progress <- "Connecting to the Docker daemon ..."
dockerConnection, err := client.NewClientWithOpts(client.WithVersion("1.37"))
if err != nil {
fail <- "Unable to connect to Docker daemon. Ensure Docker is installed and the service is started."
return
}
order.DockerClient = dockerConnection
progress <- "Finished connecting to Docker daemon"
// Pull the base image depending on what the argument was
progress <- "Pulling base container image '" + order.BaseImage + "'" + " ..."
order.BuildContext = context.Background()
_, err = order.DockerClient.ImagePull(order.BuildContext, order.BaseImage, types.ImagePullOptions{})
if err != nil {
fail <- err.Error()