This repository has been archived by the owner on Jan 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 262
/
plugin.go
1848 lines (1725 loc) · 58.7 KB
/
plugin.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package instance // import "github.com/docker/infrakit/pkg/provider/terraform/instance"
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/deckarep/golang-set"
"github.com/docker/infrakit/pkg/discovery"
"github.com/docker/infrakit/pkg/discovery/local"
logutil "github.com/docker/infrakit/pkg/log"
terraform_types "github.com/docker/infrakit/pkg/provider/terraform/instance/types"
"github.com/docker/infrakit/pkg/spi/instance"
"github.com/docker/infrakit/pkg/template"
"github.com/docker/infrakit/pkg/types"
"github.com/spf13/afero"
)
// For logging
var (
logger = logutil.New("module", "provider/terraform/instance")
debugV1 = logutil.V(100)
debugV2 = logutil.V(500)
debugV3 = logutil.V(1000)
)
// This example uses terraform as the instance plugin.
// It is very similar to the file instance plugin. When we
// provision an instance, we write a *.tf.json file in the directory
// and call terraform apply. For describing instances, we parse the
// result of terraform show. Destroying an instance is simply removing a
// tf.json file and call terraform apply again.
const (
// attachTag contains a space separated list of IDs that are to the instance
attachTag = "infrakit.attach"
// scopeDedicated is the scope key for dedicated resources
scopeDedicated = "dedicated"
// scopeGlobal is the scope key for global resources
scopeGlobal = "global"
// NameTag is the name of the tag that contains the instance name
NameTag = "infrakit.instance.name"
)
// tfFileRegex is used to determine the all terraform files; files with a ".new" suffix
// have not yet been processed by terraform
var tfFileRegex = regexp.MustCompile("(^.*).tf.json([.new]*)$")
// dedicatedScopedFileRegex is used to determine the scope ID and the instance
// ID (instance-XXXX|logicalID) for a file that contains dedicated resources
var dedicatedScopedFileRegex = regexp.MustCompile("^([a-z]*){1}_dedicated_([a-zA-Z0-9-]*).tf.json([.new]*)$")
// instanceTfFileRegex is used to determine the files that contain a terraform instance
// definition; files with a ".new" suffix have not yet been processed by terraform
var instanceTfFileRegex = regexp.MustCompile("(^instance-[0-9]+)(.tf.json)([.new]*)$")
// instNameRegex is used to determine the name of an instance
var instNameRegex = regexp.MustCompile("(.*)(instance-[0-9]+)")
type plugin struct {
Dir string
fs afero.Fs
fsLock sync.RWMutex
applying bool
applyLock sync.Mutex
pretend bool // true to actually do terraform apply
pollInterval time.Duration
pollChannel chan bool
pluginLookup func() discovery.Plugins
envs []string
cachedInstances *[]instance.Description
terraform tf
}
// ImportResource defines a resource that should be imported
type ImportResource struct {
ResourceID *string
ResourceType *TResourceType
ResourceName *TResourceName // Name of resource in the instance spec
ExcludePropIDs *[]string // Property IDs that exist in the instance spec that should be excluded
ResourceProps TResourceProperties // Populated via tf show
SpecProps TResourceProperties // Parsed from instance spec
FinalProps TResourceProperties // Properties for the tf.json.new file
FinalResourceName TResourceName // Formatted resource name
FinalFilename string // Filename for the tf.json.new file
AlreadyImported bool // Track if this resource already exists in tf state
SuccessfullyImported bool // Track if this resource was imported
}
// ImportOptions defines the resources that should be imported into terraform before
// the plugin is started
type ImportOptions struct {
InstanceSpec *instance.Spec
Resources []*ImportResource
}
// NewTerraformInstancePlugin returns an instance plugin backed by disk files.
func NewTerraformInstancePlugin(options terraform_types.Options, importOpts *ImportOptions) (instance.Plugin, error) {
return newPlugin(options, importOpts, false, terraformLookup)
}
// newPlugin is the internal function that returns an instance plugin backed by disk files. This function
// allows us to override the pretend flag for testing.
func newPlugin(
options terraform_types.Options,
importOpts *ImportOptions,
pretend bool,
tfLookup func(string, []string) (tf, error)) (instance.Plugin, error) {
logger.Info("newPlugin", "dir", options.Dir)
var pluginLookup func() discovery.Plugins
if !options.Standalone {
if err := local.Setup(); err != nil {
panic(err)
}
plugins, err := local.NewPluginDiscovery()
if err != nil {
panic(err)
}
pluginLookup = func() discovery.Plugins {
return plugins
}
}
// Environment varables to include when invoking terraform
envs, err := options.ParseOptionsEnvs()
if err != nil {
logger.Error("newPlugin",
"msg", "error parsing configuration Env Options",
"err", err)
return nil, err
}
tf, err := tfLookup(options.Dir, envs)
if err != nil {
logger.Error("newPlugin",
"msg", "error looking up terraform",
"err", err)
panic(err)
}
p := plugin{
Dir: options.Dir,
fs: afero.NewOsFs(),
pollInterval: options.PollInterval.Duration(),
pluginLookup: pluginLookup,
envs: envs,
pretend: pretend,
terraform: tf,
}
if err := p.processImport(importOpts); err != nil {
panic(err)
}
// Populate the instance cache
p.refreshNilInstanceCache()
// Ensure that tha apply goroutine is always running; it will only run "terraform apply"
// if the current node is the leader. However, when leadership changes, a Provision is
// not guaranteed to be executed so we need to create the goroutine now.
p.terraformApply()
return &p, nil
}
// processImport imports the resource with the given ID based on the instance Spec;
// after the resource is imported, a tf.json file is also generated so that the
// resource is not orphaned in terraform.
func (p *plugin) processImport(importOpts *ImportOptions) error {
if importOpts == nil {
return nil
}
if importOpts.InstanceSpec == nil {
if len(importOpts.Resources) > 0 {
return fmt.Errorf("Import instance spec required with imported resources")
}
// Values are empty, nothing to import
return nil
}
if len(importOpts.Resources) == 0 {
return fmt.Errorf("Resources required with import instance spec")
}
for _, res := range importOpts.Resources {
if res.ResourceName == nil {
logger.Info("processImport",
"ResourceType", string(*res.ResourceType),
"ResourceID", string(*res.ResourceID))
} else {
logger.Info("processImport",
"ResourceType", string(*res.ResourceType),
"ResourceName", string(*res.ResourceName),
"ResourceID", string(*res.ResourceID))
}
}
err := p.importResources(importOpts.Resources, importOpts.InstanceSpec)
if err != nil {
logger.Error("processImport", "msg", "Failed to import instances", "error", err)
return err
}
return nil
}
/*
TFormat models the on disk representation of a terraform resource JSON.
An example of this looks like:
{
"resource": {
"aws_instance": {
"web4": {
"ami": "${lookup(var.aws_amis, var.aws_region)}",
"instance_type": "m1.small",
"key_name": "PUBKEY",
"vpc_security_group_ids": ["${aws_security_group.default.id}"],
"subnet_id": "${aws_subnet.default.id}",
"tags": {
"infrakit.instance.name": "web4",
"InstancePlugin": "terraform"
},
"connection": {
"user": "ubuntu"
},
"provisioner": {
"remote_exec": {
"inline": [
"sudo apt-get -y update",
"sudo apt-get -y install nginx",
"sudo service nginx start"
]
}
}
}
}
}
}
The block above is essentially embedded inside the `Properties` field of the instance Spec:
{
"Properties": {
"resource": {
"aws_instance": {
"web4": {
"ami": "${lookup(var.aws_amis, var.aws_region)}",
"instance_type": "m1.small",
"key_name": "PUBKEY",
"vpc_security_group_ids": ["${aws_security_group.default.id}"],
"subnet_id": "${aws_subnet.default.id}",
"tags": {
"infrakit.instance.name": "web4",
"InstancePlugin": "terraform"
},
"connection": {
"user": "ubuntu"
},
"provisioner": {
"remote_exec": {
"inline": [
"sudo apt-get -y update",
"sudo apt-get -y install nginx",
"sudo service nginx start"
]
}
}
}
}
}
},
"Tags": {
"other": "values",
"to": "merge",
"with": "tags"
},
"Init": "init string"
}
*/
// TResourceType is the type name of the resource: e.g. ibmcloud_infra_virtual_guest
type TResourceType string
// TResourceName is the name of the resource e.g. host1
type TResourceName string
// TResourceProperties is a dictionary for the resource
type TResourceProperties map[string]interface{}
// TFormat is the on-disk file format for the instance-xxxx.json. This supports multiple resources.
type TFormat struct {
// Resource matches the resource structure of the tf.json resource section
Resource map[TResourceType]map[TResourceName]TResourceProperties `json:"resource"`
}
const (
//VMAmazon is the resource type for aws
VMAmazon = TResourceType("aws_instance")
// VMAzure is the resource type for azure
VMAzure = TResourceType("azurerm_virtual_machine")
// VMDigitalOcean is the resource type for digital ocean
VMDigitalOcean = TResourceType("digitalocean_droplet")
// VMGoogleCloud is the resource type for google
VMGoogleCloud = TResourceType("google_compute_instance")
// VMSoftLayer is the resource type for softlayer
VMSoftLayer = TResourceType("softlayer_virtual_guest")
// VMIBMCloud is the resource type for IBM Cloud
VMIBMCloud = TResourceType("ibm_compute_vm_instance")
)
const (
// PropHostnamePrefix is the optional terraform property that contains the hostname prefix
PropHostnamePrefix = "@hostname_prefix"
// PropScope is the optional terraform property that defines how a resource should be persisted
PropScope = "@scope"
// ValScopeDedicated defines dedicated scope: the resource lifecycle is loosely couple with the
// VM; it is written in a file named "instance-xxxx-dedicated.tf.json"
ValScopeDedicated = "@dedicated"
// ValScopeDefault defines the default scope: the resource lifecycle is tightly coupled
// with the VM; it is written in the same "instance.xxxx.tf.json" file
ValScopeDefault = "@default"
)
var (
// VMTypes is a list of supported vm types.
VMTypes = []interface{}{VMAmazon, VMAzure, VMDigitalOcean, VMGoogleCloud, VMSoftLayer, VMIBMCloud}
)
// first returns the first entry. This is based on our assumption that exactly one vm resource per file.
func first(vms map[TResourceName]TResourceProperties) (TResourceName, TResourceProperties) {
for k, v := range vms {
return k, v
}
return TResourceName(""), nil
}
// FindVM finds the resource block representing the vm instance from the tf.json representation
func FindVM(tf *TFormat) (vmType TResourceType, vmName TResourceName, properties TResourceProperties, err error) {
if tf.Resource == nil {
err = fmt.Errorf("no resource section")
return
}
supported := mapset.NewSetFromSlice(VMTypes)
for resourceType, objs := range tf.Resource {
if supported.Contains(resourceType) {
vmType = resourceType
vmName, properties = first(objs)
return
}
}
err = fmt.Errorf("not found")
return
}
// Validate performs local validation on a provision request.
func (p *plugin) Validate(req *types.Any) error {
logger.Debug("validate", "req", req.String(), "V", debugV1)
tf := TFormat{}
err := req.Decode(&tf)
if err != nil {
return err
}
vmTypes := mapset.NewSetFromSlice(VMTypes)
vms := 0
for k := range tf.Resource {
if vmTypes.Contains(k) {
vms++
}
}
if vms > 1 {
return fmt.Errorf("zero or 1 vm instance per request: %d", vms)
}
return nil
}
// platformSpecificUpdates handles unique platform specific logic
func platformSpecificUpdates(vmType TResourceType, name TResourceName, logicalID *instance.LogicalID, properties TResourceProperties) {
if properties == nil {
return
}
switch vmType {
case VMSoftLayer, VMIBMCloud:
// Process a special @hostname_prefix that will allow the setting of hostname in a
// specific format; use the LogicalID (if set), else the name
var hostname string
if logicalID == nil {
hostname = string(name)
} else {
hostname = string(*logicalID)
}
// Use the given hostname value as a prefix if it is a non-empty string
if hostnamePrefix, is := properties[PropHostnamePrefix].(string); is {
hostnamePrefix = strings.Trim(hostnamePrefix, " ")
// Use the default behavior if hostnamePrefix was either not a string, or an empty string
if hostnamePrefix == "" {
properties["hostname"] = hostname
} else {
// Remove "instance-" from "instance-XXXX", then append that string to the hostnamePrefix to create the new hostname
properties["hostname"] = fmt.Sprintf("%s-%s", hostnamePrefix, strings.Replace(hostname, "instance-", "", -1))
}
} else {
properties["hostname"] = hostname
}
// Delete hostnamePrefix so it will not be written in the *.tf.json file
delete(properties, PropHostnamePrefix)
logger.Debug("platformSpecificUpdates", "msg", "Adding hostname to properties", "hostname", properties["hostname"], "V", debugV1)
case VMAmazon:
if p, exists := properties["private_ip"]; exists {
if p == "INSTANCE_LOGICAL_ID" {
if logicalID != nil {
// set private IP to logical ID
properties["private_ip"] = string(*logicalID)
} else {
// reset private IP (the tag is not relevant in this context)
delete(properties, "private_ip")
}
}
}
// Encode user data
if data, has := properties["user_data"]; has {
properties["user_data"] = base64.StdEncoding.EncodeToString([]byte(data.(string)))
}
case VMDigitalOcean:
// Encode user data
if data, has := properties["user_data"]; has {
properties["user_data"] = base64.StdEncoding.EncodeToString([]byte(data.(string)))
}
}
}
// addUserData adds the given init data to the given map at the given key
func addUserData(m map[string]interface{}, key string, init string) {
if v, has := m[key]; has {
m[key] = fmt.Sprintf("%s\n%s", v, init)
} else {
m[key] = init
}
}
// mergeInitScript merges the user defined user data with the spec init data
func mergeInitScript(spec instance.Spec, id instance.ID, vmType TResourceType, properties TResourceProperties) {
// Merge the init scripts
switch vmType {
case VMAmazon, VMDigitalOcean:
addUserData(properties, "user_data", spec.Init)
case VMSoftLayer, VMIBMCloud:
addUserData(properties, "user_metadata", spec.Init)
case VMAzure:
// os_profile.custom_data
if m, has := properties["os_profile"]; !has {
properties["os_profile"] = map[string]interface{}{
"custom_data": spec.Init,
}
} else if mm, ok := m.(map[string]interface{}); ok {
addUserData(mm, "custom_data", spec.Init)
}
case VMGoogleCloud:
// metadata_startup_script
addUserData(properties, "metadata_startup_script", spec.Init)
}
}
// renderInstVars applies the "/self/instId", "/self/logicalId", and "/self/dedicated/attachId" variables
// as global options on the input properties
func renderInstVars(props *TResourceProperties, id instance.ID, logicalID *instance.LogicalID, dedicatedAttachKey string) error {
data, err := json.Marshal(props)
if err != nil {
return err
}
t, err := template.NewTemplate("str://"+string(data), template.Options{})
if err != nil {
return err
}
// Instance ID is always supplied
t = t.Global("/self/instId", id)
// LogicalID and dedicated attach key values are optional
if logicalID != nil {
t = t.Global("/self/logicalId", string(*logicalID))
}
if dedicatedAttachKey != "" {
t = t.Global("/self/dedicated/attachId", dedicatedAttachKey)
}
result, err := t.Render(nil)
if err != nil {
return err
}
return json.Unmarshal([]byte(result), &props)
}
// handleProvisionTags sets the Infrakit-specific tags and merges with the user-defined in the instance spec
func handleProvisionTags(spec instance.Spec, id instance.ID, vmType TResourceType, vmProperties TResourceProperties) {
// Add the name to the tags if it does not exist
if spec.Tags != nil {
match := false
for key := range spec.Tags {
if key == NameTag {
match = true
break
}
}
if !match {
spec.Tags[NameTag] = string(id)
}
}
// Merge any spec tags into the VM properties
mergeTagsIntoVMProps(vmType, vmProperties, spec.Tags)
}
// mergeTagsIntoVMProps merges the given tags into vmProperties in the appropriate
// platform-specific tag format
func mergeTagsIntoVMProps(vmType TResourceType, vmProperties TResourceProperties, tags map[string]string) {
switch vmType {
case VMAmazon, VMAzure, VMDigitalOcean, VMGoogleCloud:
if vmTags, exists := vmProperties["tags"]; !exists {
// Need to be careful with type here; the tags saved in the VM properties need to be generic
// since that it how they are parsed from json
tagsInterface := make(map[string]interface{}, len(tags))
for k, v := range tags {
tagsInterface[k] = v
}
vmProperties["tags"] = tagsInterface
} else if tagsMap, ok := vmTags.(map[string]interface{}); ok {
// merge tags
for k, v := range tags {
tagsMap[k] = v
}
} else {
logger.Error("mergeTagsIntoVMProps", "msg", fmt.Sprintf("invalid %v props tags value: %v", vmType, reflect.TypeOf(vmProperties["tags"])))
}
case VMSoftLayer, VMIBMCloud:
if _, has := vmProperties["tags"]; !has {
vmProperties["tags"] = []interface{}{}
}
if tagsArray, ok := vmProperties["tags"].([]interface{}); ok {
// softlayer uses a list of tags, instead of a map of tags
vmProperties["tags"] = mergeLabelsIntoTagSlice(tagsArray, tags)
} else {
logger.Error("mergeTagsIntoVMProps", "msg", fmt.Sprintf("invalid %v props tags value: %v", vmType, reflect.TypeOf(vmProperties["tags"])))
}
// All tags on Softlayer must be lower-case
tagsLower := []interface{}{}
for _, val := range vmProperties["tags"].([]string) {
// Commas are not valid tag characters, change to a space for tag values that
// are a list
if strings.HasPrefix(val, attachTag+":") {
val = strings.Replace(val, ",", " ", -1)
}
tagsLower = append(tagsLower, strings.ToLower(val))
}
vmProperties["tags"] = tagsLower
}
}
// decomposedFiles is populated by the decompose function
type decomposedFiles struct {
FileMap map[string]*TFormat
CurrentFiles map[string]struct{}
DedicatedAttachKey string
}
// decompose splits the data in the TFormat object into one or more terraform specs, each
// corresponding to a file that should be created. The properties of the VM resource are
// update to use the generated name and the given vmProperties.
func (p *plugin) decompose(logicalID *instance.LogicalID, generatedName string, tf *TFormat, vmType TResourceType, vmProperties TResourceProperties) (*decomposedFiles, error) {
// Map file names to the data in each file based on the "@scope" property:
// - @default: resources in same "instance-xxxx" file as VM
// - @dedicated: resources in different file as VM using the logical ID (<scopeID>_dedicated_<logicalID>) or with
// the same generated ID (<scopeID>_dedicated_instance-xxxx)
// - <other>: resource defined in different file with a scope identifier (<other>_global)
fileMap := make(map[string]*TFormat)
// Track the dedicated attach ID for this VM, this is set if there is an orphaned dedicated
// file that matches the desired format
dedicatedAttachKey := ""
// Track current files, used to determine existing dedicated and global resources
currentFiles := make(map[string]map[TResourceType]map[TResourceName]TResourceProperties)
for resourceType, resourceObj := range tf.Resource {
vmList := mapset.NewSetFromSlice(VMTypes)
for resourceName, resourceProps := range resourceObj {
var newResourceName string
if vmList.Contains(resourceType) {
// Overwrite with the changes to the VM properties
resourceProps = vmProperties
newResourceName = generatedName
} else {
if logicalID == nil {
newResourceName = fmt.Sprintf("%s-%s", generatedName, resourceName)
} else {
newResourceName = fmt.Sprintf("%s-%s", string(*logicalID), resourceName)
}
}
// Determine the scope value (default to 'default')
var scope string
if s, has := resourceProps[PropScope]; has {
scope = s.(string)
delete(resourceProps, PropScope)
} else {
scope = ValScopeDefault
}
// Determine the filename and resource name based off of the scope value
var filename string
if scope == ValScopeDefault {
// Default scope, filename is just the resource name (instance-XXXX)
filename = generatedName
} else if strings.HasPrefix(scope, ValScopeDedicated) {
// Get current files
if len(currentFiles) == 0 {
if files, err := p.listCurrentTfFiles(); err == nil {
currentFiles = files
} else {
return nil, err
}
}
// Dedicated scope, filename has a scope identifier and the generated name or logical
// ID: <scope-id>_dedicated_<instance-XXXX|logicalID>
var identifier string
if strings.Contains(scope, "-") {
identifier = strings.SplitN(scope, "-", 2)[1]
} else {
identifier = "default"
}
// And the resource name as <scopeID>-<instance-XXXX|logicalID>-<resourceName>
var key string
if logicalID == nil {
// On a rolling update, the dedicated file for a scaler group is not removed, search
// for an orphaned file with the appropriate format to attach
allKeys, orphanKeys := findDedicatedAttachmentKeys(currentFiles, identifier)
if len(orphanKeys) == 0 {
// No orphans, choose the lowest available index based on the existing files
index := 1
for ; ; index = index + 1 {
match := false
for _, existingKey := range allKeys {
if existingKey == strconv.Itoa(index) {
match = true
break
}
}
if !match {
break
}
}
key = strconv.Itoa(index)
logger.Info("decompose",
"msg", fmt.Sprintf("No orphaned attachment with prefix '%v-%s', using current name: %s", identifier, scopeDedicated, key))
} else {
// At least 1 orphaned file exists, pick the index with the lowest index
key = getLowestDedicatedOrphanIndex(orphanKeys)
for _, instID := range orphanKeys {
key = instID
break
}
logger.Info("decompose",
"msg", fmt.Sprintf("Using orphaned attachment '%s' for prefix '%s-%s'", key, identifier, scopeDedicated))
}
} else {
key = string(*logicalID)
}
filename = fmt.Sprintf("%s_%s_%s", identifier, scopeDedicated, key)
dedicatedAttachKey = key
newResourceName = fmt.Sprintf("%s-%s-%s", identifier, key, resourceName)
} else {
// Get current files
if len(currentFiles) == 0 {
if files, err := p.listCurrentTfFiles(); err == nil {
currentFiles = files
} else {
return nil, err
}
}
// Global scope, filename is just the given scope with a "global" suffix
filename = fmt.Sprintf("%s_%s", scope, scopeGlobal)
// And the resource name has the given scope as the prefix
newResourceName = fmt.Sprintf("%s-%s", scope, resourceName)
}
// Get the associated value in the file map
tfPersistence, has := fileMap[filename]
if !has {
resourceMap := make(map[TResourceType]map[TResourceName]TResourceProperties)
tfPersistence = &TFormat{Resource: resourceMap}
fileMap[filename] = tfPersistence
}
resourceNameMap, has := tfPersistence.Resource[resourceType]
if !has {
resourceNameMap = make(map[TResourceName]TResourceProperties)
tfPersistence.Resource[resourceType] = resourceNameMap
}
resourceNameMap[TResourceName(newResourceName)] = resourceProps
}
}
// Update the vmProperties with the infrakit.attach tag
attach := []string{}
for filename := range fileMap {
if filename == generatedName {
continue
}
attach = append(attach, filename)
}
if len(attach) > 0 {
sort.Strings(attach)
tags := map[string]string{
attachTag: strings.Join(attach, ","),
}
mergeTagsIntoVMProps(vmType, vmProperties, tags)
}
currentFilenames := make(map[string]struct{}, len(currentFiles))
for filename := range currentFiles {
currentFilenames[filename] = struct{}{}
}
result := decomposedFiles{
FileMap: fileMap,
CurrentFiles: currentFilenames,
DedicatedAttachKey: dedicatedAttachKey,
}
return &result, nil
}
// getLowestDedicatedOrphanIndex gets the lowest numerical slice value
func getLowestDedicatedOrphanIndex(data []string) string {
// All values should be ints as strings (but handle non-ints), convert and sort
ints := []int{}
other := []string{}
for _, v := range data {
if intVal, err := strconv.Atoi(v); err == nil {
ints = append(ints, intVal)
} else {
other = append(other, v)
}
}
if len(ints) > 0 {
sort.Ints(ints)
return strconv.Itoa(ints[0])
}
sort.Strings(other)
return other[0]
}
// writeTerraformFiles writes *.tf.json[.new] files for each entry in the given fileMap
func (p *plugin) writeTerraformFiles(fileMap map[string]*TFormat, currentFiles map[string]struct{}) ([]string, error) {
// First verify that there are no formatting errors
dataMap := make(map[string][]byte, len(fileMap))
for filename, tfVal := range fileMap {
buff, err := json.MarshalIndent(tfVal, " ", " ")
if err != nil {
return []string{}, err
}
dataMap[filename] = buff
}
// Track files written
paths := []string{}
// And write out each file, override data in tf.json if it already exists
for filename, buff := range dataMap {
var path string
if _, has := currentFiles[filename+".tf.json"]; has {
path = filepath.Join(p.Dir, filename+".tf.json")
logger.Info("writeTerraformFiles", "msg", fmt.Sprintf("Overriding data in file: %v", path))
} else {
path = filepath.Join(p.Dir, filename+".tf.json.new")
}
logger.Info("writeTerraformFiles", "file", path)
logger.Debug("writeTerraformFiles", "file", path, "data", string(buff), "V", debugV1)
paths = append(paths, path)
err := afero.WriteFile(p.fs, path, buff, 0644)
if err != nil {
return paths, err
}
}
return paths, nil
}
// listCurrentTfFiles populates the map with the names of all tf.json and tf.json.new files
func (p *plugin) listCurrentTfFiles() (map[string]map[TResourceType]map[TResourceName]TResourceProperties, error) {
// Ensure that the target directory exists
if _, err := os.Stat(p.Dir); err != nil {
logger.Warn("listCurrentTfFiles", "dir", p.Dir, "error", err)
return nil, err
}
result := make(map[string]map[TResourceType]map[TResourceName]TResourceProperties)
fs := &afero.Afero{Fs: p.fs}
err := fs.Walk(p.Dir,
func(path string, info os.FileInfo, err error) error {
if err != nil {
if os.IsNotExist(err) {
// If the file has been removed just ignore it
logger.Debug("listCurrentTfFiles", "msg", fmt.Sprintf("Ignoring file %s", path), "error", err, "V", debugV3)
return nil
}
logger.Error("listCurrentTfFiles", "msg", fmt.Sprintf("Failed to process file %s", path), "error", err)
return err
}
matches := tfFileRegex.FindStringSubmatch(info.Name())
if len(matches) == 3 {
buff, err := ioutil.ReadFile(filepath.Join(p.Dir, info.Name()))
if err != nil {
if os.IsNotExist(err) {
logger.Debug("listCurrentTfFiles", "msg", fmt.Sprintf("Ignoring removed file %s", path), "error", err)
return nil
}
logger.Warn("listCurrentTfFiles", "msg", fmt.Sprintf("Cannot read file %s", path))
return err
}
tf := TFormat{}
if err = types.AnyBytes(buff).Decode(&tf); err != nil {
return err
}
props := make(map[TResourceType]map[TResourceName]TResourceProperties)
for resType, resNameProps := range tf.Resource {
for resName, resProps := range resNameProps {
if _, has := props[resType]; !has {
props[resType] = make(map[TResourceName]TResourceProperties)
}
props[resType][resName] = resProps
}
}
result[info.Name()] = props
}
return nil
},
)
if err != nil {
return nil, err
}
return result, nil
}
// findOrphanedDedicatedAttachmentKeys proceeses the current files to determine:
// - All files that match the scope patten (ie, <scopeID>_dedicated_*)
// - A file with the given patten that is not already attached to an instance
// Returns all matching dedicated keys and those that are orphaned
func findDedicatedAttachmentKeys(currentFiles map[string]map[TResourceType]map[TResourceName]TResourceProperties, scopeID string) ([]string, []string) {
// Find all files that match this scope ID and scope
allFilesMap := make(map[string]string)
// And those that are orphaned
orphanedFilesMap := make(map[string]string)
for filename := range currentFiles {
matches := dedicatedScopedFileRegex.FindStringSubmatch(filename)
if len(matches) != 4 {
continue
}
if matches[1] != scopeID {
logger.Debug("findDedicatedAttachmentKeys", "msg", fmt.Sprintf("Ignoring file '%s', scope ID '%s' does not match", filename, scopeID), "V", debugV1)
continue
}
logger.Info("findDedicatedAttachmentKeys", "msg", fmt.Sprintf("Found candidate file '%s' for scope ID '%s'", filename, scopeID))
fileKey := strings.Split(filename, ".")[0]
allFilesMap[fileKey] = matches[2]
orphanedFilesMap[fileKey] = matches[2]
}
if len(allFilesMap) == 0 {
logger.Info("findDedicatedAttachmentKeys", "msg", fmt.Sprintf("No candidate attchment files for scope ID '%s'", scopeID))
return []string{}, []string{}
}
// Prune the candidate files that already have attachments
supportedVMs := mapset.NewSetFromSlice(VMTypes)
for filename, resTypeNameProps := range currentFiles {
matches := instanceTfFileRegex.FindStringSubmatch(filename)
if len(matches) != 4 {
continue
}
for resType, resNameProps := range resTypeNameProps {
if !supportedVMs.Contains(resType) {
continue
}
for _, vmProps := range resNameProps {
tags := parseTerraformTags(resType, vmProps)
attachTag, has := tags[attachTag]
if !has {
continue
}
for _, tag := range strings.Split(attachTag, ",") {
if _, contains := allFilesMap[tag]; contains {
logger.Info("findDedicatedAttachmentKeys", "msg", fmt.Sprintf("Attachment '%s' is used in %s for scope ID '%s'", tag, filename, scopeID))
delete(orphanedFilesMap, tag)
}
}
}
}
}
allMatches := []string{}
for _, v := range allFilesMap {
allMatches = append(allMatches, v)
}
orphans := []string{}
for _, v := range orphanedFilesMap {
orphans = append(orphans, v)
}
logger.Info("findDedicatedAttachmentKeys",
"msg",
fmt.Sprintf("Detected %v matching files and %v orphan attachments for scope ID '%v': %v",
len(allMatches),
len(orphans),
scopeID,
orphans))
return allMatches, orphans
}
// ensureUniqueFile returns a filename that is not in use
func ensureUniqueFile(dir string) string {
// use timestamp as instance id
n := fmt.Sprintf("instance-%d", time.Now().Unix())
// if we can open then we have to try again... the file cannot exist currently
if f, err := os.Open(filepath.Join(dir, n) + ".tf.json"); err == nil {
f.Close()
return ensureUniqueFile(dir)
}
if f, err := os.Open(filepath.Join(dir, n) + ".tf.json.new"); err == nil {
f.Close()
return ensureUniqueFile(dir)
}
return n
}
// Provision creates a new instance based on the spec.
func (p *plugin) Provision(spec instance.Spec) (*instance.ID, error) {
// Because the format of the spec.Properties is simply the same tf.json
// we simply look for vm instance and merge in the tags, and user init, etc.
// Hold the fs lock for the duration since the file is written at the end
p.fsLock.Lock()
defer func() {
p.clearCachedInstances()
p.fsLock.Unlock()
}()
name := ensureUniqueFile(p.Dir)
id := instance.ID(name)
logger.Info("Provision", "instance-id", name)
// Decode the given spec and find the VM resource
tf := TFormat{}
err := spec.Properties.Decode(&tf)
if err != nil {
return nil, err
}
vmType, _, vmProps, err := FindVM(&tf)
if err != nil {
return nil, err
}
if vmProps == nil {
return nil, fmt.Errorf("no-vm-instance-in-spec")
}
// Add Infrakit-specific tags to the user-defined VM properties
handleProvisionTags(spec, id, vmType, vmProps)
// Merge the init scripts into the VM properties
mergeInitScript(spec, id, vmType, vmProps)
// Decompose the spec into scope'd files
decomposedFiles, err := p.decompose(spec.LogicalID, name, &tf, vmType, vmProps)
if err != nil {
return nil, err
}
// Render any instance specific variables in all of the decomposed files
for _, tf := range decomposedFiles.FileMap {
for _, resNameProps := range tf.Resource {
for _, resProps := range resNameProps {
if err = renderInstVars(&resProps, id, spec.LogicalID, decomposedFiles.DedicatedAttachKey); err != nil {
return nil, err
}
}
}
}
// Handle any platform specific updates to the VM properties prior to writing out
platformSpecificUpdates(vmType, TResourceName(name), spec.LogicalID, vmProps)
// Write out the tf.json[.new] files
if _, err = p.writeTerraformFiles(decomposedFiles.FileMap, decomposedFiles.CurrentFiles); err != nil {
return nil, err
}
// And apply the updates
return &id, p.terraformApply()
}