Repository navigation
Expand file tree
/
Copy pathstudio.go
More file actions
1385 lines (1301 loc) · 40.9 KB
/
Copy pathstudio.go
File metadata and controls
1385 lines (1301 loc) · 40.9 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 lit
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"time"
sdkapi "github.com/lightning-ai/sdk/go/internal/lightningcloud/openapi/generated/client"
"github.com/lightning-ai/sdk/go/internal/lightningcloud/openapi/generated/client/cloud_space_service"
"github.com/lightning-ai/sdk/go/internal/lightningcloud/openapi/generated/client/projects_service"
"github.com/lightning-ai/sdk/go/internal/lightningcloud/openapi/generated/models"
"github.com/lightning-ai/sdk/go/internal/sdkclient"
)
// Studio represents a Lightning Studio.
type Studio struct {
id string
name string
status string
teamspaceID string
teamspace teamspaceRef
cloud string
machine string
interruptible bool
autoSleep bool
autoSleepTime int
env map[string]string
interruptibleSet bool
}
// RunAndDetachOptions configures detached command execution polling.
type RunAndDetachOptions struct {
// Timeout limits how long RunAndDetach waits for command completion.
Timeout time.Duration
// CheckInterval controls how often RunAndDetach polls command status.
CheckInterval time.Duration
}
type studioOptions struct {
id string
name string
status string
teamspaceID string
teamspaceName string
ownerName string
cloud string
machine string
interruptible bool
interruptibleSet bool
autoSleep bool
autoSleepTime int
env map[string]string
}
type switchMachineOptions struct {
cloud string
interruptible bool
}
type startStudioOptions struct {
machine string
interruptible bool
interruptibleSet bool
maxRuntime int
}
type duplicateStudioOptions struct {
name string
teamspaceID string
teamspaceName string
}
type teamspaceRef struct {
id string
name string
ownerName string
}
type studioFields struct {
ID string
Name string
Status string
TeamspaceID string
Teamspace string
OwnerName string
Cloud string
Machine string
Interruptible bool
AutoSleep bool
AutoSleepTime int
Env map[string]string
interruptibleSet bool
}
// StudioOptions configures studio lookup and creation.
type StudioOptions struct {
// ID resolves an existing studio directly without looking it up by name.
ID string
// Teamspace scopes studio lookup or creation to a specific teamspace.
Teamspace *Teamspace
// Cloud selects a cloud account or provider for the studio.
Cloud string
// Machine selects the compute type used when creating or seeding a studio handle.
Machine Machine
// Interruptible overrides whether the studio runs on interruptible capacity.
Interruptible *bool
// Status seeds the latest known state for ID-based handles.
Status string
// AutoSleep enables or disables studio auto-sleep.
AutoSleep bool
// AutoSleepTime sets the auto-sleep timeout in minutes.
AutoSleepTime int
// Env seeds environment variables on the studio handle.
Env map[string]string
}
// StartStudioOptions configures studio start behavior.
type StartStudioOptions struct {
// Machine overrides the machine type used to start the studio.
Machine Machine
// Interruptible overrides whether the started studio uses interruptible capacity.
Interruptible *bool
// MaxRuntime limits the studio runtime in seconds.
MaxRuntime int
}
// SwitchMachineOptions configures a studio machine switch.
type SwitchMachineOptions struct {
// Cloud selects a cloud account or provider for the new machine.
Cloud string
// Interruptible overrides whether the new machine uses interruptible capacity.
Interruptible *bool
}
// DuplicateStudioOptions configures studio duplication.
type DuplicateStudioOptions struct {
// Name sets the duplicated studio name.
Name string
// Teamspace sets the destination teamspace for the duplicate.
Teamspace *Teamspace
}
// GetStudio returns an existing studio by name or ID.
func GetStudio(name string, opts ...StudioOptions) (*Studio, error) {
resolved := applyStudioOptions(opts...)
if name == "" && resolved.id == "" {
return nil, errors.New("studio requires name or ID")
}
if resolved.id != "" {
return newStudio(studioFields{
ID: resolved.id,
Name: name,
Status: resolved.status,
TeamspaceID: resolved.teamspaceID,
Teamspace: resolved.teamspaceName,
OwnerName: resolved.ownerName,
Cloud: resolved.cloud,
Machine: resolved.machine,
Interruptible: resolved.interruptible,
interruptibleSet: resolved.interruptibleSet,
AutoSleep: resolved.autoSleep,
AutoSleepTime: resolved.autoSleepTime,
Env: cloneMap(resolved.env),
}), nil
}
if resolved.teamspaceID == "" {
return nil, errors.New("studio requires teamspace when ID is not provided")
}
api, err := sdkclient.New()
if err != nil {
return nil, err
}
params := cloud_space_service.NewCloudSpaceServiceGetCloudSpaceByNameParamsWithContext(context.Background()).
WithCloudspaceName(name).
WithProjectName(firstNonEmpty(resolved.teamspaceName, "-")).
WithUserName(firstNonEmpty(resolved.ownerName, "-"))
if resolved.teamspaceID != "" {
params = params.WithProjectID(&resolved.teamspaceID)
}
resp, err := api.CloudSpaceService.CloudSpaceServiceGetCloudSpaceByName(params)
if err != nil {
return nil, err
}
return studioFromResponse(resp.Payload, resolved)
}
// CreateStudio creates a new studio.
func CreateStudio(name string, opts ...StudioOptions) (*Studio, error) {
resolved := applyStudioOptions(opts...)
if name == "" {
return nil, errors.New("studio create requires name")
}
api, err := sdkclient.New()
if err != nil {
return nil, err
}
if resolved.teamspaceID == "" {
return nil, errors.New("studio create requires teamspace")
}
body := &models.CloudSpaceServiceCreateCloudSpaceBody{
ClusterID: resolved.cloud,
ComputeName: resolved.machine,
DisplayName: name,
Name: name,
Spot: resolved.interruptible,
}
resp, err := api.CloudSpaceService.CloudSpaceServiceCreateCloudSpace(
cloud_space_service.NewCloudSpaceServiceCreateCloudSpaceParamsWithContext(context.Background()).
WithProjectID(resolved.teamspaceID).
WithBody(body),
)
if err != nil {
return nil, err
}
if resp.Payload == nil {
return nil, fmt.Errorf("create studio returned empty payload")
}
return studioFromCloudSpace(resp.Payload, resolved), nil
}
// StartStudio starts a studio.
func StartStudio(s *Studio, opts ...StartStudioOptions) error {
if s == nil {
return errors.New("start studio requires studio")
}
return s.Start(opts...)
}
// SwitchStudioMachine switches a studio to another machine type.
func SwitchStudioMachine(s *Studio, machine Machine, opts ...SwitchMachineOptions) error {
if s == nil {
return errors.New("switch studio machine requires studio")
}
return s.SwitchMachine(machine, opts...)
}
func newStudio(fields studioFields) *Studio {
result := &Studio{
id: fields.ID,
name: fields.Name,
status: fields.Status,
teamspaceID: fields.TeamspaceID,
teamspace: teamspaceRef{id: fields.TeamspaceID, name: fields.Teamspace, ownerName: fields.OwnerName},
cloud: fields.Cloud,
machine: fields.Machine,
interruptible: fields.Interruptible,
autoSleep: fields.AutoSleep,
autoSleepTime: fields.AutoSleepTime,
env: cloneMap(fields.Env),
interruptibleSet: fields.interruptibleSet,
}
return result
}
func (s *Studio) teamspaceReference() teamspaceRef {
if s == nil {
return teamspaceRef{}
}
return s.teamspace
}
// ID returns the studio ID.
func (s *Studio) ID() string {
if s == nil {
return ""
}
return s.id
}
// TeamspaceID returns the owning teamspace ID.
func (s *Studio) TeamspaceID() string {
if s == nil {
return ""
}
return s.teamspaceID
}
// Name returns the studio name.
func (s *Studio) Name() string {
if s == nil {
return ""
}
return s.name
}
// Status returns the latest known studio status.
func (s *Studio) Status() string {
if s == nil {
return ""
}
return s.status
}
// Teamspace returns the owning teamspace name.
func (s *Studio) Teamspace() string {
if s == nil {
return ""
}
return s.teamspace.name
}
// OwnerName returns the owning user or organization name.
func (s *Studio) OwnerName() string {
if s == nil {
return ""
}
return s.teamspace.ownerName
}
// Cloud returns the configured cloud account ID.
func (s *Studio) Cloud() string {
if s == nil {
return ""
}
return s.cloud
}
// Machine returns the configured machine.
func (s *Studio) Machine() string {
if s == nil {
return ""
}
return s.machine
}
// Interruptible reports whether the studio uses interruptible capacity.
func (s *Studio) Interruptible() bool {
if s == nil {
return false
}
return s.interruptible
}
// AutoSleep reports whether auto sleep is enabled.
func (s *Studio) AutoSleep() bool {
if s == nil {
return false
}
return s.autoSleep
}
// AutoSleepTime returns the auto sleep timeout in seconds.
func (s *Studio) AutoSleepTime() int {
if s == nil {
return 0
}
return s.autoSleepTime
}
// Env returns a copy of the studio environment.
func (s *Studio) Env() map[string]string {
if s == nil {
return nil
}
return cloneMap(s.env)
}
// String returns a compact human-readable representation.
func (s *Studio) String() string {
if s == nil {
return "Studio(name=, teamspace=)"
}
teamspace := s.teamspaceReference()
return fmt.Sprintf("Studio(name=%s, teamspace=Teamspace(name=%s, owner=%s))", s.Name(), teamspace.name, teamspace.ownerName)
}
// Equal reports whether two studio handles refer to the same public state.
func (s *Studio) Equal(other *Studio) bool {
if s == nil || other == nil {
return s == other
}
return s.Name() == other.Name() && s.teamspaceReference() == other.teamspaceReference()
}
// Start starts the studio.
func (s *Studio) Start(opts ...StartStudioOptions) error {
if s == nil || s.teamspaceID == "" || s.id == "" {
return errors.New("studio start requires teamspace ID and studio ID")
}
resolved := applyStartStudioOptions(opts...)
machine := firstNonEmpty(resolved.machine, s.machine)
if machine == "" {
machine = "CPU"
}
api, err := sdkclient.New()
if err != nil {
return err
}
interruptible := s.interruptible
if override := os.Getenv("LIGHTNING_INTERRUPTIBLE_OVERRIDE"); override != "" {
interruptible = strings.ToLower(override) == "true"
} else if resolved.interruptibleSet {
interruptible = resolved.interruptible
} else if !s.interruptibleSet {
interruptible, err = resolveDefaultStartInterruptible(api, s.teamspaceID)
if err != nil {
return err
}
}
body := &models.CloudSpaceServiceStartCloudSpaceInstanceBody{
ComputeConfig: &models.V1UserRequestedComputeConfig{
ClusterOverride: s.cloud,
Name: machine,
RequestedRunDurationSeconds: maxRuntime(resolved.maxRuntime),
Spot: interruptible,
},
}
_, err = api.CloudSpaceService.CloudSpaceServiceStartCloudSpaceInstance(
cloud_space_service.NewCloudSpaceServiceStartCloudSpaceInstanceParamsWithContext(context.Background()).
WithProjectID(s.teamspaceID).
WithID(s.id).
WithBody(body),
)
if err != nil {
return err
}
s.status = "running"
s.machine = machine
s.interruptible = interruptible
s.interruptibleSet = true
return nil
}
// SwitchMachine changes the studio machine.
func (s *Studio) SwitchMachine(machine Machine, opts ...SwitchMachineOptions) error {
if s == nil || s.teamspaceID == "" || s.id == "" {
return errors.New("studio switch machine requires teamspace ID and studio ID")
}
machineName := string(machine)
if machineName == "" {
return errors.New("studio switch machine requires machine")
}
resolved := applySwitchMachineOptions(opts...)
api, err := sdkclient.New()
if err != nil {
return err
}
body := &models.CloudSpaceServiceUpdateCloudSpaceInstanceConfigBody{
ComputeConfig: &models.V1UserRequestedComputeConfig{
ClusterOverride: resolved.cloud,
Name: machineName,
Spot: resolved.interruptible,
},
}
_, err = api.CloudSpaceService.CloudSpaceServiceUpdateCloudSpaceInstanceConfig(
cloud_space_service.NewCloudSpaceServiceUpdateCloudSpaceInstanceConfigParamsWithContext(context.Background()).
WithProjectID(s.teamspaceID).
WithID(s.id).
WithBody(body),
)
if err != nil {
return err
}
s.machine = machineName
s.interruptible = resolved.interruptible
if resolved.cloud != "" {
s.cloud = resolved.cloud
}
return nil
}
// Stop stops the studio.
func (s *Studio) Stop() error {
if s == nil || s.teamspaceID == "" || s.id == "" {
return errors.New("studio stop requires teamspace ID and studio ID")
}
api, err := sdkclient.New()
if err != nil {
return err
}
_, err = api.CloudSpaceService.CloudSpaceServiceStopCloudSpaceInstance(
cloud_space_service.NewCloudSpaceServiceStopCloudSpaceInstanceParamsWithContext(context.Background()).
WithProjectID(s.teamspaceID).
WithID(s.id),
)
if err != nil {
return err
}
s.status = "stopped"
return nil
}
// Delete deletes the studio.
func (s *Studio) Delete() error {
if s == nil || s.teamspaceID == "" || s.id == "" {
return errors.New("studio delete requires teamspace ID and studio ID")
}
api, err := sdkclient.New()
if err != nil {
return err
}
_, err = api.CloudSpaceService.CloudSpaceServiceDeleteCloudSpace(
cloud_space_service.NewCloudSpaceServiceDeleteCloudSpaceParamsWithContext(context.Background()).
WithProjectID(s.teamspaceID).
WithID(s.id),
)
return err
}
// PublicIP returns the current studio public IP when available.
func (s *Studio) PublicIP() (string, error) {
if s == nil || s.teamspaceID == "" || s.id == "" {
return "", errors.New("studio public IP requires teamspace ID and studio ID")
}
api, err := sdkclient.New()
if err != nil {
return "", err
}
resp, err := api.CloudSpaceService.CloudSpaceServiceGetCloudSpaceInstanceStatus(
cloud_space_service.NewCloudSpaceServiceGetCloudSpaceInstanceStatusParamsWithContext(context.Background()).
WithProjectID(s.teamspaceID).
WithID(s.id),
)
if err != nil {
return "", err
}
if resp.Payload == nil || resp.Payload.InUse == nil {
return "", nil
}
return resp.Payload.InUse.PublicIPAddress, nil
}
// DownloadFile downloads a file from the studio.
func (s *Studio) DownloadFile(remotePath, filePath string) error {
if s == nil || s.teamspaceID == "" || s.id == "" {
return errors.New("studio download file requires teamspace ID and studio ID")
}
if remotePath == "" {
return errors.New("studio download file requires remote path")
}
if filePath == "" {
filePath = remotePath
}
api, err := sdkclient.NewRaw()
if err != nil {
return err
}
query := url.Values{}
if s.cloud != "" {
query.Set("clusterId", s.cloud)
}
return api.Download(context.Background(), studioArtifactBlobPath(s.teamspaceID, s.id, remotePath), query, filePath)
}
// DownloadFolder downloads a folder from the studio.
func (s *Studio) DownloadFolder(remotePath, targetPath string) error {
if s == nil || s.teamspaceID == "" || s.id == "" {
return errors.New("studio download folder requires teamspace ID and studio ID")
}
if targetPath == "" {
targetPath = remotePath
}
api, err := sdkclient.NewRaw()
if err != nil {
return err
}
remotePath = strings.Trim(remotePath, "/")
return downloadArtifactFolder(
api,
remotePath,
targetPath,
studioArtifactTreePath(s.teamspaceID, s.id, remotePath),
func(remoteFilePath string) string { return studioArtifactBlobPath(s.teamspaceID, s.id, remoteFilePath) },
url.Values{"recursive": []string{"true"}},
nil,
)
}
// UploadFile uploads a file to the studio.
func (s *Studio) UploadFile(filePath, remotePath string) error {
if s == nil || s.teamspaceID == "" || s.id == "" {
return errors.New("studio upload file requires teamspace ID and studio ID")
}
if filePath == "" {
return errors.New("studio upload file requires file path")
}
if remotePath == "" {
remotePath = filepath.Base(filePath)
}
api, err := sdkclient.NewRaw()
if err != nil {
return err
}
// Completion makes the file show up in a running Studio.
return api.Upload(context.Background(), studioArtifactScopePath(s.teamspaceID, s.id), strings.TrimLeft(remotePath, "/"), nil, filePath, sdkclient.UploadOptions{})
}
// UploadFolder uploads a folder to the studio.
func (s *Studio) UploadFolder(folderPath, remotePath string) error {
if s == nil || s.teamspaceID == "" || s.id == "" {
return errors.New("studio upload folder requires teamspace ID and studio ID")
}
if folderPath == "" {
return errors.New("studio upload folder requires folder path")
}
info, err := os.Stat(folderPath)
if err != nil {
return err
}
if !info.IsDir() {
return fmt.Errorf("cannot upload file as folder: %s", folderPath)
}
var files []string
if err := filepath.WalkDir(folderPath, func(path string, entry os.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
return nil
}
files = append(files, path)
return nil
}); err != nil {
return err
}
sort.Strings(files)
for _, filePath := range files {
relativePath, err := filepath.Rel(folderPath, filePath)
if err != nil {
return err
}
remoteFilePath := filepath.ToSlash(relativePath)
if remotePath != "" {
remoteFilePath = strings.TrimRight(remotePath, "/") + "/" + remoteFilePath
}
if err := s.UploadFile(filePath, remoteFilePath); err != nil {
return err
}
}
return nil
}
// ListFiles lists the immediate entries of a studio drive folder, or every
// file under it when recursive. An empty remotePath lists the studio's root.
func (s *Studio) ListFiles(remotePath string, recursive bool) ([]FileEntry, error) {
if s == nil || s.teamspaceID == "" || s.id == "" {
return nil, errors.New("studio list files requires teamspace ID and studio ID")
}
api, err := sdkclient.NewRaw()
if err != nil {
return nil, err
}
query := url.Values{}
if s.cloud != "" {
query.Set("clusterId", s.cloud)
}
if recursive {
query.Set("recursive", "true")
}
return listArtifactFolder(api, studioArtifactTreePath(s.teamspaceID, s.id, strings.Trim(remotePath, "/")), query)
}
// DeleteFile removes a single file from the studio drive.
func (s *Studio) DeleteFile(remotePath string) error {
if s == nil || s.teamspaceID == "" || s.id == "" {
return errors.New("studio delete file requires teamspace ID and studio ID")
}
if remotePath == "" {
return errors.New("studio delete file requires remote path")
}
api, err := sdkclient.NewRaw()
if err != nil {
return err
}
query := url.Values{}
if s.cloud != "" {
query.Set("clusterId", s.cloud)
}
return api.Do(context.Background(), http.MethodDelete,
studioArtifactBlobPath(s.teamspaceID, s.id, remotePath), query, nil, nil)
}
// DeleteFolder removes a studio drive folder and everything under it.
func (s *Studio) DeleteFolder(remotePath string) error {
if s == nil || s.teamspaceID == "" || s.id == "" {
return errors.New("studio delete folder requires teamspace ID and studio ID")
}
remotePath = strings.Trim(remotePath, "/")
if remotePath == "" {
return errors.New("studio delete folder requires remote path")
}
api, err := sdkclient.NewRaw()
if err != nil {
return err
}
query := url.Values{}
if s.cloud != "" {
query.Set("clusterId", s.cloud)
}
return api.Do(context.Background(), http.MethodDelete,
studioArtifactTreePath(s.teamspaceID, s.id, remotePath), query, nil, nil)
}
// RunWithExitCode runs commands in the studio and returns output plus exit code.
func (s *Studio) RunWithExitCode(commands ...string) (string, int, error) {
if s == nil || s.teamspaceID == "" || s.id == "" {
return "", 0, errors.New("studio run requires teamspace ID and studio ID")
}
if s.status != "" && !isRunningStatus(s.status) {
return "", 0, fmt.Errorf("cannot run command in studio %q with status %q", s.name, s.status)
}
api, err := sdkclient.New()
if err != nil {
return "", 0, err
}
submitResp, err := api.CloudSpaceService.CloudSpaceServiceExecuteCommandInCloudSpace(
cloud_space_service.NewCloudSpaceServiceExecuteCommandInCloudSpaceParamsWithContext(context.Background()).
WithProjectID(s.teamspaceID).
WithID(s.id).
WithBody(&models.CloudSpaceServiceExecuteCommandInCloudSpaceBody{
Command: strings.Join(commands, "; "),
Detached: true,
}),
)
if err != nil {
return "", 0, err
}
if submitResp.Payload == nil {
return "", 0, errors.New("submit studio command returned empty payload")
}
if submitResp.Payload.SessionName == "" {
return "", 0, errors.New("submit studio command returned empty session name")
}
for {
statusResp, err := api.CloudSpaceService.CloudSpaceServiceGetLongRunningCommandInCloudSpace(
cloud_space_service.NewCloudSpaceServiceGetLongRunningCommandInCloudSpaceParamsWithContext(context.Background()).
WithProjectID(s.teamspaceID).
WithID(s.id).
WithSession(submitResp.Payload.SessionName),
)
if err != nil {
return "", 0, err
}
if statusResp.Payload == nil {
return "", 0, errors.New("get studio command status returned empty payload")
}
if statusResp.Payload.ExitCode == -1 {
time.Sleep(time.Second)
continue
}
return strings.TrimSpace(statusResp.Payload.Output), int(statusResp.Payload.ExitCode), nil
}
}
// Run runs commands in the studio and returns output when they succeed.
func (s *Studio) Run(commands ...string) (string, error) {
output, exitCode, err := s.RunWithExitCode(commands...)
if err != nil {
return "", err
}
if exitCode != 0 {
return "", errors.New(output)
}
return output, nil
}
// RunAndDetach starts commands in the studio and polls briefly for completion.
func (s *Studio) RunAndDetach(commands []string, opts RunAndDetachOptions) (string, int, error) {
if s == nil || s.teamspaceID == "" || s.id == "" {
return "", 0, errors.New("studio run and detach requires teamspace ID and studio ID")
}
if s.status != "" && !isRunningStatus(s.status) {
return "", 0, fmt.Errorf("cannot run command in studio %q with status %q", s.name, s.status)
}
if opts.Timeout == 0 {
opts.Timeout = 10 * time.Second
}
if opts.CheckInterval == 0 {
opts.CheckInterval = time.Second
}
if opts.CheckInterval > opts.Timeout {
return "", 0, errors.New("check interval must be less than timeout")
}
api, err := sdkclient.New()
if err != nil {
return "", 0, err
}
submitResp, err := api.CloudSpaceService.CloudSpaceServiceExecuteCommandInCloudSpace(
cloud_space_service.NewCloudSpaceServiceExecuteCommandInCloudSpaceParamsWithContext(context.Background()).
WithProjectID(s.teamspaceID).
WithID(s.id).
WithBody(&models.CloudSpaceServiceExecuteCommandInCloudSpaceBody{
Command: strings.Join(commands, "; "),
Detached: true,
}),
)
if err != nil {
return "", 0, err
}
if submitResp.Payload == nil {
return "", 0, errors.New("submit studio command returned empty payload")
}
if submitResp.Payload.SessionName == "" {
return "", 0, errors.New("submit studio command returned empty session name")
}
output := ""
exitCode := -1
deadline := time.Now().Add(opts.Timeout)
for time.Now().Before(deadline) {
statusResp, err := api.CloudSpaceService.CloudSpaceServiceGetLongRunningCommandInCloudSpace(
cloud_space_service.NewCloudSpaceServiceGetLongRunningCommandInCloudSpaceParamsWithContext(context.Background()).
WithProjectID(s.teamspaceID).
WithID(s.id).
WithSession(submitResp.Payload.SessionName),
)
if err != nil {
return "", 0, err
}
if statusResp.Payload == nil {
return "", 0, errors.New("get studio command status returned empty payload")
}
if statusResp.Payload.ExitCode == -1 {
time.Sleep(opts.CheckInterval)
continue
}
exitCode = int(statusResp.Payload.ExitCode)
output += statusResp.Payload.Output
if exitCode != 0 {
return output, exitCode, fmt.Errorf("command failed with exit code %d. Output: %s", exitCode, statusResp.Payload.Output)
}
return output, exitCode, nil
}
return output, exitCode, nil
}
// Rename renames the studio.
func (s *Studio) Rename(newName string) error {
if s == nil || s.teamspaceID == "" || s.id == "" {
return errors.New("studio rename requires teamspace ID and studio ID")
}
if newName == "" {
return errors.New("studio rename requires name")
}
if newName == s.name {
return nil
}
api, err := sdkclient.New()
if err != nil {
return err
}
resp, err := api.CloudSpaceService.CloudSpaceServiceUpdateCloudSpace(
cloud_space_service.NewCloudSpaceServiceUpdateCloudSpaceParamsWithContext(context.Background()).
WithProjectID(s.teamspaceID).
WithID(s.id).
WithBody(&models.CloudSpaceServiceUpdateCloudSpaceBody{DisplayName: newName}),
)
if err != nil {
return err
}
if resp.Payload == nil {
s.name = newName
return nil
}
updated := studioFromCloudSpace(resp.Payload, studioOptions{
teamspaceID: s.teamspaceID,
teamspaceName: s.Teamspace(),
ownerName: s.OwnerName(),
cloud: s.cloud,
machine: s.machine,
interruptible: s.interruptible,
})
if updated != nil {
*s = *updated
}
return nil
}
// Duplicate forks the studio into a new studio.
func (s *Studio) Duplicate(opts ...DuplicateStudioOptions) (*Studio, error) {
if s == nil || s.teamspaceID == "" || s.id == "" {
return nil, errors.New("studio duplicate requires teamspace ID and studio ID")
}
resolved := applyDuplicateStudioOptions(opts...)
targetTeamspaceID := firstNonEmpty(resolved.teamspaceID, s.teamspaceID)
targetTeamspaceName := firstNonEmpty(resolved.teamspaceName, s.Teamspace())
api, err := sdkclient.New()
if err != nil {
return nil, err
}
resp, err := api.CloudSpaceService.CloudSpaceServiceForkCloudSpace(
cloud_space_service.NewCloudSpaceServiceForkCloudSpaceParamsWithContext(context.Background()).
WithProjectID(s.teamspaceID).
WithID(s.id).
WithBody(&models.CloudSpaceServiceForkCloudSpaceBody{
NewName: resolved.name,
TargetProjectID: targetTeamspaceID,
}),
)
if err != nil {
return nil, err
}
if resp.Payload == nil {
return nil, fmt.Errorf("duplicate studio returned empty payload")
}
return studioFromCloudSpace(resp.Payload, studioOptions{
teamspaceID: targetTeamspaceID,
teamspaceName: targetTeamspaceName,
ownerName: s.OwnerName(),
cloud: s.cloud,
machine: s.machine,
interruptible: s.interruptible,
}), nil
}
// SetEnv replaces or patches the studio environment.
func (s *Studio) SetEnv(newEnv map[string]string, partial bool) error {
if s == nil || s.teamspaceID == "" || s.id == "" {
return errors.New("studio set env requires teamspace ID and studio ID")
}
for key := range newEnv {
if !validSecretName(key) {
return errors.New("environment variable names must start with a letter or underscore and contain only letters, numbers, and underscores")
}
}
updatedEnv := map[string]string{}
if partial {
for key, value := range s.env {
updatedEnv[key] = value
}
}
for key, value := range newEnv {
updatedEnv[key] = value
}
api, err := sdkclient.New()
if err != nil {
return err
}
resp, err := api.CloudSpaceService.CloudSpaceServiceUpdateCloudSpace(
cloud_space_service.NewCloudSpaceServiceUpdateCloudSpaceParamsWithContext(context.Background()).
WithProjectID(s.teamspaceID).
WithID(s.id).
WithBody(&models.CloudSpaceServiceUpdateCloudSpaceBody{Env: envVars(updatedEnv)}),
)
if err != nil {
return err
}
s.env = updatedEnv
if resp.Payload == nil {
return nil
}
updated := studioFromCloudSpace(resp.Payload, studioOptions{
teamspaceID: s.teamspaceID,
teamspaceName: s.Teamspace(),
ownerName: s.OwnerName(),
cloud: s.cloud,
machine: s.machine,
interruptible: s.interruptible,
})
if updated != nil {
*s = *updated
}
return nil
}
// DeleteEnv deletes one directly configured Studio environment variable.
func (s *Studio) DeleteEnv(key string) error {
if s == nil || s.teamspaceID == "" || s.id == "" {
return errors.New("studio delete env requires teamspace ID and studio ID")
}
if !validSecretName(key) {
return errors.New("environment variable names must start with a letter or underscore and contain only letters, numbers, and underscores")
}
if _, ok := s.env[key]; !ok {
return fmt.Errorf("studio environment variable %q was not found", key)
}
updated := make(map[string]string, len(s.env)-1)
for name, value := range s.env {
if name != key {
updated[name] = value
}
}
return s.SetEnv(updated, false)
}
// AvailablePlugins lists plugins available for installation.
func (s *Studio) AvailablePlugins() (map[string]string, error) {
if s == nil || s.teamspaceID == "" || s.id == "" {
return nil, errors.New("studio available plugins requires teamspace ID and studio ID")
}
api, err := sdkclient.New()
if err != nil {
return nil, err
}
response, err := api.CloudSpaceService.CloudSpaceServiceListAvailablePlugins(
cloud_space_service.NewCloudSpaceServiceListAvailablePluginsParamsWithContext(context.Background()).
WithProjectID(&s.teamspaceID).
WithID(&s.id),
)
if err != nil {