/
subnetunsafe.go
executable file
·1520 lines (1359 loc) · 45.3 KB
/
subnetunsafe.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
/*
* Copyright 2018-2023, CS Systemes d'Information, http://csgroup.eu
*
* 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
*
* http://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 operations
import (
"context"
"fmt"
"reflect"
"strings"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"github.com/CS-SI/SafeScale/v22/lib/backend/iaas/userdata"
"github.com/CS-SI/SafeScale/v22/lib/backend/resources"
"github.com/CS-SI/SafeScale/v22/lib/backend/resources/abstract"
"github.com/CS-SI/SafeScale/v22/lib/backend/resources/enums/ipversion"
"github.com/CS-SI/SafeScale/v22/lib/backend/resources/enums/networkproperty"
"github.com/CS-SI/SafeScale/v22/lib/backend/resources/enums/securitygroupproperty"
"github.com/CS-SI/SafeScale/v22/lib/backend/resources/enums/securitygroupruledirection"
"github.com/CS-SI/SafeScale/v22/lib/backend/resources/enums/subnetproperty"
"github.com/CS-SI/SafeScale/v22/lib/backend/resources/enums/subnetstate"
"github.com/CS-SI/SafeScale/v22/lib/backend/resources/operations/consts"
propertiesv1 "github.com/CS-SI/SafeScale/v22/lib/backend/resources/properties/v1"
"github.com/CS-SI/SafeScale/v22/lib/utils"
"github.com/CS-SI/SafeScale/v22/lib/utils/data"
"github.com/CS-SI/SafeScale/v22/lib/utils/data/serialize"
"github.com/CS-SI/SafeScale/v22/lib/utils/debug"
"github.com/CS-SI/SafeScale/v22/lib/utils/fail"
)
// unsafeGetDefaultRouteIP ...
func (instance *Subnet) unsafeGetDefaultRouteIP(ctx context.Context) (_ string, ferr fail.Error) {
var ip string
xerr := instance.Inspect(ctx, func(clonable data.Clonable, _ *serialize.JSONProperties) fail.Error {
as, ok := clonable.(*abstract.Subnet)
if !ok {
return fail.InconsistentError("'*abstract.Subnet' expected, '%s' provided", reflect.TypeOf(clonable).String())
}
if as.VIP != nil && as.VIP.PrivateIP != "" {
ip = as.VIP.PrivateIP
return nil
}
if len(as.GatewayIDs) > 0 {
hostInstance, innerErr := LoadHost(ctx, instance.Service(), as.GatewayIDs[0])
if innerErr != nil {
return innerErr
}
var inErr fail.Error
ip, inErr = hostInstance.GetPrivateIP(ctx)
if inErr != nil {
return inErr
}
return nil
}
return fail.NotFoundError("failed to find default route IP: no gateway defined")
})
return ip, xerr
}
// unsafeGetVirtualIP returns an abstract.VirtualIP used by gateway HA
func (instance *Subnet) unsafeGetVirtualIP(ctx context.Context) (vip *abstract.VirtualIP, ferr fail.Error) {
xerr := instance.Inspect(ctx, func(clonable data.Clonable, props *serialize.JSONProperties) fail.Error {
as, ok := clonable.(*abstract.Subnet)
if !ok {
return fail.InconsistentError("'*abstract.Subnet' expected, '%s' provided", reflect.TypeOf(clonable).String())
}
vip = as.VIP
return nil
})
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
return nil, fail.Wrap(xerr, "cannot get Subnet virtual IP")
}
if vip == nil {
return nil, fail.NotFoundError("failed to find Virtual IP bound to gateways for Subnet '%s'", instance.GetName())
}
return vip, nil
}
// unsafeGetCIDR returns the CIDR of the network
// Intended to be used when instance is notoriously not nil (because previously checked)
func (instance *Subnet) unsafeGetCIDR(ctx context.Context) (_ string, ferr fail.Error) {
var cidr string
xerr := instance.Inspect(ctx, func(clonable data.Clonable, _ *serialize.JSONProperties) fail.Error {
as, ok := clonable.(*abstract.Subnet)
if !ok {
return fail.InconsistentError("'*abstract.Subnet' expected, '%s' provided", reflect.TypeOf(clonable).String())
}
cidr = as.CIDR
return nil
})
return cidr, xerr
}
// unsafeGetState returns the state of the network
// Intended to be used when rs is notoriously not null (because previously checked)
func (instance *Subnet) unsafeGetState(ctx context.Context) (_ subnetstate.Enum, ferr fail.Error) {
var state subnetstate.Enum
xerr := instance.Inspect(ctx, func(clonable data.Clonable, _ *serialize.JSONProperties) fail.Error {
as, ok := clonable.(*abstract.Subnet)
if !ok {
return fail.InconsistentError("'*abstract.Subnet' expected, '%s' provided", reflect.TypeOf(clonable).String())
}
state = as.State
return nil
})
return state, xerr
}
// unsafeAbandonHost is the non goroutine-safe version of UnbindHost, without parameter validation, that does the real work
func (instance *Subnet) unsafeAbandonHost(props *serialize.JSONProperties, hostID string) fail.Error {
return props.Alter(subnetproperty.HostsV1, func(clonable data.Clonable) fail.Error {
shV1, ok := clonable.(*propertiesv1.SubnetHosts)
if !ok {
return fail.InconsistentError("'*propertiesv1.SubnetHosts' expected, '%s' provided", reflect.TypeOf(clonable).String())
}
hostName, found := shV1.ByID[hostID]
if found {
delete(shV1.ByName, hostName)
delete(shV1.ByID, hostID)
}
return nil
})
}
// unsafeHasVirtualIP tells if the Subnet uses a VIP a default route
func (instance *Subnet) unsafeHasVirtualIP(ctx context.Context) (bool, fail.Error) {
var found bool
xerr := instance.Inspect(ctx, func(clonable data.Clonable, _ *serialize.JSONProperties) fail.Error {
as, ok := clonable.(*abstract.Subnet)
if !ok {
return fail.InconsistentError("'*abstract.Subnet' expected, '%s' provided", reflect.TypeOf(clonable).String())
}
found = as.VIP != nil
return nil
})
return found, xerr
}
// UnsafeCreateSecurityGroups creates the 3 Security Groups needed by a Subnet
// 'ctx' may contain values "CurrentNetworkAbstractContextKey" and "CurrentNetworkPropertiesContextKey", corresponding respectively
// to Network abstract and Network properties; these values may be used by SecurityGroup.Create() not to try to Alter networkInstance directly (might be inside a code already altering it)
func (instance *Subnet) unsafeCreateSecurityGroups(
inctx context.Context, networkInstance resources.Network, keepOnFailure bool, defaultSSHPort int32,
) (sa, sb, sc resources.SecurityGroup, _ fail.Error) {
ctx, cancel := context.WithCancel(inctx)
defer cancel()
type result struct {
a resources.SecurityGroup
b resources.SecurityGroup
c resources.SecurityGroup
rErr fail.Error
}
chRes := make(chan result)
go func() {
defer close(chRes)
gres, _ := func() (_ result, ferr fail.Error) {
defer fail.OnPanic(&ferr)
networkID, err := networkInstance.GetID()
if err != nil {
ar := result{nil, nil, nil, fail.ConvertError(err)}
return ar, ar.rErr
}
networkName := networkInstance.GetName()
subnetGWSG, xerr := instance.createGWSecurityGroup(ctx, networkID, networkName, keepOnFailure, defaultSSHPort)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
ar := result{nil, nil, nil, xerr}
return ar, ar.rErr
}
defer func() {
derr := instance.undoCreateSecurityGroup(cleanupContextFrom(ctx), &ferr, keepOnFailure, subnetGWSG)
if derr != nil {
logrus.WithContext(ctx).Warnf(derr.Error())
}
}()
subnetPublicIPSG, xerr := instance.createPublicIPSecurityGroup(ctx, networkID, networkName, keepOnFailure)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
ar := result{nil, nil, nil, xerr}
return ar, ar.rErr
}
defer func() {
derr := instance.undoCreateSecurityGroup(cleanupContextFrom(ctx), &ferr, keepOnFailure, subnetPublicIPSG)
if derr != nil {
logrus.WithContext(ctx).Warnf(derr.Error())
}
}()
subnetInternalSG, xerr := instance.createInternalSecurityGroup(ctx, networkID, networkName, keepOnFailure)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
ar := result{nil, nil, nil, xerr}
return ar, ar.rErr
}
defer func() {
derr := instance.undoCreateSecurityGroup(cleanupContextFrom(ctx), &ferr, keepOnFailure, subnetInternalSG)
if derr != nil {
logrus.WithContext(ctx).Warnf(derr.Error())
}
}()
xerr = subnetGWSG.BindToSubnet(ctx, instance, resources.SecurityGroupEnable, resources.KeepCurrentSecurityGroupMark)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
ar := result{nil, nil, nil, xerr}
return ar, ar.rErr
}
defer func() {
ferr = debug.InjectPlannedFail(ferr)
if ferr != nil && !keepOnFailure {
if derr := subnetGWSG.UnbindFromSubnet(cleanupContextFrom(ctx), instance); derr != nil {
_ = ferr.AddConsequence(fail.Wrap(derr, "cleaning up on %s, failed to unbind Security Group for gateways from Subnet", ActionFromError(ferr)))
}
}
}()
xerr = subnetInternalSG.BindToSubnet(ctx, instance, resources.SecurityGroupEnable, resources.MarkSecurityGroupAsDefault)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
ar := result{nil, nil, nil, xerr}
return ar, ar.rErr
}
ar := result{subnetGWSG, subnetInternalSG, subnetPublicIPSG, nil}
return ar, ar.rErr
}()
chRes <- gres
}() // nolint
select {
case res := <-chRes:
return res.a, res.b, res.c, res.rErr
case <-ctx.Done():
<-chRes // wait for defer
return nil, nil, nil, fail.ConvertError(ctx.Err())
case <-inctx.Done():
<-chRes // wait for defer
return nil, nil, nil, fail.ConvertError(inctx.Err())
}
}
// createGWSecurityGroup creates a Security Group that will be applied to gateways of the Subnet
func (instance *Subnet) createGWSecurityGroup(
ctx context.Context, networkID, networkName string, keepOnFailure bool, defaultSSHPort int32,
) (_ resources.SecurityGroup, ferr fail.Error) {
// Creates security group for hosts in Subnet to allow internal access
sgName := fmt.Sprintf(subnetGWSecurityGroupNamePattern, instance.GetName(), networkName)
sg, xerr := NewSecurityGroup(instance.Service())
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
return nil, xerr
}
description := fmt.Sprintf(subnetGWSecurityGroupDescriptionPattern, instance.GetName(), networkName)
xerr = sg.Create(ctx, networkID, sgName, description, nil)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
return nil, xerr
}
sgid, err := sg.GetID()
if err != nil {
return nil, fail.ConvertError(err)
}
defer func() {
ferr = debug.InjectPlannedFail(ferr)
if ferr != nil && !keepOnFailure {
if derr := sg.Delete(cleanupContextFrom(ctx), true); derr != nil {
_ = ferr.AddConsequence(fail.Wrap(derr, "cleaning up on %s, failed to delete Security Group '%s'", ActionFromError(ferr), sgName))
}
}
}()
rules := abstract.SecurityGroupRules{
{
Description: "[ingress][ipv4][tcp] Allow SSH",
Direction: securitygroupruledirection.Ingress,
PortFrom: defaultSSHPort,
EtherType: ipversion.IPv4,
Protocol: "tcp",
Sources: []string{"0.0.0.0/0"},
Targets: []string{sgid},
},
{
Description: "[ingress][ipv6][tcp] Allow SSH",
Direction: securitygroupruledirection.Ingress,
PortFrom: defaultSSHPort,
EtherType: ipversion.IPv6,
Protocol: "tcp",
Sources: []string{"::/0"},
Targets: []string{sgid},
},
{
Description: "[ingress][ipv4][icmp] Allow everything",
Direction: securitygroupruledirection.Ingress,
EtherType: ipversion.IPv4,
Protocol: "icmp",
Sources: []string{"0.0.0.0/0"},
Targets: []string{sgid},
},
{
Description: "[ingress][ipv6][icmp] Allow everything",
Direction: securitygroupruledirection.Ingress,
EtherType: ipversion.IPv6,
Protocol: "icmp",
Sources: []string{"::/0"},
Targets: []string{sgid},
},
}
xerr = sg.AddRules(ctx, rules)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
return nil, xerr
}
if defaultSSHPort != 22 {
rules := abstract.SecurityGroupRules{
{
Description: "[ingress][ipv4][tcp] Temporary Allow SSH",
Direction: securitygroupruledirection.Ingress,
PortFrom: 22,
EtherType: ipversion.IPv4,
Protocol: "tcp",
Sources: []string{"0.0.0.0/0"},
Targets: []string{sgid},
},
{
Description: "[ingress][ipv6][tcp] Temporary Allow SSH",
Direction: securitygroupruledirection.Ingress,
PortFrom: 22,
EtherType: ipversion.IPv6,
Protocol: "tcp",
Sources: []string{"::/0"},
Targets: []string{sgid},
},
}
xerr = sg.AddRules(ctx, rules)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
return nil, xerr
}
}
return sg, nil
}
// createPublicIPSecurityGroup creates a Security Group to be applied to host of the Subnet with public IP that is not a gateway
func (instance *Subnet) createPublicIPSecurityGroup(
ctx context.Context, networkID, networkName string, keepOnFailure bool,
) (_ resources.SecurityGroup, ferr fail.Error) {
// Creates security group for hosts in Subnet to allow internal access
sgName := fmt.Sprintf(subnetPublicIPSecurityGroupNamePattern, instance.GetName(), networkName)
var sgInstance resources.SecurityGroup
var xerr fail.Error
sgInstance, xerr = NewSecurityGroup(instance.Service())
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
return nil, xerr
}
description := fmt.Sprintf(subnetPublicIPSecurityGroupDescriptionPattern, instance.GetName(), networkName)
xerr = sgInstance.Create(ctx, networkID, sgName, description, nil)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
return nil, xerr
}
sgid, err := sgInstance.GetID()
if err != nil {
return nil, fail.ConvertError(err)
}
defer func() {
ferr = debug.InjectPlannedFail(ferr)
if ferr != nil && !keepOnFailure {
if derr := sgInstance.Delete(cleanupContextFrom(ctx), true); derr != nil {
_ = ferr.AddConsequence(fail.Wrap(derr, "cleaning up on %s, failed to delete Security Group '%s'", ActionFromError(ferr), sgName))
}
}
}()
rules := abstract.SecurityGroupRules{
{
Description: "[egress][ipv4][all] Allow everything",
Direction: securitygroupruledirection.Egress,
EtherType: ipversion.IPv4,
Sources: []string{sgid},
Targets: []string{"0.0.0.0/0"},
},
{
Description: "[egress][ipv6][all] Allow everything",
Direction: securitygroupruledirection.Egress,
EtherType: ipversion.IPv6,
Sources: []string{sgid},
Targets: []string{"::0/0"},
},
}
xerr = sgInstance.AddRules(ctx, rules)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
return nil, xerr
}
return sgInstance, nil
}
// Starting from here, delete the Security Group if exiting with error
func (instance *Subnet) undoCreateSecurityGroup(
ctx context.Context, errorPtr *fail.Error, keepOnFailure bool, sg resources.SecurityGroup,
) fail.Error {
if errorPtr == nil {
return fail.NewError("trying to undo an action based on the content of a nil fail.Error; undo cannot be run")
}
if *errorPtr != nil && !keepOnFailure {
sgName := sg.GetName()
if derr := sg.Delete(ctx, true); derr != nil {
_ = (*errorPtr).AddConsequence(fail.Wrap(derr, "cleaning up on %s, failed to remove Security Group for gateways '%s' of Subnet '%s'", ActionFromError(*errorPtr), sgName, instance.GetName()))
}
}
return nil
}
// Creates a Security Group to be applied on Hosts in Subnet to allow internal access
func (instance *Subnet) createInternalSecurityGroup(
ctx context.Context, networkID, networkName string, keepOnFailure bool,
) (_ resources.SecurityGroup, ferr fail.Error) {
sgName := fmt.Sprintf(subnetInternalSecurityGroupNamePattern, instance.GetName(), networkName)
cidr, xerr := instance.unsafeGetCIDR(ctx)
if xerr != nil {
return nil, xerr
}
var sg resources.SecurityGroup
sg, xerr = NewSecurityGroup(instance.Service())
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
return nil, xerr
}
description := fmt.Sprintf(subnetInternalSecurityGroupDescriptionPattern, instance.GetName(), networkName)
xerr = sg.Create(ctx, networkID, sgName, description, nil)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
return nil, xerr
}
sgid, err := sg.GetID()
if err != nil {
return nil, fail.ConvertError(err)
}
defer func() {
ferr = debug.InjectPlannedFail(ferr)
if ferr != nil && !keepOnFailure {
if derr := sg.Delete(cleanupContextFrom(ctx), true); derr != nil {
_ = ferr.AddConsequence(fail.Wrap(derr, "cleaning up on %s, failed to remove Security Group '%s'", ActionFromError(ferr), sgName))
}
}
}()
// adds rules that depend on Security Group ID
rules := abstract.SecurityGroupRules{
{
Description: fmt.Sprintf("[egress][ipv4][all] Allow all from %s", cidr),
EtherType: ipversion.IPv4,
Direction: securitygroupruledirection.Egress,
Sources: []string{sgid},
Targets: []string{"0.0.0.0/0"},
},
{
Description: fmt.Sprintf("[egress][ipv6][all] Allow all from %s", cidr),
EtherType: ipversion.IPv6,
Direction: securitygroupruledirection.Egress,
Sources: []string{sgid},
Targets: []string{"::0/0"},
},
{
Description: fmt.Sprintf("[ingress][ipv4][all] Allow LAN traffic in %s", cidr),
EtherType: ipversion.IPv4,
Direction: securitygroupruledirection.Ingress,
Sources: []string{sgid},
Targets: []string{sgid},
},
{
Description: fmt.Sprintf("[ingress][ipv6][all] Allow LAN traffic in %s", cidr),
EtherType: ipversion.IPv6,
Direction: securitygroupruledirection.Ingress,
Sources: []string{sgid},
Targets: []string{sgid},
},
}
xerr = sg.AddRules(ctx, rules)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
return nil, xerr
}
return sg, nil
}
func (instance *Subnet) unsafeCreateSubnet(inctx context.Context, req abstract.SubnetRequest) (_ fail.Error) {
ctx, cancel := context.WithCancel(inctx)
defer cancel()
type result struct {
rErr fail.Error
}
chRes := make(chan result)
go func() {
defer close(chRes)
gres, _ := func() (_ result, ferr fail.Error) {
defer fail.OnPanic(&ferr)
if req.CIDR == "" {
xerr := fail.InvalidRequestError("invalid empty string value for 'req.CIDR'")
ar := result{xerr}
return ar, ar.rErr
}
networkInstance, abstractNetwork, xerr := instance.validateNetwork(ctx, &req)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
ar := result{xerr}
return ar, ar.rErr
}
// Check if Subnet already exists and is managed by SafeScale
xerr = instance.checkUnicity(ctx, req)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
ar := result{xerr}
return ar, ar.rErr
}
// Verify the CIDR is not routable
xerr = instance.validateCIDR(ctx, &req, *abstractNetwork)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
xerr := fail.Wrap(xerr, "failed to validate CIDR '%s' for Subnet '%s'", req.CIDR, req.Name)
ar := result{xerr}
return ar, ar.rErr
}
svc := instance.Service()
abstractSubnet, xerr := svc.CreateSubnet(ctx, req)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
switch xerr.(type) {
case *fail.ErrNotFound, *fail.ErrInvalidRequest, *fail.ErrTimeout:
ar := result{xerr}
return ar, ar.rErr
default:
ar := result{xerr}
return ar, ar.rErr
}
}
// Starting from here, delete Subnet if exiting with error
defer func() {
ferr = debug.InjectPlannedFail(ferr)
if ferr != nil && abstractSubnet != nil && !req.KeepOnFailure {
if derr := instance.deleteSubnetThenWaitCompletion(cleanupContextFrom(ctx), abstractSubnet.ID); derr != nil {
_ = ferr.AddConsequence(fail.Wrap(derr, "cleaning up on %s, failed to delete Subnet", ActionFromError(ferr)))
}
}
}()
// Write Subnet object metadata and updates the service cache
xerr = instance.Carry(ctx, abstractSubnet)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
ar := result{xerr}
return ar, ar.rErr
}
// Starting from here, delete Subnet metadata if exiting with error
defer func() {
ferr = debug.InjectPlannedFail(ferr)
if ferr != nil && !req.KeepOnFailure {
theID, _ := instance.GetID()
if derr := instance.MetadataCore.Delete(cleanupContextFrom(ctx)); derr != nil {
_ = ferr.AddConsequence(fail.Wrap(derr, "cleaning up on %s, failed to delete Subnet metadata", ActionFromError(ferr)))
}
if ka, err := instance.Service().GetCache(ctx); err == nil {
if ka != nil {
if theID != "" {
_ = ka.Delete(ctx, fmt.Sprintf("%T/%s", instance, theID))
}
}
}
}
}()
if req.DefaultSSHPort == 0 {
req.DefaultSSHPort = 22
}
subnetGWSG, subnetInternalSG, subnetPublicIPSG, xerr := instance.unsafeCreateSecurityGroups(ctx, networkInstance, req.KeepOnFailure, int32(req.DefaultSSHPort))
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
ar := result{xerr}
return ar, ar.rErr
}
defer func() {
ferr = debug.InjectPlannedFail(ferr)
if ferr != nil && !req.KeepOnFailure {
a, _ := subnetGWSG.GetID()
b, _ := subnetInternalSG.GetID()
c, _ := subnetPublicIPSG.GetID()
derr := instance.deleteSecurityGroups(cleanupContextFrom(ctx), [3]string{a, b, c})
if derr != nil {
_ = ferr.AddConsequence(fail.Wrap(derr, "cleaning up on failure, failed to delete Security Groups"))
}
}
}()
caps, xerr := svc.GetCapabilities(ctx)
if xerr != nil {
ar := result{xerr}
return ar, ar.rErr
}
failover := req.HA
if failover {
if caps.PrivateVirtualIP {
logrus.Info("Driver support private Virtual IP, honoring the failover setup for gateways.")
} else {
logrus.WithContext(ctx).Warnf("Driver does not support private Virtual IP, cannot set up failover of Subnet default route.")
failover = false
}
}
// Creates VIP for gateways if asked for
var avip *abstract.VirtualIP
if failover {
a, err := subnetGWSG.GetID()
if err != nil {
ar := result{fail.ConvertError(err)}
return ar, ar.rErr
}
avip, xerr = svc.CreateVIP(ctx, abstractSubnet.Network, abstractSubnet.ID, fmt.Sprintf(virtualIPNamePattern, abstractSubnet.Name, networkInstance.GetName()), []string{a})
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
xerr := fail.Wrap(xerr, "failed to create VIP")
ar := result{xerr}
return ar, ar.rErr
}
// Starting from here, delete VIP if exists with error
defer func() {
ferr = debug.InjectPlannedFail(ferr)
if ferr != nil && abstractSubnet != nil && abstractSubnet.VIP != nil && !req.KeepOnFailure {
if derr := svc.DeleteVIP(cleanupContextFrom(ctx), abstractSubnet.VIP); derr != nil {
_ = ferr.AddConsequence(fail.Wrap(derr, "cleaning up on %s, failed to delete VIP", ActionFromError(ferr)))
}
}
}()
}
xerr = instance.Alter(ctx, func(clonable data.Clonable, props *serialize.JSONProperties) fail.Error {
as, ok := clonable.(*abstract.Subnet)
if !ok {
return fail.InconsistentError("'*abstract.Subnet' expected, '%s' provided", reflect.TypeOf(clonable).String())
}
var err error
as.VIP = avip
as.State = subnetstate.GatewayCreation
as.GWSecurityGroupID, err = subnetGWSG.GetID()
if err != nil {
return fail.ConvertError(err)
}
as.InternalSecurityGroupID, err = subnetInternalSG.GetID()
if err != nil {
return fail.ConvertError(err)
}
as.PublicIPSecurityGroupID, err = subnetPublicIPSG.GetID()
if err != nil {
return fail.ConvertError(err)
}
a, err := subnetGWSG.GetID()
if err != nil {
return fail.ConvertError(err)
}
// Creates the bind between the Subnet default security group and the Subnet
return props.Alter(subnetproperty.SecurityGroupsV1, func(clonable data.Clonable) fail.Error {
ssgV1, ok := clonable.(*propertiesv1.SubnetSecurityGroups)
if !ok {
return fail.InconsistentError("'*propertiesv1.SubnetSecurityGroups' expected, '%s' provided", reflect.TypeOf(clonable).String())
}
item := &propertiesv1.SecurityGroupBond{
ID: a,
Name: subnetGWSG.GetName(),
Disabled: false,
}
ssgV1.ByID[item.ID] = item
ssgV1.ByName[subnetGWSG.GetName()] = item.ID
a, err := subnetInternalSG.GetID()
if err != nil {
return fail.ConvertError(err)
}
item = &propertiesv1.SecurityGroupBond{
ID: a,
Name: subnetInternalSG.GetName(),
Disabled: false,
}
ssgV1.ByID[item.ID] = item
ssgV1.ByName[item.Name] = item.ID
return nil
})
})
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
ar := result{xerr}
return ar, ar.rErr
}
// attach Subnet to Network
xerr = networkInstance.Alter(ctx, func(_ data.Clonable, props *serialize.JSONProperties) fail.Error {
return props.Alter(networkproperty.SubnetsV1, func(clonable data.Clonable) fail.Error {
nsV1, ok := clonable.(*propertiesv1.NetworkSubnets)
if !ok {
return fail.InconsistentError("'*propertiesv1.NetworkSubnets' expected, '%s' provided", reflect.TypeOf(clonable).String())
}
nsV1.ByID[abstractSubnet.ID] = abstractSubnet.Name
nsV1.ByName[abstractSubnet.Name] = abstractSubnet.ID
return nil
})
})
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
ar := result{xerr}
return ar, ar.rErr
}
// FIXME: Disable VIP SG and port security
// Starting from here, remove Subnet from Network metadata if exiting with error
defer func() {
ferr = debug.InjectPlannedFail(ferr)
if ferr != nil && !req.KeepOnFailure {
derr := networkInstance.Alter(cleanupContextFrom(ctx), func(
_ data.Clonable, props *serialize.JSONProperties,
) fail.Error {
return props.Alter(networkproperty.SubnetsV1, func(clonable data.Clonable) fail.Error {
nsV1, ok := clonable.(*propertiesv1.NetworkSubnets)
if !ok {
return fail.InconsistentError("'*propertiesv1.NetworkSubnets' expected, '%s' provided", reflect.TypeOf(clonable).String())
}
delete(nsV1.ByID, abstractSubnet.ID)
delete(nsV1.ByName, abstractSubnet.Name)
return nil
})
})
if derr != nil {
_ = ferr.AddConsequence(fail.Wrap(derr, "cleaning up on %s, failed to detach Subnet from Network", ActionFromError(ferr)))
}
}
}()
ar := result{nil}
return ar, ar.rErr
}()
chRes <- gres
}() // nolint
select {
case res := <-chRes:
return res.rErr
case <-ctx.Done():
<-chRes // wait for cleanup
return fail.ConvertError(ctx.Err())
case <-inctx.Done():
<-chRes // wait for cleanup
return fail.ConvertError(inctx.Err())
}
}
func (instance *Subnet) unsafeFinalizeSubnetCreation(inctx context.Context) fail.Error {
ctx, cancel := context.WithCancel(inctx)
defer cancel()
type result struct {
rErr fail.Error
}
chRes := make(chan result)
go func() {
defer close(chRes)
xerr := instance.Alter(ctx, func(clonable data.Clonable, _ *serialize.JSONProperties) fail.Error {
as, ok := clonable.(*abstract.Subnet)
if !ok {
return fail.InconsistentError("'*abstract.Subnet' expected, '%s' provided", reflect.TypeOf(clonable).String())
}
as.State = subnetstate.Ready
return nil
})
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
chRes <- result{xerr}
return
}
chRes <- result{nil}
}()
select {
case res := <-chRes:
return res.rErr
case <-ctx.Done():
return fail.ConvertError(ctx.Err())
case <-inctx.Done():
return fail.ConvertError(inctx.Err())
}
}
func (instance *Subnet) unsafeCreateGateways(
inctx context.Context, req abstract.SubnetRequest, gwname string, gwSizing *abstract.HostSizingRequirements,
sgs map[string]struct{},
) (_ fail.Error) {
ctx, cancel := context.WithCancel(inctx)
defer cancel()
type result struct {
rErr fail.Error
}
chRes := make(chan result)
go func() {
defer close(chRes)
gres, _ := func() (_ result, ferr fail.Error) {
defer fail.OnPanic(&ferr)
svc := instance.Service()
if gwSizing == nil {
gwSizing = &abstract.HostSizingRequirements{MinGPU: -1}
}
template, xerr := svc.FindTemplateBySizing(ctx, *gwSizing)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
xerr := fail.Wrap(xerr, "failed to find appropriate template")
ar := result{xerr}
return ar, ar.rErr
}
// define image...
imageQuery := gwSizing.Image
if imageQuery == "" {
imageQuery = req.ImageRef
if imageQuery == "" {
cfg, xerr := svc.GetConfigurationOptions(ctx)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
ar := result{xerr}
return ar, ar.rErr
}
imageQuery = cfg.GetString("DefaultImage")
if imageQuery == "" {
imageQuery = consts.DEFAULTOS
}
}
img, xerr := svc.SearchImage(ctx, imageQuery)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
switch xerr.(type) {
case *fail.ErrNotFound:
// look for an exact match by ID
imgs, xerr := svc.ListImages(ctx, true)
xerr = debug.InjectPlannedFail(xerr)
if xerr != nil {
xerr := fail.Wrap(xerr, "failure listing images")
ar := result{xerr}
return ar, ar.rErr
}
img = nil
for _, aimg := range imgs {
if strings.Compare(aimg.ID, imageQuery) == 0 {
logrus.WithContext(ctx).Tracef("exact match by ID, ignoring jarowinkler results")
img = aimg
break
}
}
if img == nil {
xerr := fail.Wrap(xerr, "failed to find image with ID %s", imageQuery)
ar := result{xerr}
return ar, ar.rErr
}
default:
xerr := fail.Wrap(xerr, "failed to find image '%s'", imageQuery)
ar := result{xerr}
return ar, ar.rErr
}
}
gwSizing.Image = img.ID
}
subnetName := instance.GetName()
var primaryGatewayName, secondaryGatewayName string
if req.HA || gwname == "" {
primaryGatewayName = "gw-" + subnetName
} else {
primaryGatewayName = gwname
}
if req.HA {
secondaryGatewayName = "gw2-" + subnetName
}
domain := strings.Trim(req.Domain, ".")
if domain != "" {
domain = "." + domain
}
keepalivedPassword, err := utils.GeneratePassword(16)
err = debug.InjectPlannedError(err)
if err != nil {
err := fail.ConvertError(err)
ar := result{err}
return ar, ar.rErr
}
var as *abstract.Subnet
xerr = instance.Inspect(ctx, func(clonable data.Clonable, _ *serialize.JSONProperties) fail.Error {
var ok bool
as, ok = clonable.(*abstract.Subnet)
if !ok {
return fail.InconsistentError("'*abstract.Subnet' expected, '%s' provided", reflect.TypeOf(clonable).String())
}
// IDs of Security Groups to attach to Host used as gateway
if len(sgs) == 0 {
sgs = map[string]struct{}{}
}
sgs[as.GWSecurityGroupID] = struct{}{}
sgs[as.InternalSecurityGroupID] = struct{}{}
sgs[as.PublicIPSecurityGroupID] = struct{}{}
return nil
})
if xerr != nil {
ar := result{xerr}
return ar, ar.rErr
}
gwRequest := abstract.HostRequest{
ImageID: gwSizing.Image,
ImageRef: imageQuery,
Subnets: []*abstract.Subnet{as},