-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathinstance.go
More file actions
1743 lines (1508 loc) · 57 KB
/
Copy pathinstance.go
File metadata and controls
1743 lines (1508 loc) · 57 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
// Package services implements core business workflows.
package services
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"math"
"net"
"strconv"
"strings"
"time"
"github.com/google/uuid"
appcontext "github.com/poyrazk/thecloud/internal/core/context"
"github.com/poyrazk/thecloud/internal/core/domain"
"github.com/poyrazk/thecloud/internal/core/ports"
"github.com/poyrazk/thecloud/internal/errors"
"github.com/poyrazk/thecloud/internal/platform"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
)
// InstanceService manages compute instance lifecycle (containers or VMs).
//
// Supports multiple backends (Docker, Libvirt) and networking modes (bridge, VPC).
// Handles instance CRUD, port mapping, volume attachment, and resource monitoring.
//
// All methods are safe for concurrent use and return domain errors.
const (
// NanoCPUsPerVCPU is the number of nanocpus per vCPU (1 vCPU = 1e9 nanocpus).
NanoCPUsPerVCPU = int64(1e9)
// BytesPerMB is the number of bytes per megabyte.
BytesPerMB = int64(1024 * 1024)
// maxStatsSize bounds instance stats JSON decoding to prevent memory exhaustion.
maxStatsSize = 1 * 1024 * 1024 // 1 MB
)
type InstanceService struct {
repo ports.InstanceRepository
vpcRepo ports.VpcRepository
subnetRepo ports.SubnetRepository
volumeRepo ports.VolumeRepository
instanceTypeRepo ports.InstanceTypeRepository
rbacSvc ports.RBACService
compute ports.ComputeBackend
network ports.NetworkBackend
eventSvc ports.EventService
auditSvc ports.AuditService
dnsSvc ports.DNSService
logSvc ports.LogService
taskQueue ports.TaskQueue
tenantSvc ports.TenantService
sshKeySvc ports.SSHKeyService
dockerNetwork string
logger *slog.Logger
}
// InstanceServiceParams holds dependencies for InstanceService creation.
// Uses parameter object pattern for cleaner dependency injection.
type InstanceServiceParams struct {
Repo ports.InstanceRepository
VpcRepo ports.VpcRepository
SubnetRepo ports.SubnetRepository
VolumeRepo ports.VolumeRepository
InstanceTypeRepo ports.InstanceTypeRepository
RBAC ports.RBACService
Compute ports.ComputeBackend
Network ports.NetworkBackend
EventSvc ports.EventService
AuditSvc ports.AuditService
DNSSvc ports.DNSService
LogSvc ports.LogService
TaskQueue ports.TaskQueue // Optional
TenantSvc ports.TenantService
SSHKeySvc ports.SSHKeyService
DockerNetwork string // Optional
Logger *slog.Logger
}
// NewInstanceService creates a new InstanceService with the given dependencies.
func NewInstanceService(params InstanceServiceParams) *InstanceService {
logger := params.Logger
if logger == nil {
logger = slog.Default()
}
return &InstanceService{
repo: params.Repo,
vpcRepo: params.VpcRepo,
subnetRepo: params.SubnetRepo,
volumeRepo: params.VolumeRepo,
instanceTypeRepo: params.InstanceTypeRepo,
rbacSvc: params.RBAC,
compute: params.Compute,
network: params.Network,
eventSvc: params.EventSvc,
auditSvc: params.AuditSvc,
dnsSvc: params.DNSSvc,
logSvc: params.LogSvc,
taskQueue: params.TaskQueue,
tenantSvc: params.TenantSvc,
sshKeySvc: params.SSHKeySvc,
dockerNetwork: params.DockerNetwork,
logger: logger,
}
}
// LaunchInstance provisions a new instance, sets up its network (if VPC/Subnet provided),
// and attaches any requested volumes.
func (s *InstanceService) LaunchInstance(ctx context.Context, params ports.LaunchParams) (*domain.Instance, error) {
ctx, span := otel.Tracer("instance-service").Start(ctx, "LaunchInstance")
defer span.End()
userID := appcontext.UserIDFromContext(ctx)
tenantID := appcontext.TenantIDFromContext(ctx)
if err := s.rbacSvc.Authorize(ctx, userID, tenantID, domain.PermissionInstanceLaunch, "*"); err != nil {
return nil, err
}
span.SetAttributes(
attribute.String("instance.name", params.Name),
attribute.String("instance.image", params.Image),
)
// 1. Validate ports if provided
_, err := s.parseAndValidatePorts(params.Ports)
if err != nil {
return nil, err
}
// 2. Resolve Instance Type
instanceType := params.InstanceType
if instanceType == "" {
instanceType = "basic-2"
}
it, err := s.instanceTypeRepo.GetByID(ctx, instanceType)
if err != nil {
return nil, errors.New(errors.InvalidInput, fmt.Sprintf("invalid instance type: %s", instanceType))
}
// 3. Quota Check & Reservation
// Resolve SSH Key if provided
var userData string
if params.SSHKeyID != nil {
key, err := s.sshKeySvc.GetKey(ctx, *params.SSHKeyID)
if err != nil {
return nil, err
}
// Use a shell script for maximum compatibility with CirrOS and Ubuntu
userData = fmt.Sprintf("#!/bin/sh\n"+
"for user in cirros ubuntu root; do\n"+
" home=\"/home/$user\"\n"+
" if [ \"$user\" = \"root\" ]; then home=\"/root\"; fi\n"+
" if [ -d \"$home\" ]; then\n"+
" mkdir -p \"$home/.ssh\"\n"+
" echo '%s' >> \"$home/.ssh/authorized_keys\"\n"+
" chown -R \"$user:$user\" \"$home/.ssh\" 2>/dev/null || true\n"+
" chmod 700 \"$home/.ssh\"\n"+
" chmod 600 \"$home/.ssh/authorized_keys\"\n"+
" fi\n"+
"done\n", key.PublicKey)
}
// Check instances quota
if err := s.tenantSvc.CheckQuota(ctx, tenantID, "instances", 1); err != nil {
return nil, err
}
// Check & Reserve vCPU/Memory quota
// Note: We use atomic increment/decrement to manage usage state
if err := s.tenantSvc.CheckQuota(ctx, tenantID, "vcpus", it.VCPUs); err != nil {
return nil, err
}
if err := s.tenantSvc.CheckQuota(ctx, tenantID, "memory", it.MemoryMB/1024); err != nil {
return nil, err
}
// Reserve resources
if err := s.tenantSvc.IncrementUsage(ctx, tenantID, "vcpus", it.VCPUs); err != nil {
return nil, err
}
if err := s.tenantSvc.IncrementUsage(ctx, tenantID, "memory", it.MemoryMB/1024); err != nil {
// Rollback vCPUs if memory fails
_ = s.tenantSvc.DecrementUsage(ctx, tenantID, "vcpus", it.VCPUs)
return nil, err
}
// 4. Create domain entity
inst := &domain.Instance{
ID: uuid.New(),
UserID: userID,
TenantID: tenantID,
Name: params.Name,
Image: params.Image,
Status: domain.StatusStarting,
Ports: params.Ports,
VpcID: params.VpcID,
SubnetID: params.SubnetID,
InstanceType: instanceType,
Version: 1,
VolumeBinds: params.VolumeBinds,
Env: params.Env,
Cmd: params.Cmd,
CPULimit: params.CPULimit,
MemoryLimit: params.MemoryLimit,
DiskLimit: params.DiskLimit,
Metadata: params.Metadata,
Labels: params.Labels,
SSHKeyID: params.SSHKeyID,
CreatedAt: time.Now().UTC(),
UpdatedAt: time.Now(),
}
if err := s.repo.Create(ctx, inst); err != nil {
// Rollback quota reservation
_ = s.tenantSvc.DecrementUsage(ctx, tenantID, "vcpus", it.VCPUs)
_ = s.tenantSvc.DecrementUsage(ctx, tenantID, "memory", it.MemoryMB/1024)
return nil, err
}
// 4. Enqueue provision task
job := domain.ProvisionJob{
InstanceID: inst.ID,
UserID: inst.UserID,
TenantID: inst.TenantID,
Volumes: params.Volumes,
VolumeBinds: params.VolumeBinds,
Env: params.Env,
Cmd: params.Cmd,
CPULimit: params.CPULimit,
MemoryLimit: params.MemoryLimit,
DiskLimit: params.DiskLimit,
Metadata: params.Metadata,
Labels: params.Labels,
UserData: userData,
}
s.logger.Info("enqueueing provision job", "instance_id", inst.ID, "queue", "provision_queue", "tenant_id", inst.TenantID)
if err := s.taskQueue.Enqueue(ctx, "provision_queue", job); err != nil {
s.logger.Error("failed to enqueue provision job", "instance_id", inst.ID, "error", err)
// Rollback quota reservation on enqueue failure
_ = s.tenantSvc.DecrementUsage(ctx, tenantID, "vcpus", it.VCPUs)
_ = s.tenantSvc.DecrementUsage(ctx, tenantID, "memory", it.MemoryMB/1024)
// Rollback database record creation
if delErr := s.repo.Delete(ctx, inst.ID); delErr != nil {
s.logger.Error("failed to delete instance record after enqueue failure", "instance_id", inst.ID, "error", delErr)
}
return nil, errors.Wrap(errors.Internal, "failed to enqueue provisioning task", err)
}
return inst, nil
}
// LaunchInstanceWithOptions provisions an instance using structured options.
func (s *InstanceService) LaunchInstanceWithOptions(ctx context.Context, opts ports.CreateInstanceOptions) (*domain.Instance, error) {
ctx, span := otel.Tracer("instance-service").Start(ctx, "LaunchInstanceWithOptions")
defer span.End()
userID := appcontext.UserIDFromContext(ctx)
tenantID := appcontext.TenantIDFromContext(ctx)
if err := s.rbacSvc.Authorize(ctx, userID, tenantID, domain.PermissionInstanceLaunch, "*"); err != nil {
return nil, err
}
inst := &domain.Instance{
ID: uuid.New(),
UserID: userID,
TenantID: tenantID,
Name: opts.Name,
Image: opts.ImageName,
Status: domain.StatusStarting,
Ports: strings.Join(opts.Ports, ","),
VolumeBinds: opts.VolumeBinds,
Env: opts.Env,
Cmd: opts.Cmd,
CPULimit: opts.CPULimit,
MemoryLimit: opts.MemoryLimit,
DiskLimit: opts.DiskLimit,
InstanceType: "custom", // Marking as custom since we are passing raw constraints or defaults
Version: 1,
CreatedAt: time.Now().UTC(),
UpdatedAt: time.Now(),
}
if opts.NetworkID != "" {
vpcID, err := uuid.Parse(opts.NetworkID)
if err != nil {
return nil, errors.New(errors.InvalidInput, "invalid network id format")
}
inst.VpcID = &vpcID
}
if err := s.repo.Create(ctx, inst); err != nil {
return nil, err
}
// 4. Enqueue provision task with full options
job := domain.ProvisionJob{
InstanceID: inst.ID,
UserID: inst.UserID,
TenantID: inst.TenantID,
UserData: opts.UserData,
Ports: opts.Ports,
VolumeBinds: opts.VolumeBinds,
Env: opts.Env,
Cmd: opts.Cmd,
CPULimit: opts.CPULimit,
MemoryLimit: opts.MemoryLimit,
DiskLimit: opts.DiskLimit,
}
if err := s.taskQueue.Enqueue(ctx, "provision_queue", job); err != nil {
s.logger.Error("failed to enqueue provision job", "instance_id", inst.ID, "error", err)
// Rollback database record creation
if delErr := s.repo.Delete(ctx, inst.ID); delErr != nil {
s.logger.Error("failed to delete instance record after enqueue failure", "instance_id", inst.ID, "error", delErr)
}
return nil, errors.Wrap(errors.Internal, "failed to enqueue provisioning task", err)
}
return inst, nil
}
// Provision contains the heavy lifting of instance launch, called by background workers.
func (s *InstanceService) Provision(ctx context.Context, job domain.ProvisionJob) error {
instanceID := job.InstanceID
userData := job.UserData
volumes := job.Volumes
inst, err := s.repo.GetByID(ctx, instanceID)
if err != nil {
return err
}
// 1. Resolve Networking
networkID, err := s.provisionNetwork(ctx, inst)
if err != nil {
s.updateStatus(ctx, inst)
return err
}
// 2. Resolve Volumes
volumeBinds, attachedVolumes, err := s.resolveVolumes(ctx, volumes)
if err != nil {
s.updateStatus(ctx, inst)
return err
}
// 3. Create Instance
it, itErr := s.instanceTypeRepo.GetByID(ctx, inst.InstanceType)
if itErr != nil {
s.updateStatus(ctx, inst)
return errors.Wrap(errors.Internal, "failed to resolve instance type for provisioning", itErr)
}
// Use limits from instance type but override if custom values provided in inst/job
cpuLimit := int64(it.VCPUs)
if inst.CPULimit > 0 {
cpuLimit = inst.CPULimit
}
memLimit := int64(it.MemoryMB) * 1024 * 1024
if inst.MemoryLimit > 0 {
memLimit = inst.MemoryLimit
}
diskLimit := int64(it.DiskGB) * 1024 * 1024 * 1024
if inst.DiskLimit > 0 {
diskLimit = inst.DiskLimit
}
dockerName := s.formatContainerName(inst.ID)
portList, _ := s.parseAndValidatePorts(inst.Ports)
containerID, allocatedPorts, err := s.compute.LaunchInstanceWithOptions(ctx, ports.CreateInstanceOptions{
Name: dockerName,
ImageName: inst.Image,
Ports: portList,
NetworkID: networkID,
VolumeBinds: volumeBinds,
Env: inst.Env,
Cmd: inst.Cmd,
CPULimit: cpuLimit,
MemoryLimit: memLimit,
DiskLimit: diskLimit,
UserData: userData,
})
if err != nil {
platform.InstanceOperationsTotal.WithLabelValues("launch", "failure").Inc()
s.updateStatus(ctx, inst)
return errors.Wrap(errors.Internal, "failed to launch container", err)
}
// Update ports with actually allocated ones if any
if len(allocatedPorts) > 0 {
inst.Ports = strings.Join(allocatedPorts, ",")
}
// 4. Finalize
return s.finalizeProvision(ctx, inst, containerID, attachedVolumes)
}
func (s *InstanceService) provisionNetwork(ctx context.Context, inst *domain.Instance) (string, error) {
if s.compute.Type() == "noop" && inst.VpcID == nil && inst.SubnetID == nil {
inst.PrivateIP = "127.0.0.1"
return "", nil
}
networkID, allocatedIP, ovsPort, err := s.resolveNetworkConfig(ctx, inst.VpcID, inst.SubnetID)
if err != nil {
return "", err
}
inst.PrivateIP = allocatedIP
inst.OvsPort = ovsPort
return networkID, nil
}
func (s *InstanceService) finalizeProvision(ctx context.Context, inst *domain.Instance, containerID string, attachedVolumes []*domain.Volume) error {
if err := s.plumbNetwork(ctx, inst, containerID); err != nil {
s.logger.Warn("failed to plumb network", "error", err)
}
inst.Status = domain.StatusRunning
inst.ContainerID = containerID
// If IP was not allocated during provision (e.g. Docker dynamic), fetch it now
if inst.PrivateIP == "" {
ip, err := s.compute.GetInstanceIP(ctx, containerID)
if err == nil && ip != "" {
inst.PrivateIP = ip
} else {
s.logger.Warn("failed to get instance IP from backend", "instance_id", inst.ID, "error", err)
}
}
// 5. Register DNS (if applicable)
if s.dnsSvc != nil && inst.PrivateIP != "" {
if err := s.dnsSvc.RegisterInstance(ctx, inst, inst.PrivateIP); err != nil {
s.logger.Warn("failed to register instance DNS", "error", err, "instance", inst.Name)
// Don't fail provisioning for DNS failure
}
}
if err := s.repo.Update(ctx, inst); err != nil {
return err
}
s.updateVolumesAfterLaunch(ctx, attachedVolumes, inst.ID)
if err := s.eventSvc.RecordEvent(ctx, "INSTANCE_LAUNCH", inst.ID.String(), "INSTANCE", map[string]interface{}{
"name": inst.Name,
"image": inst.Image,
"ip": inst.PrivateIP,
}); err != nil {
s.logger.Warn("failed to record event", "action", "INSTANCE_LAUNCH", "instance_id", inst.ID, "error", err)
}
if err := s.auditSvc.Log(ctx, inst.UserID, "instance.launch", "instance", inst.ID.String(), map[string]interface{}{
"name": inst.Name,
"image": inst.Image,
"ip": inst.PrivateIP,
}); err != nil {
s.logger.Warn("failed to log audit event", "action", "instance.launch", "instance_id", inst.ID, "error", err)
}
return nil
}
func (s *InstanceService) updateStatus(ctx context.Context, inst *domain.Instance) {
inst.Status = domain.StatusError
_ = s.repo.Update(ctx, inst)
}
func (s *InstanceService) parseAndValidatePorts(ports string) ([]string, error) {
if ports == "" {
return nil, nil
}
portList := strings.Split(ports, ",")
if len(portList) > domain.MaxPortsPerInstance {
return nil, errors.New(errors.TooManyPorts, fmt.Sprintf("max %d ports allowed", domain.MaxPortsPerInstance))
}
for _, p := range portList {
if err := validatePortMapping(p); err != nil {
return nil, err
}
}
return portList, nil
}
func validatePortMapping(p string) error {
idx := strings.Index(p, ":")
if idx == -1 || strings.Contains(p[idx+1:], ":") {
return errors.New(errors.InvalidPortFormat, "port format must be host:container")
}
hostPart := p[:idx]
containerPart := p[idx+1:]
hostPort, err := parsePort(hostPart)
if err != nil {
return errors.New(errors.InvalidPortFormat, fmt.Sprintf("invalid host port: %s", hostPart))
}
containerPort, err := parsePort(containerPart)
if err != nil {
return errors.New(errors.InvalidPortFormat, fmt.Sprintf("invalid container port: %s", containerPart))
}
if hostPort < domain.MinPort || hostPort > domain.MaxPort {
return errors.New(errors.InvalidPortFormat, fmt.Sprintf("host port %d out of range (%d-%d)", hostPort, domain.MinPort, domain.MaxPort))
}
if containerPort < domain.MinPort || containerPort > domain.MaxPort {
return errors.New(errors.InvalidPortFormat, fmt.Sprintf("container port %d out of range (%d-%d)", containerPort, domain.MinPort, domain.MaxPort))
}
return nil
}
func parsePort(s string) (int, error) {
s = strings.TrimSpace(s)
if s == "" {
return 0, fmt.Errorf("empty port")
}
port, err := strconv.Atoi(s)
if err != nil {
return 0, err
}
return port, nil
}
// StartInstance boots up a stopped instance.
func (s *InstanceService) StartInstance(ctx context.Context, idOrName string) error {
userID := appcontext.UserIDFromContext(ctx)
tenantID := appcontext.TenantIDFromContext(ctx)
if err := s.rbacSvc.Authorize(ctx, userID, tenantID, domain.PermissionInstanceUpdate, idOrName); err != nil {
return err
}
// 1. Get from DB
inst, err := s.GetInstance(ctx, idOrName)
if err != nil {
return err
}
if inst.Status == domain.StatusRunning {
return nil // Already running
}
// 2. Call Compute backend
target := inst.ContainerID
if target == "" {
// Try to recover ID from name if missing
target = s.formatContainerName(inst.ID)
}
if err := s.compute.StartInstance(ctx, target); err != nil {
platform.InstanceOperationsTotal.WithLabelValues("start", "failure").Inc()
s.logger.Error("failed to start instance", "instance_id", inst.ID, "container_id", target, "error", err)
return errors.Wrap(errors.Internal, "failed to start instance", err)
}
// 3. Update Metrics & Status
platform.InstancesTotal.WithLabelValues("stopped", s.compute.Type()).Dec()
platform.InstancesTotal.WithLabelValues("running", s.compute.Type()).Inc()
platform.InstanceOperationsTotal.WithLabelValues("start", "success").Inc()
s.logger.Info("instance started", "instance_id", inst.ID)
inst.Status = domain.StatusRunning
if err := s.repo.Update(ctx, inst); err != nil {
return err
}
if err := s.auditSvc.Log(ctx, inst.UserID, "instance.start", "instance", inst.ID.String(), map[string]interface{}{
"name": inst.Name,
}); err != nil {
s.logger.Warn("failed to log audit event", "action", "instance.start", "instance_id", inst.ID, "error", err)
}
return nil
}
// StopInstance halts a running instance's associated compute resource (e.g., container).
func (s *InstanceService) StopInstance(ctx context.Context, idOrName string) error {
userID := appcontext.UserIDFromContext(ctx)
tenantID := appcontext.TenantIDFromContext(ctx)
if err := s.rbacSvc.Authorize(ctx, userID, tenantID, domain.PermissionInstanceUpdate, idOrName); err != nil {
return err
}
// 1. Get from DB (handles both Name and UUID)
inst, err := s.GetInstance(ctx, idOrName)
if err != nil {
return err
}
if inst.Status == domain.StatusStopped {
return nil // Already stopped
}
// 2. Call Docker stop
target := inst.ContainerID
if target == "" {
// Fallback to Reconstruction
target = s.formatContainerName(inst.ID)
}
if err := s.compute.StopInstance(ctx, target); err != nil {
platform.InstanceOperationsTotal.WithLabelValues("stop", "failure").Inc()
s.logger.Error("failed to stop instance", "backend", s.compute.Type(), "id", target, "error", err)
return errors.Wrap(errors.Internal, fmt.Sprintf("failed to stop %s instance", s.compute.Type()), err)
}
platform.InstancesTotal.WithLabelValues("running", s.compute.Type()).Dec()
platform.InstancesTotal.WithLabelValues("stopped", s.compute.Type()).Inc()
platform.InstanceOperationsTotal.WithLabelValues("stop", "success").Inc()
s.logger.Info("instance stopped", "instance_id", inst.ID)
// 3. Update DB
inst.Status = domain.StatusStopped
if err := s.repo.Update(ctx, inst); err != nil {
return err
}
if err := s.auditSvc.Log(ctx, inst.UserID, "instance.stop", "instance", inst.ID.String(), map[string]interface{}{
"name": inst.Name,
}); err != nil {
s.logger.Warn("failed to log audit event", "action", "instance.stop", "instance_id", inst.ID, "error", err)
}
return nil
}
// PauseInstance freezes a running instance (CPU halted, memory/network retained).
func (s *InstanceService) PauseInstance(ctx context.Context, idOrName string) error {
userID := appcontext.UserIDFromContext(ctx)
tenantID := appcontext.TenantIDFromContext(ctx)
if err := s.rbacSvc.Authorize(ctx, userID, tenantID, domain.PermissionInstanceUpdate, idOrName); err != nil {
return err
}
inst, err := s.GetInstance(ctx, idOrName)
if err != nil {
return err
}
if inst.Status != domain.StatusRunning {
return errors.New(errors.Conflict, "instance must be RUNNING to pause, got: "+string(inst.Status))
}
target := inst.ContainerID
if target == "" {
target = s.formatContainerName(inst.ID)
}
if err := s.compute.PauseInstance(ctx, target); err != nil {
platform.InstanceOperationsTotal.WithLabelValues("pause", "failure").Inc()
if errors.Is(err, errors.Conflict) {
s.logger.Warn("pause not possible in current state", "container_id", target, "error", err)
return errors.New(errors.Conflict, err.Error())
}
s.logger.Error("failed to pause container", "container_id", target, "error", err)
return errors.Wrap(errors.Internal, "failed to pause container", err)
}
oldStatus := inst.Status
inst.Status = domain.StatusPaused
if err := s.repo.Update(ctx, inst); err != nil {
// Best-effort rollback: undo the pause since DB update failed
// Call compensating backend first, then restore DB status
if resumeErr := s.compute.ResumeInstance(ctx, target); resumeErr != nil {
s.logger.Warn("failed to undo pause after repo error",
"instance_id", inst.ID, "resume_error", resumeErr)
}
inst.Status = oldStatus
if rollbackErr := s.repo.Update(ctx, inst); rollbackErr != nil {
s.logger.Warn("failed to rollback pause after repo error",
"instance_id", inst.ID, "pause_error", err, "rollback_error", rollbackErr)
}
return err
}
if err := s.auditSvc.Log(ctx, inst.UserID, "instance.pause", "instance", inst.ID.String(), map[string]interface{}{
"name": inst.Name,
}); err != nil {
s.logger.Warn("failed to log audit event", "action", "instance.pause", "instance_id", inst.ID, "error", err)
}
platform.InstanceOperationsTotal.WithLabelValues("pause", "success").Inc()
s.logger.Info("instance paused", "instance_id", inst.ID)
return nil
}
// ResumeInstance resumes a paused instance back to running state.
func (s *InstanceService) ResumeInstance(ctx context.Context, idOrName string) error {
userID := appcontext.UserIDFromContext(ctx)
tenantID := appcontext.TenantIDFromContext(ctx)
if err := s.rbacSvc.Authorize(ctx, userID, tenantID, domain.PermissionInstanceUpdate, idOrName); err != nil {
return err
}
inst, err := s.GetInstance(ctx, idOrName)
if err != nil {
return err
}
if inst.Status != domain.StatusPaused {
return errors.New(errors.Conflict, "instance must be PAUSED to resume, got: "+string(inst.Status))
}
target := inst.ContainerID
if target == "" {
target = s.formatContainerName(inst.ID)
}
if err := s.compute.ResumeInstance(ctx, target); err != nil {
platform.InstanceOperationsTotal.WithLabelValues("resume", "failure").Inc()
oldStatus := inst.Status
if errors.Is(err, errors.Conflict) {
s.logger.Warn("resume not possible in current state",
"container_id", target, "instance_id", inst.ID, "error", err)
return errors.New(errors.Conflict, err.Error())
}
s.logger.Error("failed to resume container, instance left in PAUSED state",
"container_id", target, "instance_id", inst.ID, "error", err)
inst.Status = oldStatus
if repoErr := s.repo.Update(ctx, inst); repoErr != nil {
s.logger.Error("failed to persist instance status after resume failure",
"instance_id", inst.ID, "resume_error", err, "persist_error", repoErr)
}
return errors.Wrap(errors.Internal, "failed to resume container", err)
}
inst.Status = domain.StatusRunning
if err := s.repo.Update(ctx, inst); err != nil {
// Best-effort rollback: undo the resume since DB update failed
// Call compensating backend first, then restore DB status
if pauseErr := s.compute.PauseInstance(ctx, target); pauseErr != nil {
s.logger.Warn("failed to undo resume after repo error",
"instance_id", inst.ID, "pause_error", pauseErr)
}
inst.Status = domain.StatusPaused
if rollbackErr := s.repo.Update(ctx, inst); rollbackErr != nil {
s.logger.Warn("failed to rollback resume after repo error",
"instance_id", inst.ID, "resume_error", err, "rollback_error", rollbackErr)
}
return err
}
if err := s.auditSvc.Log(ctx, inst.UserID, "instance.resume", "instance", inst.ID.String(), map[string]interface{}{
"name": inst.Name,
}); err != nil {
s.logger.Warn("failed to log audit event", "action", "instance.resume", "instance_id", inst.ID, "error", err)
}
platform.InstanceOperationsTotal.WithLabelValues("resume", "success").Inc()
s.logger.Info("instance resumed", "instance_id", inst.ID)
return nil
}
// ListInstances returns all instances owned by the current user.
// tagFilter optionally restricts results to instances matching all given label constraints.
func (s *InstanceService) ListInstances(ctx context.Context, tagFilter []string) ([]*domain.Instance, error) {
userID := appcontext.UserIDFromContext(ctx)
tenantID := appcontext.TenantIDFromContext(ctx)
if err := s.rbacSvc.Authorize(ctx, userID, tenantID, domain.PermissionInstanceRead, "*"); err != nil {
return nil, err
}
return s.repo.List(ctx, tagFilter)
}
// GetInstance retrieves an instance by its UUID or name.
func (s *InstanceService) GetInstance(ctx context.Context, idOrName string) (*domain.Instance, error) {
userID := appcontext.UserIDFromContext(ctx)
tenantID := appcontext.TenantIDFromContext(ctx)
if err := s.rbacSvc.Authorize(ctx, userID, tenantID, domain.PermissionInstanceRead, idOrName); err != nil {
return nil, err
}
// 1. Try to parse as UUID
id, uuidErr := uuid.Parse(idOrName)
if uuidErr == nil {
return s.repo.GetByID(ctx, id)
}
// 2. Fallback to name lookup
return s.repo.GetByName(ctx, idOrName)
}
// GetInstanceLogs retrieves the execution logs from the instance's compute resource.
func (s *InstanceService) GetInstanceLogs(ctx context.Context, idOrName string) (string, error) {
userID := appcontext.UserIDFromContext(ctx)
tenantID := appcontext.TenantIDFromContext(ctx)
if err := s.rbacSvc.Authorize(ctx, userID, tenantID, domain.PermissionInstanceRead, idOrName); err != nil {
return "", err
}
inst, err := s.repo.GetByName(ctx, idOrName) // Use underlying repo to avoid double RBAC if GetInstance is used
if err != nil {
id, uuidErr := uuid.Parse(idOrName)
if uuidErr == nil {
inst, err = s.repo.GetByID(ctx, id)
}
}
if err != nil || inst == nil {
return "", errors.New(errors.NotFound, "instance not found")
}
if inst.ContainerID == "" {
return "", errors.New(errors.InstanceNotRunning, "instance has no active container")
}
stream, err := s.compute.GetInstanceLogs(ctx, inst.ContainerID)
if err != nil {
return "", errors.Wrap(errors.Internal, "failed to get instance logs", err)
}
defer func() { _ = stream.Close() }()
bytes, err := io.ReadAll(stream)
if err != nil {
return "", errors.Wrap(errors.Internal, "failed to read logs", err)
}
return string(bytes), nil
}
// GetConsoleURL returns the VNC console URL for an instance.
func (s *InstanceService) GetConsoleURL(ctx context.Context, idOrName string) (string, error) {
userID := appcontext.UserIDFromContext(ctx)
tenantID := appcontext.TenantIDFromContext(ctx)
if err := s.rbacSvc.Authorize(ctx, userID, tenantID, domain.PermissionInstanceRead, idOrName); err != nil {
return "", err
}
inst, err := s.repo.GetByName(ctx, idOrName)
if err != nil {
id, uuidErr := uuid.Parse(idOrName)
if uuidErr == nil {
inst, err = s.repo.GetByID(ctx, id)
}
}
if err != nil || inst == nil {
return "", errors.New(errors.NotFound, "instance not found")
}
id := inst.ID.String()
if inst.ContainerID != "" {
id = inst.ContainerID
}
url, err := s.compute.GetConsoleURL(ctx, id)
if err != nil {
return "", errors.Wrap(errors.Internal, "failed to get console URL", err)
}
return url, nil
}
func (s *InstanceService) ResizeInstance(ctx context.Context, idOrName, newInstanceType string) (*domain.Instance, error) {
userID := appcontext.UserIDFromContext(ctx)
tenantID := appcontext.TenantIDFromContext(ctx)
if err := s.rbacSvc.Authorize(ctx, userID, tenantID, domain.PermissionInstanceResize, idOrName); err != nil {
return nil, err
}
inst, err := s.resolveInstance(ctx, idOrName)
if err != nil || inst == nil {
return nil, errors.New(errors.NotFound, "instance not found")
}
oldIT, newIT, err := s.resolveInstanceTypes(ctx, inst.InstanceType, newInstanceType)
if err != nil {
return nil, err
}
if oldIT.ID == newIT.ID {
s.logger.Info("instance already at target type, skipping resize", "instance_id", inst.ID, "type", oldIT.ID)
return inst, nil
}
if err := s.validateResize(inst); err != nil {
return nil, err
}
target := inst.ContainerID
if target == "" {
target = s.formatContainerName(inst.ID)
}
if err := s.completeResize(ctx, tenantID, inst, target, oldIT, newIT, newInstanceType); err != nil {
return nil, err
}
s.logger.Info("instance resized", "instance_id", inst.ID, "old_type", oldIT.ID, "new_type", newIT.ID)
return inst, nil
}
func (s *InstanceService) resolveInstance(ctx context.Context, idOrName string) (*domain.Instance, error) {
inst, err := s.repo.GetByName(ctx, idOrName)
if err != nil {
if errors.Is(err, errors.NotFound) {
id, uuidErr := uuid.Parse(idOrName)
if uuidErr == nil {
inst, err = s.repo.GetByID(ctx, id)
}
}
if err != nil {
return nil, err
}
}
return inst, nil
}
func (s *InstanceService) resolveInstanceTypes(ctx context.Context, currentType, newType string) (*domain.InstanceType, *domain.InstanceType, error) {
oldIT, err := s.instanceTypeRepo.GetByID(ctx, currentType)
if err != nil {
return nil, nil, errors.Wrap(errors.InvalidInput, "current instance type not found", err)
}
newIT, err := s.instanceTypeRepo.GetByID(ctx, newType)
if err != nil {
return nil, nil, errors.Wrap(errors.InvalidInput, "invalid instance type: "+newType, err)
}
return oldIT, newIT, nil
}
func (s *InstanceService) validateResize(inst *domain.Instance) error {
if inst.ContainerID == "" {
return errors.New(errors.InvalidInput, "instance has no active container, not yet provisioned")
}
if inst.Status != domain.StatusRunning && inst.Status != domain.StatusStopped {
return errors.New(errors.Conflict, "instance state must be RUNNING or STOPPED to resize, got: "+string(inst.Status))
}
return nil
}
// rollbackQuotaChanges reverses quota modifications made before the compute resize attempt.
// It logs failures but does not return errors, since undo is not guaranteed to be possible.
func (s *InstanceService) rollbackQuotaChanges(ctx context.Context, tenantID uuid.UUID, deltaCPU, deltaMemMB, memoryGB int) {
if deltaCPU > 0 {
if err := s.tenantSvc.DecrementUsage(ctx, tenantID, "vcpus", deltaCPU); err != nil {
s.logger.Error("rollback vcpu decrement failed", "error", err, "tenant_id", tenantID, "delta", deltaCPU)
}
} else if deltaCPU < 0 {
if err := s.tenantSvc.IncrementUsage(ctx, tenantID, "vcpus", -deltaCPU); err != nil {
s.logger.Error("rollback vcpu increment failed", "error", err, "tenant_id", tenantID, "delta", -deltaCPU)
}
}
if deltaMemMB > 0 {
if err := s.tenantSvc.DecrementUsage(ctx, tenantID, "memory", memoryGB); err != nil {
s.logger.Error("rollback memory decrement failed", "error", err, "tenant_id", tenantID)
}
} else if deltaMemMB < 0 {
if err := s.tenantSvc.IncrementUsage(ctx, tenantID, "memory", -memoryGB); err != nil {
s.logger.Error("rollback memory increment failed", "error", err, "tenant_id", tenantID)
}
}
}
func (s *InstanceService) completeResize(ctx context.Context, tenantID uuid.UUID, inst *domain.Instance, target string, oldIT, newIT *domain.InstanceType, newInstanceType string) error {
deltaCPU := newIT.VCPUs - oldIT.VCPUs
deltaMemMB := newIT.MemoryMB - oldIT.MemoryMB
memoryGB := deltaMemMB / 1024
// 1. Quota changes first — fail fast before any VM state change
if deltaCPU > 0 {
if err := s.tenantSvc.CheckQuota(ctx, tenantID, "vcpus", deltaCPU); err != nil {
return err
}
if err := s.tenantSvc.IncrementUsage(ctx, tenantID, "vcpus", deltaCPU); err != nil {
platform.InstanceOperationsTotal.WithLabelValues("resize", "quota_failure").Inc()
return errors.Wrap(errors.Internal, "failed to increment vCPU quota for resize", err)
}
} else if deltaCPU < 0 {
if err := s.tenantSvc.DecrementUsage(ctx, tenantID, "vcpus", -deltaCPU); err != nil {
platform.InstanceOperationsTotal.WithLabelValues("resize", "quota_decrement_failure").Inc()
return errors.Wrap(errors.Internal, "failed to decrement vCPU quota for resize", err)
}
}
if deltaMemMB > 0 {
if err := s.tenantSvc.CheckQuota(ctx, tenantID, "memory", memoryGB); err != nil {
// Rollback vCPU increment since memory quota check failed
if deltaCPU > 0 {
if decErr := s.tenantSvc.DecrementUsage(ctx, tenantID, "vcpus", deltaCPU); decErr != nil {
return errors.Wrap(errors.Internal,
fmt.Sprintf("memory quota check failed (%v), vCPU rollback also failed (%v)", err, decErr), err)
}