-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstance.go
More file actions
1354 lines (1242 loc) · 54.6 KB
/
instance.go
File metadata and controls
1354 lines (1242 loc) · 54.6 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
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
package hypeman
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"time"
"github.com/kernel/hypeman-go/internal/apijson"
"github.com/kernel/hypeman-go/internal/apiquery"
"github.com/kernel/hypeman-go/internal/requestconfig"
"github.com/kernel/hypeman-go/option"
"github.com/kernel/hypeman-go/packages/param"
"github.com/kernel/hypeman-go/packages/respjson"
"github.com/kernel/hypeman-go/packages/ssestream"
"github.com/kernel/hypeman-go/shared"
)
// InstanceService contains methods and other services that help with interacting
// with the hypeman API.
//
// Note, unlike clients, this service does not read variables from the environment
// automatically. You should not instantiate this service directly, and instead use
// the [NewInstanceService] method instead.
type InstanceService struct {
Options []option.RequestOption
AutoStandby InstanceAutoStandbyService
Volumes InstanceVolumeService
Snapshots InstanceSnapshotService
SnapshotSchedule InstanceSnapshotScheduleService
}
// NewInstanceService generates a new service that applies the given options to
// each request. These options are applied after the parent client's options (if
// there is one), and before any request-specific options.
func NewInstanceService(opts ...option.RequestOption) (r InstanceService) {
r = InstanceService{}
r.Options = opts
r.AutoStandby = NewInstanceAutoStandbyService(opts...)
r.Volumes = NewInstanceVolumeService(opts...)
r.Snapshots = NewInstanceSnapshotService(opts...)
r.SnapshotSchedule = NewInstanceSnapshotScheduleService(opts...)
return
}
// Create and start instance
func (r *InstanceService) New(ctx context.Context, body InstanceNewParams, opts ...option.RequestOption) (res *Instance, err error) {
opts = slices.Concat(r.Options, opts)
path := "instances"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
// Update mutable properties of a running instance. Currently supports updating
// only the environment variables referenced by existing credential policies,
// enabling secret/key rotation without instance restart.
func (r *InstanceService) Update(ctx context.Context, id string, body InstanceUpdateParams, opts ...option.RequestOption) (res *Instance, err error) {
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("instances/%s", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPatch, path, body, &res, opts...)
return res, err
}
// List instances
func (r *InstanceService) List(ctx context.Context, query InstanceListParams, opts ...option.RequestOption) (res *[]Instance, err error) {
opts = slices.Concat(r.Options, opts)
path := "instances"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return res, err
}
// Stop and delete instance
func (r *InstanceService) Delete(ctx context.Context, id string, opts ...option.RequestOption) (err error) {
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithHeader("Accept", "*/*")}, opts...)
if id == "" {
err = errors.New("missing required id parameter")
return err
}
path := fmt.Sprintf("instances/%s", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, nil, opts...)
return err
}
// Fork an instance from stopped, standby, or running (with from_running=true)
func (r *InstanceService) Fork(ctx context.Context, id string, body InstanceForkParams, opts ...option.RequestOption) (res *Instance, err error) {
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("instances/%s/fork", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
// Get instance details
func (r *InstanceService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *Instance, err error) {
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("instances/%s", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
return res, err
}
// Streams instance logs as Server-Sent Events. Use the `source` parameter to
// select which log to stream:
//
// - `app` (default): Guest application logs (serial console)
// - `vmm`: Cloud Hypervisor VMM logs
// - `hypeman`: Hypeman operations log
//
// Returns the last N lines (controlled by `tail` parameter), then optionally
// continues streaming new lines if `follow=true`.
func (r *InstanceService) LogsStreaming(ctx context.Context, id string, query InstanceLogsParams, opts ...option.RequestOption) (stream *ssestream.Stream[string]) {
var (
raw *http.Response
err error
)
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithHeader("Accept", "text/event-stream")}, opts...)
if id == "" {
err = errors.New("missing required id parameter")
return ssestream.NewStream[string](nil, err)
}
path := fmt.Sprintf("instances/%s/logs", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &raw, opts...)
return ssestream.NewStream[string](ssestream.NewDecoder(raw), err)
}
// Restore instance from standby
func (r *InstanceService) Restore(ctx context.Context, id string, opts ...option.RequestOption) (res *Instance, err error) {
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("instances/%s/restore", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...)
return res, err
}
// Put instance in standby (pause, snapshot, delete VMM)
func (r *InstanceService) Standby(ctx context.Context, id string, body InstanceStandbyParams, opts ...option.RequestOption) (res *Instance, err error) {
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("instances/%s/standby", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
// Start a stopped instance
func (r *InstanceService) Start(ctx context.Context, id string, body InstanceStartParams, opts ...option.RequestOption) (res *Instance, err error) {
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("instances/%s/start", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
// Returns information about a path in the guest filesystem. Useful for checking if
// a path exists, its type, and permissions before performing file operations.
func (r *InstanceService) Stat(ctx context.Context, id string, query InstanceStatParams, opts ...option.RequestOption) (res *PathInfo, err error) {
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("instances/%s/stat", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return res, err
}
// Returns real-time resource utilization statistics for a running VM instance.
// Metrics are collected from /proc/<pid>/stat and /proc/<pid>/statm for CPU and
// memory, and from TAP interface statistics for network I/O.
func (r *InstanceService) Stats(ctx context.Context, id string, opts ...option.RequestOption) (res *InstanceStats, err error) {
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("instances/%s/stats", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
return res, err
}
// Stop instance (graceful shutdown)
func (r *InstanceService) Stop(ctx context.Context, id string, opts ...option.RequestOption) (res *Instance, err error) {
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("instances/%s/stop", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...)
return res, err
}
// Blocks until the instance reaches the specified target state, the timeout
// expires, or the instance enters a terminal/error state. Useful for avoiding
// client-side polling when waiting for state transitions (e.g. waiting for an
// instance to become Running).
func (r *InstanceService) Wait(ctx context.Context, id string, query InstanceWaitParams, opts ...option.RequestOption) (res *WaitForStateResponse, err error) {
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("instances/%s/wait", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return res, err
}
// Linux-only automatic standby policy based on active inbound TCP connections
// observed from the host conntrack table.
type AutoStandbyPolicy struct {
// Whether automatic standby is enabled for this instance.
Enabled bool `json:"enabled"`
// How long the instance must have zero qualifying inbound TCP connections before
// Hypeman places it into standby.
IdleTimeout string `json:"idle_timeout"`
// Optional destination TCP ports that should not keep the instance awake.
IgnoreDestinationPorts []int64 `json:"ignore_destination_ports"`
// Optional client CIDRs that should not keep the instance awake.
IgnoreSourceCidrs []string `json:"ignore_source_cidrs"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Enabled respjson.Field
IdleTimeout respjson.Field
IgnoreDestinationPorts respjson.Field
IgnoreSourceCidrs respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r AutoStandbyPolicy) RawJSON() string { return r.JSON.raw }
func (r *AutoStandbyPolicy) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// ToParam converts this AutoStandbyPolicy to a AutoStandbyPolicyParam.
//
// Warning: the fields of the param type will not be present. ToParam should only
// be used at the last possible moment before sending a request. Test for this with
// AutoStandbyPolicyParam.Overrides()
func (r AutoStandbyPolicy) ToParam() AutoStandbyPolicyParam {
return param.Override[AutoStandbyPolicyParam](json.RawMessage(r.RawJSON()))
}
// Linux-only automatic standby policy based on active inbound TCP connections
// observed from the host conntrack table.
type AutoStandbyPolicyParam struct {
// Whether automatic standby is enabled for this instance.
Enabled param.Opt[bool] `json:"enabled,omitzero"`
// How long the instance must have zero qualifying inbound TCP connections before
// Hypeman places it into standby.
IdleTimeout param.Opt[string] `json:"idle_timeout,omitzero"`
// Optional destination TCP ports that should not keep the instance awake.
IgnoreDestinationPorts []int64 `json:"ignore_destination_ports,omitzero"`
// Optional client CIDRs that should not keep the instance awake.
IgnoreSourceCidrs []string `json:"ignore_source_cidrs,omitzero"`
paramObj
}
func (r AutoStandbyPolicyParam) MarshalJSON() (data []byte, err error) {
type shadow AutoStandbyPolicyParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *AutoStandbyPolicyParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type AutoStandbyStatus struct {
// Number of currently tracked qualifying inbound TCP connections.
ActiveInboundConnections int64 `json:"active_inbound_connections" api:"required"`
// Whether the instance has any auto-standby policy configured.
Configured bool `json:"configured" api:"required"`
// Whether the instance is currently eligible to enter standby.
Eligible bool `json:"eligible" api:"required"`
// Whether the configured auto-standby policy is enabled.
Enabled bool `json:"enabled" api:"required"`
// Any of "unsupported_platform", "policy_missing", "policy_disabled",
// "instance_not_running", "network_disabled", "missing_ip", "has_vgpu",
// "active_inbound_connections", "idle_timeout_not_elapsed", "observer_error",
// "ready_for_standby".
Reason AutoStandbyStatusReason `json:"reason" api:"required"`
// Any of "unsupported", "disabled", "ineligible", "active", "idle_countdown",
// "ready_for_standby", "standby_requested", "error".
Status AutoStandbyStatusStatus `json:"status" api:"required"`
// Whether the current host platform supports auto-standby diagnostics.
Supported bool `json:"supported" api:"required"`
// Diagnostic identifier for the runtime tracking mode in use.
TrackingMode string `json:"tracking_mode" api:"required"`
// Remaining time before the controller attempts standby, when applicable.
CountdownRemaining string `json:"countdown_remaining" api:"nullable"`
// When the controller most recently observed the instance become idle.
IdleSince time.Time `json:"idle_since" api:"nullable" format:"date-time"`
// Configured idle timeout from the auto-standby policy.
IdleTimeout string `json:"idle_timeout" api:"nullable"`
// Timestamp of the most recent qualifying inbound TCP activity the controller
// observed.
LastInboundActivityAt time.Time `json:"last_inbound_activity_at" api:"nullable" format:"date-time"`
// When the controller expects to attempt standby next, if a countdown is active.
NextStandbyAt time.Time `json:"next_standby_at" api:"nullable" format:"date-time"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ActiveInboundConnections respjson.Field
Configured respjson.Field
Eligible respjson.Field
Enabled respjson.Field
Reason respjson.Field
Status respjson.Field
Supported respjson.Field
TrackingMode respjson.Field
CountdownRemaining respjson.Field
IdleSince respjson.Field
IdleTimeout respjson.Field
LastInboundActivityAt respjson.Field
NextStandbyAt respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r AutoStandbyStatus) RawJSON() string { return r.JSON.raw }
func (r *AutoStandbyStatus) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type AutoStandbyStatusReason string
const (
AutoStandbyStatusReasonUnsupportedPlatform AutoStandbyStatusReason = "unsupported_platform"
AutoStandbyStatusReasonPolicyMissing AutoStandbyStatusReason = "policy_missing"
AutoStandbyStatusReasonPolicyDisabled AutoStandbyStatusReason = "policy_disabled"
AutoStandbyStatusReasonInstanceNotRunning AutoStandbyStatusReason = "instance_not_running"
AutoStandbyStatusReasonNetworkDisabled AutoStandbyStatusReason = "network_disabled"
AutoStandbyStatusReasonMissingIP AutoStandbyStatusReason = "missing_ip"
AutoStandbyStatusReasonHasVgpu AutoStandbyStatusReason = "has_vgpu"
AutoStandbyStatusReasonActiveInboundConnections AutoStandbyStatusReason = "active_inbound_connections"
AutoStandbyStatusReasonIdleTimeoutNotElapsed AutoStandbyStatusReason = "idle_timeout_not_elapsed"
AutoStandbyStatusReasonObserverError AutoStandbyStatusReason = "observer_error"
AutoStandbyStatusReasonReadyForStandby AutoStandbyStatusReason = "ready_for_standby"
)
type AutoStandbyStatusStatus string
const (
AutoStandbyStatusStatusUnsupported AutoStandbyStatusStatus = "unsupported"
AutoStandbyStatusStatusDisabled AutoStandbyStatusStatus = "disabled"
AutoStandbyStatusStatusIneligible AutoStandbyStatusStatus = "ineligible"
AutoStandbyStatusStatusActive AutoStandbyStatusStatus = "active"
AutoStandbyStatusStatusIdleCountdown AutoStandbyStatusStatus = "idle_countdown"
AutoStandbyStatusStatusReadyForStandby AutoStandbyStatusStatus = "ready_for_standby"
AutoStandbyStatusStatusStandbyRequested AutoStandbyStatusStatus = "standby_requested"
AutoStandbyStatusStatusError AutoStandbyStatusStatus = "error"
)
type Instance struct {
// Auto-generated unique identifier (CUID2 format)
ID string `json:"id" api:"required"`
// Creation timestamp (RFC3339)
CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
// OCI image reference
Image string `json:"image" api:"required"`
// Human-readable name
Name string `json:"name" api:"required"`
// Instance state:
//
// - Created: VMM created but not started (Cloud Hypervisor native)
// - Initializing: VM is running while guest init is still in progress
// - Running: Guest program has started and instance is ready
// - Paused: VM is paused (Cloud Hypervisor native)
// - Shutdown: VM shut down but VMM exists (Cloud Hypervisor native)
// - Stopped: No VMM running, no snapshot exists
// - Standby: No VMM running, snapshot exists (can be restored)
// - Unknown: Failed to determine state (see state_error for details)
//
// Any of "Created", "Initializing", "Running", "Paused", "Shutdown", "Stopped",
// "Standby", "Unknown".
State InstanceState `json:"state" api:"required"`
// Linux-only automatic standby policy based on active inbound TCP connections
// observed from the host conntrack table.
AutoStandby AutoStandbyPolicy `json:"auto_standby"`
// Disk I/O rate limit (human-readable, e.g., "100MB/s")
DiskIoBps string `json:"disk_io_bps"`
// Environment variables
Env map[string]string `json:"env"`
// App exit code (null if VM hasn't exited)
ExitCode int64 `json:"exit_code" api:"nullable"`
// Human-readable description of exit (e.g., "command not found", "killed by signal
// 9 (SIGKILL) - OOM")
ExitMessage string `json:"exit_message"`
// GPU information attached to the instance
GPU InstanceGPU `json:"gpu"`
// Whether a snapshot exists for this instance
HasSnapshot bool `json:"has_snapshot"`
// Hotplug memory size (human-readable)
HotplugSize string `json:"hotplug_size"`
// Hypervisor running this instance
//
// Any of "cloud-hypervisor", "firecracker", "qemu", "vz".
Hypervisor InstanceHypervisor `json:"hypervisor"`
// Network configuration of the instance
Network InstanceNetwork `json:"network"`
// Writable overlay disk size (human-readable)
OverlaySize string `json:"overlay_size"`
// Base memory size (human-readable)
Size string `json:"size"`
SnapshotPolicy SnapshotPolicy `json:"snapshot_policy"`
// Start timestamp (RFC3339)
StartedAt time.Time `json:"started_at" api:"nullable" format:"date-time"`
// Error message if state couldn't be determined (only set when state is Unknown)
StateError string `json:"state_error" api:"nullable"`
// Stop timestamp (RFC3339)
StoppedAt time.Time `json:"stopped_at" api:"nullable" format:"date-time"`
// User-defined key-value tags.
Tags map[string]string `json:"tags"`
// Number of virtual CPUs
Vcpus int64 `json:"vcpus"`
// Volumes attached to the instance
Volumes []VolumeMount `json:"volumes"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ID respjson.Field
CreatedAt respjson.Field
Image respjson.Field
Name respjson.Field
State respjson.Field
AutoStandby respjson.Field
DiskIoBps respjson.Field
Env respjson.Field
ExitCode respjson.Field
ExitMessage respjson.Field
GPU respjson.Field
HasSnapshot respjson.Field
HotplugSize respjson.Field
Hypervisor respjson.Field
Network respjson.Field
OverlaySize respjson.Field
Size respjson.Field
SnapshotPolicy respjson.Field
StartedAt respjson.Field
StateError respjson.Field
StoppedAt respjson.Field
Tags respjson.Field
Vcpus respjson.Field
Volumes respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r Instance) RawJSON() string { return r.JSON.raw }
func (r *Instance) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Instance state:
//
// - Created: VMM created but not started (Cloud Hypervisor native)
// - Initializing: VM is running while guest init is still in progress
// - Running: Guest program has started and instance is ready
// - Paused: VM is paused (Cloud Hypervisor native)
// - Shutdown: VM shut down but VMM exists (Cloud Hypervisor native)
// - Stopped: No VMM running, no snapshot exists
// - Standby: No VMM running, snapshot exists (can be restored)
// - Unknown: Failed to determine state (see state_error for details)
type InstanceState string
const (
InstanceStateCreated InstanceState = "Created"
InstanceStateInitializing InstanceState = "Initializing"
InstanceStateRunning InstanceState = "Running"
InstanceStatePaused InstanceState = "Paused"
InstanceStateShutdown InstanceState = "Shutdown"
InstanceStateStopped InstanceState = "Stopped"
InstanceStateStandby InstanceState = "Standby"
InstanceStateUnknown InstanceState = "Unknown"
)
// GPU information attached to the instance
type InstanceGPU struct {
// mdev device UUID
MdevUuid string `json:"mdev_uuid"`
// vGPU profile name
Profile string `json:"profile"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
MdevUuid respjson.Field
Profile respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r InstanceGPU) RawJSON() string { return r.JSON.raw }
func (r *InstanceGPU) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Hypervisor running this instance
type InstanceHypervisor string
const (
InstanceHypervisorCloudHypervisor InstanceHypervisor = "cloud-hypervisor"
InstanceHypervisorFirecracker InstanceHypervisor = "firecracker"
InstanceHypervisorQemu InstanceHypervisor = "qemu"
InstanceHypervisorVz InstanceHypervisor = "vz"
)
// Network configuration of the instance
type InstanceNetwork struct {
// Download bandwidth limit (human-readable, e.g., "1Gbps", "125MB/s")
BandwidthDownload string `json:"bandwidth_download"`
// Upload bandwidth limit (human-readable, e.g., "1Gbps", "125MB/s")
BandwidthUpload string `json:"bandwidth_upload"`
// Whether instance is attached to the default network
Enabled bool `json:"enabled"`
// Assigned IP address (null if no network)
IP string `json:"ip" api:"nullable"`
// Assigned MAC address (null if no network)
Mac string `json:"mac" api:"nullable"`
// Network name (always "default" when enabled)
Name string `json:"name"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
BandwidthDownload respjson.Field
BandwidthUpload respjson.Field
Enabled respjson.Field
IP respjson.Field
Mac respjson.Field
Name respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r InstanceNetwork) RawJSON() string { return r.JSON.raw }
func (r *InstanceNetwork) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Real-time resource utilization statistics for a VM instance
type InstanceStats struct {
// Total memory allocated to the VM (Size + HotplugSize) in bytes
AllocatedMemoryBytes int64 `json:"allocated_memory_bytes" api:"required"`
// Number of vCPUs allocated to the VM
AllocatedVcpus int64 `json:"allocated_vcpus" api:"required"`
// Total CPU time consumed by the VM hypervisor process in seconds
CPUSeconds float64 `json:"cpu_seconds" api:"required"`
// Instance identifier
InstanceID string `json:"instance_id" api:"required"`
// Instance name
InstanceName string `json:"instance_name" api:"required"`
// Resident Set Size - actual physical memory used by the VM in bytes
MemoryRssBytes int64 `json:"memory_rss_bytes" api:"required"`
// Virtual Memory Size - total virtual memory allocated in bytes
MemoryVmsBytes int64 `json:"memory_vms_bytes" api:"required"`
// Total network bytes received by the VM (from TAP interface)
NetworkRxBytes int64 `json:"network_rx_bytes" api:"required"`
// Total network bytes transmitted by the VM (from TAP interface)
NetworkTxBytes int64 `json:"network_tx_bytes" api:"required"`
// Memory utilization ratio (RSS / allocated memory). Only present when
// allocated_memory_bytes > 0.
MemoryUtilizationRatio float64 `json:"memory_utilization_ratio" api:"nullable"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
AllocatedMemoryBytes respjson.Field
AllocatedVcpus respjson.Field
CPUSeconds respjson.Field
InstanceID respjson.Field
InstanceName respjson.Field
MemoryRssBytes respjson.Field
MemoryVmsBytes respjson.Field
NetworkRxBytes respjson.Field
NetworkTxBytes respjson.Field
MemoryUtilizationRatio respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r InstanceStats) RawJSON() string { return r.JSON.raw }
func (r *InstanceStats) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type PathInfo struct {
// Whether the path exists
Exists bool `json:"exists" api:"required"`
// Error message if stat failed (e.g., permission denied). Only set when exists is
// false due to an error rather than the path not existing.
Error string `json:"error" api:"nullable"`
// True if this is a directory
IsDir bool `json:"is_dir"`
// True if this is a regular file
IsFile bool `json:"is_file"`
// True if this is a symbolic link (only set when follow_links=false)
IsSymlink bool `json:"is_symlink"`
// Symlink target path (only set when is_symlink=true)
LinkTarget string `json:"link_target" api:"nullable"`
// File mode (Unix permissions)
Mode int64 `json:"mode"`
// File size in bytes
Size int64 `json:"size"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Exists respjson.Field
Error respjson.Field
IsDir respjson.Field
IsFile respjson.Field
IsSymlink respjson.Field
LinkTarget respjson.Field
Mode respjson.Field
Size respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r PathInfo) RawJSON() string { return r.JSON.raw }
func (r *PathInfo) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// The properties Interval, Retention are required.
type SetSnapshotScheduleRequestParam struct {
// Snapshot interval (Go duration format, minimum 1m).
Interval string `json:"interval" api:"required"`
// At least one of max_count or max_age must be provided.
Retention SnapshotScheduleRetentionParam `json:"retention,omitzero" api:"required"`
// Optional prefix for auto-generated scheduled snapshot names (max 47 chars).
NamePrefix param.Opt[string] `json:"name_prefix,omitzero"`
// User-defined key-value tags.
Metadata map[string]string `json:"metadata,omitzero"`
paramObj
}
func (r SetSnapshotScheduleRequestParam) MarshalJSON() (data []byte, err error) {
type shadow SetSnapshotScheduleRequestParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *SetSnapshotScheduleRequestParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type SnapshotPolicy struct {
Compression shared.SnapshotCompressionConfig `json:"compression"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Compression respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r SnapshotPolicy) RawJSON() string { return r.JSON.raw }
func (r *SnapshotPolicy) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// ToParam converts this SnapshotPolicy to a SnapshotPolicyParam.
//
// Warning: the fields of the param type will not be present. ToParam should only
// be used at the last possible moment before sending a request. Test for this with
// SnapshotPolicyParam.Overrides()
func (r SnapshotPolicy) ToParam() SnapshotPolicyParam {
return param.Override[SnapshotPolicyParam](json.RawMessage(r.RawJSON()))
}
type SnapshotPolicyParam struct {
Compression shared.SnapshotCompressionConfigParam `json:"compression,omitzero"`
paramObj
}
func (r SnapshotPolicyParam) MarshalJSON() (data []byte, err error) {
type shadow SnapshotPolicyParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *SnapshotPolicyParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type SnapshotSchedule struct {
// Schedule creation timestamp.
CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
// Source instance ID.
InstanceID string `json:"instance_id" api:"required"`
// Snapshot interval (Go duration format).
Interval string `json:"interval" api:"required"`
// Next scheduled run time.
NextRunAt time.Time `json:"next_run_at" api:"required" format:"date-time"`
// Automatic cleanup policy for scheduled snapshots.
Retention SnapshotScheduleRetention `json:"retention" api:"required"`
// Schedule update timestamp.
UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
// Last schedule run error, if any.
LastError string `json:"last_error" api:"nullable"`
// Last schedule execution time.
LastRunAt time.Time `json:"last_run_at" api:"nullable" format:"date-time"`
// Snapshot ID produced by the last successful run.
LastSnapshotID string `json:"last_snapshot_id" api:"nullable"`
// User-defined key-value tags.
Metadata map[string]string `json:"metadata"`
// Optional prefix used for generated scheduled snapshot names.
NamePrefix string `json:"name_prefix" api:"nullable"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
CreatedAt respjson.Field
InstanceID respjson.Field
Interval respjson.Field
NextRunAt respjson.Field
Retention respjson.Field
UpdatedAt respjson.Field
LastError respjson.Field
LastRunAt respjson.Field
LastSnapshotID respjson.Field
Metadata respjson.Field
NamePrefix respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r SnapshotSchedule) RawJSON() string { return r.JSON.raw }
func (r *SnapshotSchedule) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Automatic cleanup policy for scheduled snapshots.
type SnapshotScheduleRetention struct {
// Delete scheduled snapshots older than this duration (Go duration format).
MaxAge string `json:"max_age"`
// Keep at most this many scheduled snapshots for the instance (0 disables
// count-based cleanup).
MaxCount int64 `json:"max_count"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
MaxAge respjson.Field
MaxCount respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r SnapshotScheduleRetention) RawJSON() string { return r.JSON.raw }
func (r *SnapshotScheduleRetention) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// ToParam converts this SnapshotScheduleRetention to a
// SnapshotScheduleRetentionParam.
//
// Warning: the fields of the param type will not be present. ToParam should only
// be used at the last possible moment before sending a request. Test for this with
// SnapshotScheduleRetentionParam.Overrides()
func (r SnapshotScheduleRetention) ToParam() SnapshotScheduleRetentionParam {
return param.Override[SnapshotScheduleRetentionParam](json.RawMessage(r.RawJSON()))
}
// Automatic cleanup policy for scheduled snapshots.
type SnapshotScheduleRetentionParam struct {
// Delete scheduled snapshots older than this duration (Go duration format).
MaxAge param.Opt[string] `json:"max_age,omitzero"`
// Keep at most this many scheduled snapshots for the instance (0 disables
// count-based cleanup).
MaxCount param.Opt[int64] `json:"max_count,omitzero"`
paramObj
}
func (r SnapshotScheduleRetentionParam) MarshalJSON() (data []byte, err error) {
type shadow SnapshotScheduleRetentionParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *SnapshotScheduleRetentionParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type VolumeMount struct {
// Path where volume is mounted in the guest
MountPath string `json:"mount_path" api:"required"`
// Volume identifier
VolumeID string `json:"volume_id" api:"required"`
// Create per-instance overlay for writes (requires readonly=true)
Overlay bool `json:"overlay"`
// Max overlay size as human-readable string (e.g., "1GB"). Required if
// overlay=true.
OverlaySize string `json:"overlay_size"`
// Whether volume is mounted read-only
Readonly bool `json:"readonly"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
MountPath respjson.Field
VolumeID respjson.Field
Overlay respjson.Field
OverlaySize respjson.Field
Readonly respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r VolumeMount) RawJSON() string { return r.JSON.raw }
func (r *VolumeMount) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// ToParam converts this VolumeMount to a VolumeMountParam.
//
// Warning: the fields of the param type will not be present. ToParam should only
// be used at the last possible moment before sending a request. Test for this with
// VolumeMountParam.Overrides()
func (r VolumeMount) ToParam() VolumeMountParam {
return param.Override[VolumeMountParam](json.RawMessage(r.RawJSON()))
}
// The properties MountPath, VolumeID are required.
type VolumeMountParam struct {
// Path where volume is mounted in the guest
MountPath string `json:"mount_path" api:"required"`
// Volume identifier
VolumeID string `json:"volume_id" api:"required"`
// Create per-instance overlay for writes (requires readonly=true)
Overlay param.Opt[bool] `json:"overlay,omitzero"`
// Max overlay size as human-readable string (e.g., "1GB"). Required if
// overlay=true.
OverlaySize param.Opt[string] `json:"overlay_size,omitzero"`
// Whether volume is mounted read-only
Readonly param.Opt[bool] `json:"readonly,omitzero"`
paramObj
}
func (r VolumeMountParam) MarshalJSON() (data []byte, err error) {
type shadow VolumeMountParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *VolumeMountParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type WaitForStateResponse struct {
// Current instance state when the wait completed
//
// Any of "Created", "Initializing", "Running", "Paused", "Shutdown", "Stopped",
// "Standby", "Unknown".
State WaitForStateResponseState `json:"state" api:"required"`
// Whether the timeout expired before the target state was reached
TimedOut bool `json:"timed_out" api:"required"`
// Error message when derived state is Unknown
StateError string `json:"state_error" api:"nullable"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
State respjson.Field
TimedOut respjson.Field
StateError respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r WaitForStateResponse) RawJSON() string { return r.JSON.raw }
func (r *WaitForStateResponse) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Current instance state when the wait completed
type WaitForStateResponseState string
const (
WaitForStateResponseStateCreated WaitForStateResponseState = "Created"
WaitForStateResponseStateInitializing WaitForStateResponseState = "Initializing"
WaitForStateResponseStateRunning WaitForStateResponseState = "Running"
WaitForStateResponseStatePaused WaitForStateResponseState = "Paused"
WaitForStateResponseStateShutdown WaitForStateResponseState = "Shutdown"
WaitForStateResponseStateStopped WaitForStateResponseState = "Stopped"
WaitForStateResponseStateStandby WaitForStateResponseState = "Standby"
WaitForStateResponseStateUnknown WaitForStateResponseState = "Unknown"
)
type InstanceNewParams struct {
// OCI image reference
Image string `json:"image" api:"required"`
// Human-readable name (lowercase letters, digits, and dashes only; cannot start or
// end with a dash)
Name string `json:"name" api:"required"`
// Disk I/O rate limit (e.g., "100MB/s", "500MB/s"). Defaults to proportional share
// based on CPU allocation if configured.
DiskIoBps param.Opt[string] `json:"disk_io_bps,omitzero"`
// Additional memory for hotplug (human-readable format like "3GB", "1G"). Omit to
// disable hotplug memory.
HotplugSize param.Opt[string] `json:"hotplug_size,omitzero"`
// Writable overlay disk size (human-readable format like "10GB", "50G")
OverlaySize param.Opt[string] `json:"overlay_size,omitzero"`
// Base memory size (human-readable format like "1GB", "512MB", "2G")
Size param.Opt[string] `json:"size,omitzero"`
// Skip guest-agent installation during boot. When true, the exec and stat APIs
// will not work for this instance. The instance will still run, but remote command
// execution will be unavailable.
SkipGuestAgent param.Opt[bool] `json:"skip_guest_agent,omitzero"`
// Skip kernel headers installation during boot for faster startup. When true, DKMS
// (Dynamic Kernel Module Support) will not work, preventing compilation of
// out-of-tree kernel modules (e.g., NVIDIA vGPU drivers). Recommended for
// workloads that don't need kernel module compilation.
SkipKernelHeaders param.Opt[bool] `json:"skip_kernel_headers,omitzero"`
// Number of virtual CPUs
Vcpus param.Opt[int64] `json:"vcpus,omitzero"`
// Linux-only automatic standby policy based on active inbound TCP connections
// observed from the host conntrack table.
AutoStandby AutoStandbyPolicyParam `json:"auto_standby,omitzero"`
// Override image CMD (like docker run <image> <command>). Omit to use image
// default.
Cmd []string `json:"cmd,omitzero"`
// Host-managed credential brokering policies keyed by guest-visible env var name.
// Those guest env vars receive mock placeholder values, while the real values
// remain host-scoped in the request `env` map and are only materialized on the
// mediated egress path according to each credential's `source` and `inject` rules.
Credentials map[string]InstanceNewParamsCredential `json:"credentials,omitzero"`
// Device IDs or names to attach for GPU/PCI passthrough
Devices []string `json:"devices,omitzero"`
// Override image entrypoint (like docker run --entrypoint). Omit to use image
// default.
Entrypoint []string `json:"entrypoint,omitzero"`
// Environment variables
Env map[string]string `json:"env,omitzero"`
// GPU configuration for the instance
GPU InstanceNewParamsGPU `json:"gpu,omitzero"`
// Hypervisor to use for this instance. Defaults to server configuration.
//
// Any of "cloud-hypervisor", "firecracker", "qemu", "vz".
Hypervisor InstanceNewParamsHypervisor `json:"hypervisor,omitzero"`
// Network configuration for the instance
Network InstanceNewParamsNetwork `json:"network,omitzero"`
// Snapshot compression policy for this instance. Controls compression settings
// applied when creating snapshots or entering standby.
SnapshotPolicy SnapshotPolicyParam `json:"snapshot_policy,omitzero"`
// User-defined key-value tags.
Tags map[string]string `json:"tags,omitzero"`
// Volumes to attach to the instance at creation time
Volumes []VolumeMountParam `json:"volumes,omitzero"`
paramObj
}
func (r InstanceNewParams) MarshalJSON() (data []byte, err error) {
type shadow InstanceNewParams
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *InstanceNewParams) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// The properties Inject, Source are required.
type InstanceNewParamsCredential struct {
Inject []InstanceNewParamsCredentialInject `json:"inject,omitzero" api:"required"`
Source InstanceNewParamsCredentialSource `json:"source,omitzero" api:"required"`
paramObj
}
func (r InstanceNewParamsCredential) MarshalJSON() (data []byte, err error) {
type shadow InstanceNewParamsCredential
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *InstanceNewParamsCredential) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// The property As is required.