-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathinstance.go
More file actions
2005 lines (1727 loc) · 74.8 KB
/
instance.go
File metadata and controls
2005 lines (1727 loc) · 74.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* 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 instance
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"google.golang.org/protobuf/types/known/timestamppb"
"go.temporal.io/sdk/client"
cdb "github.com/nvidia/bare-metal-manager-rest/db/pkg/db"
"github.com/nvidia/bare-metal-manager-rest/db/pkg/db/ipam"
cdbm "github.com/nvidia/bare-metal-manager-rest/db/pkg/db/model"
"github.com/nvidia/bare-metal-manager-rest/db/pkg/db/paginator"
cdbp "github.com/nvidia/bare-metal-manager-rest/db/pkg/db/paginator"
sc "github.com/nvidia/bare-metal-manager-rest/workflow/pkg/client/site"
"github.com/nvidia/bare-metal-manager-rest/workflow/pkg/queue"
"github.com/nvidia/bare-metal-manager-rest/workflow/pkg/util"
cwsv1 "github.com/nvidia/bare-metal-manager-rest/workflow-schema/schema/site-agent/workflows/v1"
"github.com/nvidia/bare-metal-manager-rest/workflow/internal/config"
cwm "github.com/nvidia/bare-metal-manager-rest/workflow/internal/metrics"
"github.com/prometheus/client_golang/prometheus"
cwutil "github.com/nvidia/bare-metal-manager-rest/common/pkg/util"
)
// ManageInstance is an activity wrapper for managing Instance lifecycle that allows
// injecting DB access
type ManageInstance struct {
dbSession *cdb.Session
siteClientPool *sc.ClientPool
tc client.Client
cfg *config.Config
}
// Activity functions
// CreateInstanceViaSiteAgent is a Temporal activity that create an Instance in Site Controller via Site agent
func (mi ManageInstance) CreateInstanceViaSiteAgent(ctx context.Context, instanceID uuid.UUID) error {
logger := log.With().Str("Activity", "CreateInstanceViaSiteAgent").Str("Instance ID", instanceID.String()).Logger()
logger.Info().Msg("starting activity")
instanceDAO := cdbm.NewInstanceDAO(mi.dbSession)
instance, err := instanceDAO.GetByID(ctx, nil, instanceID, nil)
if err != nil {
logger.Error().Err(err).Msg("failed to retrieve Instance from DB by ID")
return err
}
logger.Info().Msg("retrieved Instance from DB")
tc, err := mi.siteClientPool.GetClientByID(instance.SiteID)
if err != nil {
logger.Error().Err(err).Msg("failed to retrieve Temporal client for Site")
return err
}
workflowOptions := client.StartWorkflowOptions{
ID: "site-instance-create-" + instanceID.String(),
TaskQueue: queue.SiteTaskQueue,
}
transactionID := &cwsv1.TransactionID{
ResourceId: instanceID.String(),
Timestamp: timestamppb.Now(),
}
// find the segment-id from the subnet which we get from the instance subnet table
interfaceDAO := cdbm.NewInterfaceDAO(mi.dbSession)
interfaces, _, err := interfaceDAO.GetAll(ctx, nil, cdbm.InterfaceFilterInput{InstanceIDs: []uuid.UUID{instanceID}}, paginator.PageInput{}, nil)
if err != nil {
logger.Error().Err(err).Msg("error retrieving interfaces")
return err
}
if len(interfaces) == 0 {
message := "no interfaces found for instance"
logger.Error().Msg(message)
return errors.New(message)
}
// get the subnet
subnetDAO := cdbm.NewSubnetDAO(mi.dbSession)
if instance.MachineID == nil {
message := "machine id in instance is nil"
logger.Error().Msg(message)
return errors.New(message)
}
// Check and add InfiniBand Interfaces to the Instance
ibiDAO := cdbm.NewInfiniBandInterfaceDAO(mi.dbSession)
ibinterfaces, _, err := ibiDAO.GetAll(
ctx,
nil,
cdbm.InfiniBandInterfaceFilterInput{
InstanceIDs: []uuid.UUID{instanceID},
},
paginator.PageInput{Limit: cdb.GetIntPtr(cdbp.TotalLimit)},
[]string{cdbm.InfiniBandPartitionRelationName},
)
if err != nil {
logger.Error().Err(err).Msg("failed to retrieve InfiniBand Interfaces from DB")
return err
}
mDAO := cdbm.NewMachineDAO(mi.dbSession)
machine, err := mDAO.GetByID(ctx, nil, *instance.MachineID, nil, false)
if err != nil {
logger.Error().Err(err).Msg("failed to retrieve Machine for Instance from DB")
return err
}
vpcDAO := cdbm.NewVpcDAO(mi.dbSession)
vpc, err := vpcDAO.GetByID(ctx, nil, instance.VpcID, nil)
if err != nil {
logger.Error().Err(err).Msg("failed to retrieve VPC for Instance from DB")
return err
}
// Check and add SSH Key Groups to the Instance
skgiaDAO := cdbm.NewSSHKeyGroupInstanceAssociationDAO(mi.dbSession)
skgias, _, err := skgiaDAO.GetAll(ctx, nil, nil, nil, []uuid.UUID{instance.ID}, nil, nil, cdb.GetIntPtr(cdbp.TotalLimit), nil)
if err != nil {
logger.Error().Err(err).Msg("failed to retrieve SSH Key Group Instance Associations from DB")
return err
}
tenantKeysetIDs := []string{}
for _, skgia := range skgias {
tenantKeysetIDs = append(tenantKeysetIDs, skgia.SSHKeyGroupID.String())
}
// Preparing create instance request
createInstanceRequest := &cwsv1.CreateInstanceRequest{
InstanceId: &cwsv1.UUID{Value: instanceID.String()},
MachineId: &cwsv1.MachineId{Id: machine.ControllerMachineID},
TenantOrg: vpc.Org,
Interfaces: []*cwsv1.InstanceInterfaceConfig{},
CustomIpxe: instance.IpxeScript,
AlwaysBootWithCustomIpxe: &instance.AlwaysBootWithCustomIpxe,
UserData: instance.UserData,
TenantKeysetIds: tenantKeysetIDs,
PhoneHomeEnabled: instance.PhoneHomeEnabled,
}
for _, ifc := range interfaces {
if ifc.SubnetID == nil {
message := "Legacy CreateInstance workflow called without Subnet ID in interface"
logger.Error().Msg(message)
return errors.New(message)
}
subnet, serr := subnetDAO.GetByID(ctx, nil, *ifc.SubnetID, nil)
if serr != nil {
logger.Error().Err(serr).Msgf("failed to retrieve Subnet %v from DB", ifc.SubnetID.String())
return serr
}
if subnet.Status == cdbm.SubnetStatusDeleting {
message := fmt.Sprintf("Subnet: %v is in Deleting state", subnet.ID.String())
logger.Error().Msg(message)
return errors.New(message)
}
if subnet.ControllerNetworkSegmentID == nil {
message := fmt.Sprintf("Subnet: %v does not have Controller Segment ID populated", subnet.ID.String())
logger.Error().Msg(message)
return errors.New(message)
}
iCfg := &cwsv1.InstanceInterfaceConfig{
NetworkSegmentId: &cwsv1.NetworkSegmentId{Value: subnet.ControllerNetworkSegmentID.String()},
}
iCfg.FunctionType = cwsv1.InterfaceFunctionType_VIRTUAL_FUNCTION
if ifc.IsPhysical {
iCfg.FunctionType = cwsv1.InterfaceFunctionType_PHYSICAL_FUNCTION
}
createInstanceRequest.Interfaces = append(createInstanceRequest.Interfaces, iCfg)
}
for _, ibinterface := range ibinterfaces {
// InfiniBandPartition Status
if ibinterface.InfiniBandPartition.Status == cdbm.InfiniBandPartitionStatusDeleting {
message := fmt.Sprintf("InfiniBandPartition: %v is in Deleting state", ibinterface.InfiniBandPartitionID.String())
logger.Error().Msg(message)
return errors.New(message)
}
// InfiniBandPartition Controller IB Partition ID
if ibinterface.InfiniBandPartition.ControllerIBPartitionID == nil {
message := fmt.Sprintf("InfiniBandPartition: %v does not have Controller IB Partition ID populated", ibinterface.InfiniBandPartitionID.String())
logger.Error().Msg(message)
return errors.New(message)
}
ibcfg := &cwsv1.InstanceIBInterfaceConfig{
Device: ibinterface.Device,
Vendor: ibinterface.Vendor,
DeviceInstance: uint32(ibinterface.DeviceInstance),
IbPartitionId: &cwsv1.IBPartitionId{Value: ibinterface.InfiniBandPartition.ControllerIBPartitionID.String()},
}
if ibinterface.IsPhysical {
ibcfg.FunctionType = cwsv1.InterfaceFunctionType_PHYSICAL_FUNCTION
} else if ibinterface.VirtualFunctionID != nil {
ibcfg.FunctionType = cwsv1.InterfaceFunctionType_VIRTUAL_FUNCTION
// Move the conversion of *int to *uint32 in common
vfID := *ibinterface.VirtualFunctionID
uvfID := uint32(vfID)
ibcfg.VirtualFunctionId = &uvfID
}
createInstanceRequest.IbInterfaces = append(createInstanceRequest.IbInterfaces, ibcfg)
}
// Instance metadata info
metadata := &cwsv1.Metadata{
Name: instance.Name,
}
if instance.Description != nil {
metadata.Description = *instance.Description
}
// Prepare labels for site controller
if len(instance.Labels) > 0 {
var labels []*cwsv1.Label
for key, value := range instance.Labels {
curVal := value
localLable := &cwsv1.Label{
Key: key,
Value: &curVal,
}
labels = append(labels, localLable)
}
metadata.Labels = labels
}
createInstanceRequest.Metadata = metadata
we, err := tc.ExecuteWorkflow(ctx, workflowOptions, "CreateInstance",
// Workflow arguments
// Transaction ID
transactionID,
// Create Instance Request
createInstanceRequest,
)
status := cdbm.InstanceStatusProvisioning
statusMessage := "Provisioning request was sent to the Site"
if err != nil {
status = cdbm.InstanceStatusError
statusMessage = "Failed to initiate Instance provisioning on Site"
}
_ = mi.updateInstanceStatusInDB(ctx, nil, instanceID, &status, &statusMessage, nil)
if err != nil {
logger.Error().Err(err).Msg("failed to execute CreateInstance workflow in Site Agent")
return err
}
logger.Info().Str("Workflow ID", we.GetID()).Msg("triggered Site Agent workflow to create Instance")
logger.Info().Msg("completed activity")
return nil
}
// OnCreateInstanceError is a Temporal activity that is invoked when
// the activity CreateInstanceViaSiteAgent has errored
// it sets the instance status to error, and releases the machine associated with it
func (mi ManageInstance) OnCreateInstanceError(ctx context.Context, instanceID uuid.UUID, errMessage *string) error {
logger := log.With().Str("Activity", "CreateInstanceError").Str("Instance ID", instanceID.String()).Logger()
logger.Info().Msg("starting activity")
instanceDAO := cdbm.NewInstanceDAO(mi.dbSession)
instance, err := instanceDAO.GetByID(ctx, nil, instanceID, []string{cdbm.SiteRelationName})
if err != nil {
logger.Error().Err(err).Msg("failed to retrieve Instance from DB by ID")
return err
}
logger.Info().Msg("retrieved Instance from DB")
// Start a db tx
tx, serr := cdb.BeginTx(ctx, mi.dbSession, &sql.TxOptions{})
if serr != nil {
logger.Error().Err(serr).Msg("failed to start transaction")
return serr
}
// update instance status to error
status := cdb.GetStrPtr(cdbm.InstanceStatusError)
var statusMessage *string
if errMessage != nil {
statusMessage = errMessage
} else {
statusMessage = cdb.GetStrPtr("Failed to create Instance via Site Agent")
}
err = mi.updateInstanceStatusInDB(ctx, tx, instance.ID, status, statusMessage, nil)
if err != nil {
terr := tx.Rollback()
if terr != nil {
logger.Error().Err(terr).Msg("failed to rollback transaction")
}
return err
}
// clear the machine id in instance
iDAO := cdbm.NewInstanceDAO(mi.dbSession)
_, err = iDAO.Clear(ctx, tx, cdbm.InstanceClearInput{
InstanceID: instance.ID,
MachineID: true,
})
if err != nil {
logger.Error().Err(err).Msg("failed to clear machineID field in instance in DB")
terr := tx.Rollback()
if terr != nil {
logger.Error().Err(terr).Msg("failed to rollback transaction")
}
return err
}
// clear isAssigned on the machine
if instance.MachineID != nil {
err = mi.clearMachineIsAssigned(ctx, tx, logger, *instance.MachineID)
if err != nil {
logger.Error().Err(err).Msg("failed to clear isAssigned field in machine in DB")
terr := tx.Rollback()
if terr != nil {
logger.Error().Err(terr).Msg("failed to rollback transaction")
}
return err
}
}
// Commit transaction
err = tx.Commit()
if err != nil {
logger.Error().Err(err).Msg("error committing transaction to DB")
return err
}
logger.Info().Msg("successfully completed activity")
return nil
}
// DeleteInstanceViaSiteAgent is a Temporal activity that delete an Instance in Site Controller via Site agent
func (mi ManageInstance) DeleteInstanceViaSiteAgent(ctx context.Context, instanceID uuid.UUID) error {
logger := log.With().Str("Activity", "DeleteInstanceViaSiteAgent").Str("Instance ID", instanceID.String()).Logger()
logger.Info().Msg("starting activity")
instanceDAO := cdbm.NewInstanceDAO(mi.dbSession)
instance, err := instanceDAO.GetByID(ctx, nil, instanceID, nil)
if err != nil {
logger.Error().Err(err).Msg("failed to retrieve Instance from DB by ID")
return err
}
logger.Info().Msg("retrieved Instance from DB")
// NOTE: This section to be removed once all Site/Site Agents have been updated with Instance ID convergence
if instance.ControllerInstanceID == nil {
logger.Warn().Msg("cannot initiate deletion via Site Agent as Instance does not have controller ID set")
// Return an error to schedule retry, once Instance create call update or inventory is received, controller ID will be populated
return fmt.Errorf("Instance does not have controller ID set")
}
tc, err := mi.siteClientPool.GetClientByID(instance.SiteID)
if err != nil {
logger.Error().Err(err).Msg("failed to retrieve Temporal client for Site")
return err
}
workflowOptions := client.StartWorkflowOptions{
ID: "site-instance-delete-" + instanceID.String(),
TaskQueue: queue.SiteTaskQueue,
}
transactionID := &cwsv1.TransactionID{
ResourceId: instanceID.String(),
Timestamp: timestamppb.Now(),
}
deleteInstanceRequest := &cwsv1.DeleteInstanceRequest{
InstanceId: &cwsv1.UUID{Value: instance.ControllerInstanceID.String()},
}
we, err := tc.ExecuteWorkflow(ctx, workflowOptions, "DeleteInstance",
// Workflow arguments
// Transaction ID
transactionID,
// request
deleteInstanceRequest,
)
if err != nil {
logger.Error().Err(err).Msg("failed to initiate DeleteInstance workflow in Site Agent")
return err
}
status := cdbm.InstanceStatusTerminating
statusMessage := "Deletion request was sent to the Site"
_ = mi.updateInstanceStatusInDB(ctx, nil, instanceID, &status, &statusMessage, nil)
logger.Info().Str("Workflow ID", we.GetID()).Msg("triggered Site Agent workflow to delete Instance")
logger.Info().Msg("completed activity")
return nil
}
// RebootInstanceViaSiteAgent is a Temporal activity that reboot a machine which is associated with Instance in Site Controller via Site agent
func (mi ManageInstance) RebootInstanceViaSiteAgent(ctx context.Context, instanceID uuid.UUID, rebootWithCustomIpxe bool, applyUpdatesOnReboot bool) error {
logger := log.With().Str("Activity", "RebootInstanceViaSiteAgent").Str("Instance ID", instanceID.String()).Logger()
logger.Info().Msg("starting activity")
instanceDAO := cdbm.NewInstanceDAO(mi.dbSession)
instance, err := instanceDAO.GetByID(ctx, nil, instanceID, nil)
if err != nil {
logger.Error().Err(err).Msg("failed to retrieve Instance from DB by ID")
return err
}
logger.Info().Msg("retrieved Instance from DB")
if instance.MachineID == nil {
message := "machine id in instance is nil"
logger.Error().Msg(message)
return errors.New(message)
}
mDAO := cdbm.NewMachineDAO(mi.dbSession)
machine, err := mDAO.GetByID(ctx, nil, *instance.MachineID, nil, false)
if err != nil {
logger.Error().Err(err).Msg("failed to retrieve Machine for Instance from DB")
return err
}
tc, err := mi.siteClientPool.GetClientByID(instance.SiteID)
if err != nil {
logger.Error().Err(err).Msg("failed to retrieve Temporal client for Site")
return err
}
workflowOptions := client.StartWorkflowOptions{
ID: "site-instance-reboot-" + instanceID.String(),
TaskQueue: queue.SiteTaskQueue,
}
transactionID := &cwsv1.TransactionID{
ResourceId: instanceID.String(),
Timestamp: timestamppb.Now(),
}
RebootInstanceRequest := &cwsv1.RebootInstanceRequest{
MachineId: &cwsv1.MachineId{Id: machine.ControllerMachineID},
BootWithCustomIpxe: rebootWithCustomIpxe,
ApplyUpdatesOnReboot: applyUpdatesOnReboot,
}
we, err := tc.ExecuteWorkflow(ctx, workflowOptions, "RebootInstance",
// Workflow arguments
// Transaction ID
transactionID,
// request
RebootInstanceRequest,
)
powerstatus := cdbm.InstancePowerStatusRebooting
statusMessage := "Initiated Instance reboot via Site Agent"
if RebootInstanceRequest.ApplyUpdatesOnReboot {
statusMessage = "Initiated Instance reboot with flag enabled to apply pending updates via Site Agent"
}
if err != nil {
logger.Error().Err(err).Msg("failed to execute site agent RebootInstance workflow")
powerstatus = cdbm.InstancePowerStatusError
statusMessage = "Failed to initiate reboot Instance via Site Agent"
}
_ = mi.updateInstanceStatusInDB(ctx, nil, instanceID, nil, &statusMessage, &powerstatus)
if err != nil {
logger.Error().Err(err).Msg("failed to execute RebootInstance workflow in site agent")
return err
}
logger.Info().Str("Workflow ID", we.GetID()).Msg("triggered Site Agent workflow to reboot Instance")
logger.Info().Msg("completed activity")
return nil
}
// UpdateInstanceInDB is a temporal activity which
// updates the Instance in the DB from data pushed by Site Controller
func (mi ManageInstance) UpdateInstanceInDB(ctx context.Context, transactionID *cwsv1.TransactionID, instanceInfo *cwsv1.InstanceInfo) error {
logger := log.With().Str("Activity", "UpdateInstanceInDB").Str("Instance ID", transactionID.ResourceId).Logger()
logger.Info().Msg("starting activity")
instanceDAO := cdbm.NewInstanceDAO(mi.dbSession)
instanceID, err := uuid.Parse(transactionID.ResourceId)
if err != nil {
logger.Error().Err(err).Msg("failed to parse Instance ID from transaction ID")
return err
}
instance, err := instanceDAO.GetByID(ctx, nil, instanceID, nil)
if err != nil {
if err == cdb.ErrDoesNotExist {
logger.Error().Err(err).Msg("could not find Instance from DB by resource ID specified in Site agent transaction ID")
} else {
logger.Error().Err(err).Msg("failed to retrieve Instance from DB by resource ID specified in Site agent transaction ID")
}
return err
}
logger.Info().Msg("retrieved Instance from DB")
// Start a db tx
tx, err := cdb.BeginTx(ctx, mi.dbSession, &sql.TxOptions{})
if err != nil {
logger.Error().Err(err).Msg("failed to start transaction")
return err
}
interfaceDAO := cdbm.NewInterfaceDAO(mi.dbSession)
var status *string
var statusMessage *string
var interfaceStatus *string
if instanceInfo.Status == cwsv1.WorkflowStatus_WORKFLOW_STATUS_SUCCESS {
if instanceInfo.ObjectStatus == cwsv1.ObjectStatus_OBJECT_STATUS_CREATED {
status = cdb.GetStrPtr(cdbm.InstanceStatusProvisioning)
statusMessage = cdb.GetStrPtr("Instance provisioning was successfully initiated on Site")
// Controller Instance ID must be extracted/saved
if instanceInfo.Instance != nil && instanceInfo.Instance.Id != nil {
controllerInstanceID, serr := uuid.Parse(instanceInfo.Instance.Id.Value)
if serr != nil {
logger.Error().Err(serr).Msg("failed to parse Site Controller Instance ID from Instance Info")
terr := tx.Rollback()
if terr != nil {
logger.Error().Err(terr).Msg("failed to rollback transaction")
}
return serr
}
_, serr = instanceDAO.Update(ctx, tx, cdbm.InstanceUpdateInput{InstanceID: instanceID, ControllerInstanceID: cdb.GetUUIDPtr(controllerInstanceID)})
if serr != nil {
logger.Error().Err(serr).Msg("failed to update Controller Instance ID in DB")
terr := tx.Rollback()
if terr != nil {
logger.Error().Err(terr).Msg("failed to rollback transaction")
}
return serr
}
interfaceStatus = cdb.GetStrPtr(cdbm.InterfaceStatusProvisioning)
} else {
errMsg := "controller Instance ID is missing from object creation success response"
logger.Error().Msg(errMsg)
terr := tx.Rollback()
if terr != nil {
logger.Error().Err(terr).Msg("failed to rollback transaction")
}
return errors.New(errMsg)
}
} else if instanceInfo.ObjectStatus == cwsv1.ObjectStatus_OBJECT_STATUS_DELETED {
status = cdb.GetStrPtr(cdbm.InstanceStatusTerminating)
statusMessage = cdb.GetStrPtr("Deletion has been initiated on Site")
interfaceStatus = cdb.GetStrPtr(cdbm.InterfaceStatusDeleting)
}
} else if instanceInfo.Status == cwsv1.WorkflowStatus_WORKFLOW_STATUS_FAILURE {
status = cdb.GetStrPtr(cdbm.InstanceStatusError)
statusMessage = cdb.GetStrPtr(instanceInfo.StatusMsg)
interfaceStatus = cdb.GetStrPtr(cdbm.InterfaceStatusError)
// If the Instance is being deleted then log the error but don't change the status
if instance.Status == cdbm.InstanceStatusTerminating && statusMessage != nil {
status = cdb.GetStrPtr(cdbm.InstanceStatusTerminating)
interfaceStatus = nil
}
}
if status != nil {
err = mi.updateInstanceStatusInDB(ctx, tx, instanceID, status, statusMessage, nil)
if err != nil {
logger.Error().Err(err).Msg("failed to update Instance status detail in DB")
terr := tx.Rollback()
if terr != nil {
logger.Error().Err(terr).Msg("failed to rollback transaction")
}
return err
}
}
if interfaceStatus != nil {
// Update Instance Subnets in DB
iss, _, serr := interfaceDAO.GetAll(ctx, tx, cdbm.InterfaceFilterInput{InstanceIDs: []uuid.UUID{instanceID}}, paginator.PageInput{Limit: cdb.GetIntPtr(cdbp.TotalLimit)}, nil)
if serr != nil {
logger.Error().Err(serr).Msg("failed to retrieve Instance Subnets from DB")
terr := tx.Rollback()
if terr != nil {
logger.Error().Err(terr).Msg("failed to rollback transaction")
}
return serr
}
for _, is := range iss {
_, serr := interfaceDAO.Update(ctx, tx, cdbm.InterfaceUpdateInput{InterfaceID: is.ID, Status: interfaceStatus})
if serr != nil {
logger.Error().Err(serr).Msg("failed to update Instance Subnet in DB")
terr := tx.Rollback()
if terr != nil {
logger.Error().Err(terr).Msg("failed to rollback transaction")
}
return serr
}
}
}
// Commit transaction
err = tx.Commit()
if err != nil {
logger.Error().Err(err).Msg("error committing Instance status update transaction to DB")
return err
}
logger.Info().Msg("successfully completed activity")
return nil
}
// UpdateInstancesInDB is a Temporal activity that takes a collection of Instance data pushed by Site Agent and updates the DB
func (mi ManageInstance) UpdateInstancesInDB(ctx context.Context, siteID uuid.UUID, instanceInventory *cwsv1.InstanceInventory) ([]cwm.InventoryObjectLifecycleEvent, error) {
logger := log.With().Str("Activity", "UpdateInstancesInDB").Str("Site", siteID.String()).Logger()
logger.Info().Msg("starting activity")
// Initialize lifecycle events collector for metrics
instanceLifecycleEvents := []cwm.InventoryObjectLifecycleEvent{}
stDAO := cdbm.NewSiteDAO(mi.dbSession)
site, err := stDAO.GetByID(ctx, nil, siteID, nil, false)
if err != nil {
if err == cdb.ErrDoesNotExist {
logger.Warn().Err(err).Msg("received Machine inventory for unknown or deleted Site")
} else {
logger.Error().Err(err).Msg("failed to retrieve Site from DB")
}
return nil, err
}
if instanceInventory.InventoryStatus == cwsv1.InventoryStatus_INVENTORY_STATUS_FAILED {
logger.Warn().Msg("received failed inventory status from Site Agent, skipping inventory processing")
return nil, nil
}
instanceDAO := cdbm.NewInstanceDAO(mi.dbSession)
// Get all Instances for Site
existingInstances, _, err := instanceDAO.GetAll(ctx, nil, cdbm.InstanceFilterInput{SiteIDs: []uuid.UUID{site.ID}}, cdbp.PageInput{Limit: cdb.GetIntPtr(cdbp.TotalLimit)}, nil)
if err != nil {
logger.Error().Err(err).Msg("failed to get Instances for Site from DB")
return nil, err
}
// Construct a map of Controller Instance ID to Instance
existingInstanceIDMap := make(map[string]*cdbm.Instance)
existingInstanceCtrlIDMap := make(map[string]*cdbm.Instance)
for _, instance := range existingInstances {
curInstance := instance
existingInstanceIDMap[instance.ID.String()] = &curInstance
// Also check by Controller Instance ID
if instance.ControllerInstanceID != nil {
existingInstanceCtrlIDMap[instance.ControllerInstanceID.String()] = &curInstance
}
}
reportedInstanceIDMap := map[uuid.UUID]bool{}
if instanceInventory.InventoryPage != nil {
logger.Info().Msgf("Received Instance inventory page: %d of %d, page size: %d, total count: %d",
instanceInventory.InventoryPage.CurrentPage, instanceInventory.InventoryPage.TotalPages,
instanceInventory.InventoryPage.PageSize, instanceInventory.InventoryPage.TotalItems)
for _, strId := range instanceInventory.InventoryPage.ItemIds {
id, serr := uuid.Parse(strId)
if serr != nil {
logger.Error().Err(serr).Str("ID", strId).Msg("failed to parse Instance ID from inventory page")
continue
}
reportedInstanceIDMap[id] = true
}
}
// Get temporal client for specified Site
tc, err := mi.siteClientPool.GetClientByID(siteID)
if err != nil {
logger.Error().Err(err).Msg("failed to retrieve Temporal client for Site")
return nil, err
}
// Prepare a map of ID -> propagation status
// so we can quickly attach it to the object
// when need to perform the update query.
instancePropagationStatus := map[string]*cdbm.NetworkSecurityGroupPropagationDetails{}
for _, propStatus := range instanceInventory.NetworkSecurityGroupPropagations {
instancePropagationStatus[propStatus.Id] = &cdbm.NetworkSecurityGroupPropagationDetails{NetworkSecurityGroupPropagationObjectStatus: propStatus}
logger.Debug().Str("Controller Instance ID", propStatus.Id).Msg("propagation details cached for Instance")
}
sdDAO := cdbm.NewStatusDetailDAO(mi.dbSession)
ethernetInterfacesToDelete := []*cdbm.Interface{}
infiniBandInterfacesToDelete := []*cdbm.InfiniBandInterface{}
nvlinkInterfacesToDelete := []*cdbm.NVLinkInterface{}
// Iterate through Instances in the inventory and update them in DB
for _, controllerInstance := range instanceInventory.Instances {
slogger := logger.With().Str("Controller Instance ID", controllerInstance.Id.Value).Logger()
instance, ok := existingInstanceCtrlIDMap[controllerInstance.Id.Value]
if !ok {
// Check if the Instance is found by ID (controllerInstance.ID.Value == cloudInstance.ID)
instance, ok = existingInstanceIDMap[controllerInstance.Id.Value]
if ok {
existingInstanceCtrlIDMap[controllerInstance.Id.Value] = instance
}
}
if instance == nil {
logger.Warn().Str("Controller Instance ID", controllerInstance.Id.Value).Msg("Instance does not have a record in DB, possibly created directly on Site")
continue
}
sitePropagationStatus := instancePropagationStatus[controllerInstance.Id.Value]
logger.Debug().Str("Controller Instance ID", controllerInstance.Id.Value).Msgf("cached propagation status for Instance %+v", sitePropagationStatus)
// NOTE: This will be used later to determine if we should delete
// an instance from forge-cloud. If the instance is marked as Terminating
// in cloud-db an it isn't found in this map, it will be deleted.
// We should _always_ track this, even if the inventory might be stale.
reportedInstanceIDMap[instance.ID] = true
// If the instance was updated at all since this inventory was received, we
// should probably consider the inventory details stale for this instance.
// We'll add a 5 second buffer to account for a little clock skew/drift.
// The only thing that might be safe to perform is propagation status clearing,
// but only if we never allow multiple inventory processes to run concurrently.
if time.Since(instance.Updated) < cwutil.InventoryReceiptInterval+(time.Second*5) {
slogger.Warn().Msg("instance updated more recently than inventory received time, skipping processing")
continue
}
// Reset missing flag if necessary.
// If we're here, then it means we saw the instance in the
// inventory returned from the site. If the instance in cloud-db
// had been marked as missing on site up to now, that should be
// reset because inventory is reporting it as on site now.
var isMissingOnSite *bool
if instance.IsMissingOnSite {
isMissingOnSite = cdb.GetBoolPtr(false)
}
// Populate controller Instance ID if necessary
var controllerInstanceID *uuid.UUID
if instance.ControllerInstanceID == nil {
ctrlID, serr := uuid.Parse(controllerInstance.Id.Value)
if serr != nil {
slogger.Error().Err(serr).Msg("failed to parse controller ID, not a valid UUID")
continue
}
controllerInstanceID = &ctrlID
}
// Verify if Update Instance required with Reboot
var isUpdatePending *bool
if controllerInstance.Status != nil {
if controllerInstance.Status.Update != nil {
// If Status.Update is populated and user approval has not been received
if !controllerInstance.Status.Update.UserApprovalReceived {
isUpdatePending = cdb.GetBoolPtr(true)
} else if instance.IsUpdatePending {
// An update was pending, user triggered it, Site Controller has acknowledged
isUpdatePending = cdb.GetBoolPtr(false)
}
} else if instance.IsUpdatePending {
// update was triggered by user, Site Controller has finished execution, hence Status.Update is no longer populated
isUpdatePending = cdb.GetBoolPtr(false)
// Update Instance update status in DB
err = mi.updateInstanceStatusInDB(ctx, nil, instance.ID, cdb.GetStrPtr(instance.Status), cdb.GetStrPtr("Instance updates have successfully been applied"), nil)
if err != nil {
// Log error and continue
slogger.Error().Err(err).Msg("failed to update Instance status detail in DB")
}
}
}
var tpmEkCertificateUpdated *bool
if controllerInstance.TpmEkCertificate != nil &&
(instance.TpmEkCertificate == nil || *instance.TpmEkCertificate != *controllerInstance.TpmEkCertificate) {
tpmEkCertificateUpdated = cdb.GetBoolPtr(true)
}
// NOTE: When adding new properties, make sure to explicitly check for changes between
// the DB instance and the site-reported instance here.
//
// TODO: We probably could use a function here to do the comparison for us.
needsUpdate := isMissingOnSite != nil ||
controllerInstanceID != nil ||
isUpdatePending != nil ||
tpmEkCertificateUpdated != nil ||
!util.NetworkSecurityGroupPropagationDetailsEqual(instance.NetworkSecurityGroupPropagationDetails, sitePropagationStatus)
if needsUpdate {
// If the Instance in the DB has propagation details but the site reported no propagation details
// then we should clear it in the DB. Passing along the nil to the Update call would
// just ignore the field.
if instance.NetworkSecurityGroupPropagationDetails != nil && sitePropagationStatus == nil {
instance, err = instanceDAO.Clear(ctx, nil, cdbm.InstanceClearInput{
InstanceID: instance.ID,
NetworkSecurityGroupPropagationDetails: true,
})
if err != nil {
slogger.Error().Err(err).Msg("failed to clear NetworkSecurityGroupPropagationDetails for Instance in DB")
continue
}
}
// NOTE: InstanceType should NOT be updated.
// The type for an instance can't change because it inherits the type
// from its parent machine when an instance is allocated.
_, serr := instanceDAO.Update(ctx, nil, cdbm.InstanceUpdateInput{
InstanceID: instance.ID,
NetworkSecurityGroupID: controllerInstance.Config.NetworkSecurityGroupId,
NetworkSecurityGroupPropagationDetails: sitePropagationStatus,
ControllerInstanceID: controllerInstanceID,
IsUpdatePending: isUpdatePending,
IsMissingOnSite: isMissingOnSite,
TpmEkCertificate: controllerInstance.TpmEkCertificate,
})
if serr != nil {
slogger.Error().Err(serr).Msg("failed to update missing on Site flag/controller Instance ID in DB")
continue
}
}
var updatedInstanceStatus *string
if controllerInstance.Status != nil && controllerInstance.Status.Tenant != nil {
status, statusMessage := getForgeInstanceStatus(controllerInstance.Status.Tenant.State)
var powerStatus *string
// Get the status from the controller instance
updatedInstanceStatus = &status
// Even if the Instance is in a Terminating state according to the cloud DB,
// we should process the inventory returned from the site.
// Check if most recent status detail is the same as the current status, otherwise create a new one
updateStatusInDB := false
if instance.Status != status {
// Status is different, create a new status detail
updateStatusInDB = true
} else {
// Check if the latest status detail message is different from the current status message
// Leave orderBy nil since the result is sorted by create timestamp by default
latestsd, _, serr := sdDAO.GetAllByEntityID(ctx, nil, instance.ID.String(), nil, cdb.GetIntPtr(1), nil)
if serr != nil {
slogger.Error().Err(serr).Msg("failed to retrieve latest Status Detail for Instance")
} else if len(latestsd) == 0 || (latestsd[0].Message != nil && *latestsd[0].Message != statusMessage) {
updateStatusInDB = true
}
}
if updateStatusInDB {
serr := mi.updateInstanceStatusInDB(ctx, nil, instance.ID, &status, &statusMessage, nil)
if serr != nil {
slogger.Error().Err(serr).Msg("failed to update status and/or create Status Detail in DB")
} else {
// When instance becomes Ready, record a creation lifecycle event; actual duration is computed from StatusDetails
if status == cdbm.InstanceStatusReady {
slogger.Info().Str("To Status", status).Msg("recording instance create lifecycle event")
instanceLifecycleEvents = append(instanceLifecycleEvents, cwm.InventoryObjectLifecycleEvent{ObjectID: instance.ID, Created: cdb.GetTimePtr(time.Now())})
}
}
}
// Update power status if appropriate
if status == cdbm.InstanceStatusReady && (instance.PowerStatus == nil || *instance.PowerStatus != cdbm.InstancePowerStatusBootCompleted) {
powerStatus = cdb.GetStrPtr(cdbm.InstancePowerStatusBootCompleted)
// Update Instance status in DB
err = mi.updateInstanceStatusInDB(ctx, nil, instance.ID, nil, &statusMessage, powerStatus)
if err != nil {
// Log error and continue
slogger.Error().Err(err).Msg("failed to update Instance power status and add Status Detail in DB")
}
}
}
// Process/update Ethernet Interfaces in DB
// Process Interface type of VpcPrefix as well as Subnet
if controllerInstance.Config.Network != nil && controllerInstance.Status.Network != nil {
interfaceDAO := cdbm.NewInterfaceDAO(mi.dbSession)
interfaces, _, serr := interfaceDAO.GetAll(ctx, nil, cdbm.InterfaceFilterInput{InstanceIDs: []uuid.UUID{instance.ID}}, cdbp.PageInput{Limit: cdb.GetIntPtr(cdbp.TotalLimit)}, []string{cdbm.SubnetRelationName, cdbm.VpcPrefixRelationName})
if serr != nil {
slogger.Error().Err(serr).Msg("failed to get Interfaces for Instance from DB")
continue
}
// Build either Subnet or VpcPrefix Map
interfaceMap := map[string]*cdbm.Interface{}
for _, ifc := range interfaces {
curIfc := ifc
// If the Interface is in Deleting state, add it into list of interfaces to be deleted
if ifc.Status == cdbm.InterfaceStatusDeleting {
if updatedInstanceStatus != nil && *updatedInstanceStatus == cdbm.InstanceStatusReady {
ethernetInterfacesToDelete = append(ethernetInterfacesToDelete, &curIfc)
continue
}
} else {
// Build multi DPU interface map where same VPC prefix can have multiple interfaces
if ifc.VpcPrefixID != nil && ifc.Device != nil {
// Multi DPU interface
deviceInstanceId := fmt.Sprintf("%s-%d", *ifc.Device, 0)
if ifc.DeviceInstance != nil {
deviceInstanceId = fmt.Sprintf("%s-%d", *ifc.Device, *ifc.DeviceInstance)
}
if ifc.IsPhysical {
deviceInstanceId = fmt.Sprintf("%s-physical", deviceInstanceId)
} else {
deviceInstanceId = fmt.Sprintf("%s-virtual-%d", deviceInstanceId, *ifc.VirtualFunctionID)
}
interfaceMap[deviceInstanceId] = &curIfc
} else if ifc.VpcPrefixID != nil {
// FNN interface
interfaceMap[ifc.VpcPrefixID.String()] = &curIfc
}
if ifc.SubnetID != nil && ifc.Status != cdbm.InterfaceStatusDeleting {
if ifc.Subnet.ControllerNetworkSegmentID == nil {
_, serr := interfaceDAO.Update(ctx, nil, cdbm.InterfaceUpdateInput{InterfaceID: ifc.ID, Status: cdb.GetStrPtr(cdbm.InterfaceStatusError)})
if serr != nil {
slogger.Error().Err(serr).Str("Interface ID", ifc.ID.String()).Msg("failed to update Interface in DB")
}
} else {
interfaceMap[ifc.Subnet.ControllerNetworkSegmentID.String()] = &curIfc
}
}
}
}
for idx, interfaceConfig := range controllerInstance.Config.Network.Interfaces {