-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathservice.go
More file actions
1364 lines (1133 loc) · 46.3 KB
/
service.go
File metadata and controls
1364 lines (1133 loc) · 46.3 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 cmd
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/timescale/tiger-cli/internal/tiger/api"
"github.com/timescale/tiger-cli/internal/tiger/config"
"github.com/timescale/tiger-cli/internal/tiger/password"
"github.com/timescale/tiger-cli/internal/tiger/util"
)
var (
// getCredentialsForService can be overridden for testing
getCredentialsForService = config.GetCredentials
)
// buildServiceCmd creates the main service command with all subcommands
func buildServiceCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "service",
Aliases: []string{"services", "svc"},
Short: "Manage database services",
Long: `Manage database services within Tiger Cloud platform.`,
}
// Add all subcommands
cmd.AddCommand(buildServiceGetCmd())
cmd.AddCommand(buildServiceListCmd())
cmd.AddCommand(buildServiceCreateCmd())
cmd.AddCommand(buildServiceDeleteCmd())
cmd.AddCommand(buildServiceUpdatePasswordCmd())
cmd.AddCommand(buildServiceForkCmd())
return cmd
}
// buildServiceGetCmd represents the get command under service
func buildServiceGetCmd() *cobra.Command {
var withPassword bool
var output string
cmd := &cobra.Command{
Use: "get [service-id]",
Aliases: []string{"describe", "show"},
Short: "Show detailed information about a service",
Long: `Show detailed information about a specific database service.
The service ID can be provided as an argument or will use the default service
from your configuration. This command displays comprehensive information about
the service including configuration, status, endpoints, and resource usage.
Examples:
# Get default service details
tiger service get
# Get specific service details
tiger service get svc-12345
# Get service details in JSON format
tiger service get svc-12345 --output json
# Get service details in YAML format
tiger service get svc-12345 --output yaml`,
Args: cobra.MaximumNArgs(1),
ValidArgsFunction: serviceIDCompletion,
RunE: func(cmd *cobra.Command, args []string) error {
// Get config
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
// Use flag value if provided, otherwise use config value
if cmd.Flags().Changed("output") {
cfg.Output = output
}
// Determine service ID
serviceID, err := getServiceID(cfg, args)
if err != nil {
return err
}
cmd.SilenceUsage = true
// Get API key and project ID for authentication
apiKey, projectID, err := getCredentialsForService()
if err != nil {
return exitWithCode(ExitAuthenticationError, fmt.Errorf("authentication required: %w. Please run 'tiger auth login'", err))
}
// Create API client
client, err := api.NewTigerClient(cfg, apiKey)
if err != nil {
return fmt.Errorf("failed to create API client: %w", err)
}
// Make API call to get service details
ctx, cancel := context.WithTimeout(cmd.Context(), 30*time.Second)
defer cancel()
resp, err := client.GetProjectsProjectIdServicesServiceIdWithResponse(ctx, projectID, serviceID)
if err != nil {
return fmt.Errorf("failed to get service details: %w", err)
}
// Handle API response
if resp.StatusCode() != 200 {
return exitWithErrorFromStatusCode(resp.StatusCode(), resp.JSON4XX)
}
if resp.JSON200 == nil {
return fmt.Errorf("empty response from API")
}
service := *resp.JSON200
// Output service in requested format
return outputService(cmd, service, cfg.Output, withPassword, true)
},
}
cmd.Flags().BoolVar(&withPassword, "with-password", false, "Include password in output")
cmd.Flags().VarP((*outputWithEnvFlag)(&output), "output", "o", "output format (json, yaml, env, table)")
return cmd
}
// serviceListCmd represents the list command under service
func buildServiceListCmd() *cobra.Command {
var output string
cmd := &cobra.Command{
Use: "list",
Short: "List all services",
Long: `List all database services in the current project.`,
Args: cobra.NoArgs,
ValidArgsFunction: cobra.NoFileCompletions,
RunE: func(cmd *cobra.Command, args []string) error {
// Get config
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
// Use flag value if provided, otherwise use config value
if cmd.Flags().Changed("output") {
cfg.Output = output
}
cmd.SilenceUsage = true
// Get API key and project ID for authentication
apiKey, projectID, err := getCredentialsForService()
if err != nil {
return exitWithCode(ExitAuthenticationError, fmt.Errorf("authentication required: %w. Please run 'tiger auth login'", err))
}
// Create API client
client, err := api.NewTigerClient(cfg, apiKey)
if err != nil {
return fmt.Errorf("failed to create API client: %w", err)
}
// Make API call to list services
ctx, cancel := context.WithTimeout(cmd.Context(), 30*time.Second)
defer cancel()
resp, err := client.GetProjectsProjectIdServicesWithResponse(ctx, projectID)
if err != nil {
return fmt.Errorf("failed to list services: %w", err)
}
statusOutput := cmd.ErrOrStderr()
// Handle API response
if resp.StatusCode() != 200 {
return exitWithErrorFromStatusCode(resp.StatusCode(), resp.JSON4XX)
}
services := *resp.JSON200
if len(services) == 0 {
fmt.Fprintln(statusOutput, "🏜️ No services found! Your project is looking a bit empty.")
fmt.Fprintln(statusOutput, "🚀 Ready to get started? Create your first service with: tiger service create")
return nil
}
if resp.JSON200 == nil {
fmt.Fprintln(statusOutput, "🏜️ No services found! Your project is looking a bit empty.")
fmt.Fprintln(statusOutput, "🚀 Ready to get started? Create your first service with: tiger service create")
return nil
}
// Output services in requested format
return outputServices(cmd, services, cfg.Output)
},
}
cmd.Flags().VarP((*outputFlag)(&output), "output", "o", "output format (json, yaml, table)")
return cmd
}
// serviceCreateCmd represents the create command under service
func buildServiceCreateCmd() *cobra.Command {
var createServiceName string
var createAddons []string
var createRegionCode string
var createCpuMillis string
var createMemoryGBs string
var createReplicaCount int
var createNoWait bool
var createWaitTimeout time.Duration
var createNoSetDefault bool
var createWithPassword bool
var createEnvironment string
var output string
cmd := &cobra.Command{
Use: "create",
Short: "Create a new database service",
Long: `Create a new database service in the current project.
The default type of service created depends on your plan:
- Free plan: Creates a service with shared CPU/memory and the 'time-series' and 'ai' add-ons
- Paid plans: Creates a service with 0.5 CPU / 2 GB memory and the 'time-series' add-on
By default, the newly created service will be set as your default service for future
commands. Use --no-set-default to prevent this behavior.
Examples:
# Create a TimescaleDB service with all defaults (0.5 CPU, 2GB, us-east-1, auto-generated name)
tiger service create
# Create a free TimescaleDB service
tiger service create --name free-db --cpu shared
# Create a TimescaleDB service with AI add-ons
tiger service create --name hybrid-db --addons time-series,ai
# Create a plain Postgres service
tiger service create --name postgres-db --addons none
# Create a service with more resources (waits for ready by default)
tiger service create --name resources-db --cpu 2000 --memory 8 --replicas 2
# Create service in a different region
tiger service create --name eu-db --region eu-central-1
# Create service without setting it as default
tiger service create --name temp-db --no-set-default
# Create service specifying only CPU (memory will be auto-configured to 8GB)
tiger service create --name auto-memory --cpu 2000
# Create service specifying only memory (CPU will be auto-configured to 4000m)
tiger service create --name auto-cpu --memory 16
# Create service without waiting for completion
tiger service create --name quick-db --no-wait
# Create service with custom wait timeout
tiger service create --name patient-db --wait-timeout 1h
Allowed CPU/Memory Configurations:
shared / shared | 0.5 CPU (500m) / 2GB | 1 CPU (1000m) / 4GB | 2 CPU (2000m) / 8GB
4 CPU (4000m) / 16GB | 8 CPU (8000m) / 32GB | 16 CPU (16000m) / 64GB | 32 CPU (32000m) / 128GB
Note: You can specify both CPU and memory together, or specify only one (the other will be automatically configured).`,
Args: cobra.NoArgs,
ValidArgsFunction: cobra.NoFileCompletions,
RunE: func(cmd *cobra.Command, args []string) error {
// Get config
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
// Use flag value if provided, otherwise use config value
if cmd.Flags().Changed("output") {
cfg.Output = output
}
// Auto-generate service name if not provided
if createServiceName == "" {
createServiceName = util.GenerateServiceName()
}
// Validate addons and resources
addons, err := util.ValidateAddons(createAddons)
if err != nil {
return err
}
if createReplicaCount < 0 {
return fmt.Errorf("replica count must be non-negative (--replicas)")
}
// Validate and normalize environment tag (case-insensitive)
createEnvironment = strings.ToUpper(createEnvironment)
if createEnvironment != "DEV" && createEnvironment != "PROD" {
return fmt.Errorf("environment must be either 'DEV' or 'PROD', got '%s'", createEnvironment)
}
// Validate and normalize CPU/Memory configuration
cpuMillis, memoryGBs, err := util.ValidateAndNormalizeCPUMemory(createCpuMillis, createMemoryGBs)
if err != nil {
return err
}
// Validate wait timeout (Cobra handles parsing automatically)
if createWaitTimeout <= 0 {
return fmt.Errorf("wait timeout must be positive, got %v", createWaitTimeout)
}
cmd.SilenceUsage = true
// Get API key and project ID for authentication
apiKey, projectID, err := getCredentialsForService()
if err != nil {
return exitWithCode(ExitAuthenticationError, fmt.Errorf("authentication required: %w. Please run 'tiger auth login'", err))
}
// Create API client
client, err := api.NewTigerClient(cfg, apiKey)
if err != nil {
return fmt.Errorf("failed to create API client: %w", err)
}
// Prepare service creation request
environmentTag := api.EnvironmentTag(createEnvironment)
serviceCreateReq := api.ServiceCreate{
Name: createServiceName,
Addons: util.ConvertStringSlicePtr[api.ServiceCreateAddons](addons),
ReplicaCount: &createReplicaCount,
CpuMillis: cpuMillis,
MemoryGbs: memoryGBs,
EnvironmentTag: &environmentTag,
}
if createRegionCode != "" {
serviceCreateReq.RegionCode = &createRegionCode
}
// Make API call to create service
ctx, cancel := context.WithTimeout(cmd.Context(), 30*time.Second)
defer cancel()
// All status messages go to stderr
statusOutput := cmd.ErrOrStderr()
if cmd.Flags().Changed("name") {
fmt.Fprintf(statusOutput, "🚀 Creating service '%s'...\n", createServiceName)
} else {
fmt.Fprintf(statusOutput, "🚀 Creating service '%s' (auto-generated name)...\n", createServiceName)
}
resp, err := client.PostProjectsProjectIdServicesWithResponse(ctx, projectID, serviceCreateReq)
if err != nil {
return fmt.Errorf("failed to create service: %w", err)
}
// Handle API response
switch resp.StatusCode() {
case 202:
// Success - service creation accepted
if resp.JSON202 == nil {
fmt.Fprintln(statusOutput, "✅ Service creation request accepted!")
return nil
}
service := *resp.JSON202
serviceID := util.Deref(service.ServiceId)
fmt.Fprintf(statusOutput, "✅ Service creation request accepted!\n")
fmt.Fprintf(statusOutput, "📋 Service ID: %s\n", serviceID)
// Save password immediately after service creation, before any waiting
// This ensures users have access even if they interrupt the wait or it fails
passwordSaved := handlePasswordSaving(service, util.Deref(service.InitialPassword), statusOutput)
// Set as default service unless --no-set-default is specified
if !createNoSetDefault {
if err := setDefaultService(cfg, serviceID, statusOutput); err != nil {
// Log warning but don't fail the command
fmt.Fprintf(statusOutput, "⚠️ Warning: Failed to set service as default: %v\n", err)
}
}
// Handle wait behavior
var serviceErr error
if createNoWait {
fmt.Fprintf(statusOutput, "⏳ Service is being created. Use 'tiger service list' to check status.\n")
} else {
// Wait for service to be ready
fmt.Fprintf(statusOutput, "⏳ Waiting for service to be ready (wait timeout: %v)...\n", createWaitTimeout)
service.Status, serviceErr = waitForServiceReady(cmd.Context(), client, projectID, serviceID, createWaitTimeout, service.Status, statusOutput)
if serviceErr != nil {
fmt.Fprintf(statusOutput, "❌ Error: %s\n", serviceErr)
} else {
fmt.Fprintf(statusOutput, "🎉 Service is ready and running!\n")
printConnectMessage(statusOutput, passwordSaved, createNoSetDefault, serviceID)
}
}
if err := outputService(cmd, service, cfg.Output, createWithPassword, false); err != nil {
fmt.Fprintf(statusOutput, "⚠️ Warning: Failed to output service details: %v\n", err)
}
// Return error for sake of exit code, but silence it since it was already output above
cmd.SilenceErrors = true
return serviceErr
default:
return exitWithErrorFromStatusCode(resp.StatusCode(), resp.JSON4XX)
}
},
}
// Add flags
cmd.Flags().StringVar(&createServiceName, "name", "", "Service name (auto-generated if not provided)")
cmd.Flags().StringSliceVar(&createAddons, "addons", nil, fmt.Sprintf("Addons to enable (%s, or 'none' for PostgreSQL-only)", strings.Join(util.ValidAddons(), ", ")))
cmd.Flags().StringVar(&createRegionCode, "region", "", "Region code")
cmd.Flags().StringVar(&createCpuMillis, "cpu", "", "CPU allocation in millicores or 'shared'")
cmd.Flags().StringVar(&createMemoryGBs, "memory", "", "Memory allocation in gigabytes or 'shared'")
cmd.Flags().IntVar(&createReplicaCount, "replicas", 0, "Number of high-availability replicas")
cmd.Flags().StringVar(&createEnvironment, "environment", "DEV", "Environment tag (DEV or PROD)")
cmd.Flags().BoolVar(&createNoWait, "no-wait", false, "Don't wait for operation to complete")
cmd.Flags().DurationVar(&createWaitTimeout, "wait-timeout", 30*time.Minute, "Wait timeout duration (e.g., 30m, 1h30m, 90s)")
cmd.Flags().BoolVar(&createNoSetDefault, "no-set-default", false, "Don't set this service as the default service")
cmd.Flags().BoolVar(&createWithPassword, "with-password", false, "Include password in output")
cmd.Flags().VarP((*outputWithEnvFlag)(&output), "output", "o", "output format (json, yaml, env, table)")
return cmd
}
// buildServiceUpdatePasswordCmd creates a new update-password command
func buildServiceUpdatePasswordCmd() *cobra.Command {
var updatePasswordValue string
cmd := &cobra.Command{
Use: "update-password [service-id]",
Short: "Update the master password for a service",
Long: `Update the master password for a specific database service.
The service ID can be provided as an argument or will use the default service
from your configuration. This command updates the master password for the
'tsdbadmin' user used to authenticate to the database service.
Examples:
# Update password for default service
tiger service update-password --new-password new-secure-password
# Update password for specific service
tiger service update-password svc-12345 --new-password new-secure-password
# Update password using environment variable (TIGER_NEW_PASSWORD)
export TIGER_NEW_PASSWORD="new-secure-password"
tiger service update-password svc-12345
# Update password and save to .pgpass (default behavior)
tiger service update-password svc-12345 --new-password new-secure-password
# Update password without saving (using global flag)
tiger service update-password svc-12345 --new-password new-secure-password --password-storage none`,
Args: cobra.MaximumNArgs(1),
ValidArgsFunction: serviceIDCompletion,
RunE: func(cmd *cobra.Command, args []string) error {
// Get config
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
// Determine service ID
serviceID, err := getServiceID(cfg, args)
if err != nil {
return err
}
// Get password from flag or environment variable via viper
password := viper.GetString("new_password")
if password == "" {
return fmt.Errorf("new password is required. Use --new-password flag or set TIGER_NEW_PASSWORD environment variable")
}
cmd.SilenceUsage = true
// Get API key and project ID for authentication
apiKey, projectID, err := getCredentialsForService()
if err != nil {
return exitWithCode(ExitAuthenticationError, fmt.Errorf("authentication required: %w. Please run 'tiger auth login'", err))
}
// Create API client
client, err := api.NewTigerClient(cfg, apiKey)
if err != nil {
return fmt.Errorf("failed to create API client: %w", err)
}
// Prepare password update request
updateReq := api.UpdatePasswordInput{
Password: password,
}
// Make API call to update password
ctx, cancel := context.WithTimeout(cmd.Context(), 30*time.Second)
defer cancel()
resp, err := client.PostProjectsProjectIdServicesServiceIdUpdatePasswordWithResponse(ctx, projectID, serviceID, updateReq)
if err != nil {
return fmt.Errorf("failed to update service password: %w", err)
}
statusOutput := cmd.ErrOrStderr()
// Handle API response
if resp.StatusCode() != 200 && resp.StatusCode() != 204 {
return exitWithErrorFromStatusCode(resp.StatusCode(), resp.JSON4XX)
}
fmt.Fprintf(statusOutput, "✅ Master password for 'tsdbadmin' user updated successfully\n")
// Handle password storage using the configured method
// Get the service details for password storage
serviceResp, err := client.GetProjectsProjectIdServicesServiceIdWithResponse(ctx, projectID, serviceID)
if err == nil && serviceResp.StatusCode() == 200 && serviceResp.JSON200 != nil {
handlePasswordSaving(*serviceResp.JSON200, password, statusOutput)
}
return nil
},
}
// Add flags
cmd.Flags().StringVar(&updatePasswordValue, "new-password", "", "New password for the tsdbadmin user (can also be set via TIGER_NEW_PASSWORD env var)")
// Bind flags to viper
viper.BindPFlag("new_password", cmd.Flags().Lookup("new-password"))
return cmd
}
// OutputService represents a service with computed fields for output
type OutputService struct {
api.Service
password.ConnectionDetails
ConnectionString string `json:"connection_string,omitempty" yaml:"connection_string,omitempty"`
ConsoleURL string `json:"console_url,omitempty" yaml:"console_url,omitempty"`
}
// outputService formats and outputs a single service based on the specified format
func outputService(cmd *cobra.Command, service api.Service, format string, withPassword bool, strict bool) error {
// Prepare the output service with computed fields
outputSvc := prepareServiceForOutput(service, withPassword, cmd.ErrOrStderr())
if strict && withPassword && outputSvc.Password == "" {
return fmt.Errorf("password requested but not available for service %s", util.Deref(outputSvc.ServiceId))
}
outputWriter := cmd.OutOrStdout()
switch strings.ToLower(format) {
case "json":
return util.SerializeToJSON(outputWriter, outputSvc)
case "yaml":
return util.SerializeToYAML(outputWriter, outputSvc, true)
case "env":
return outputServiceEnv(outputSvc, outputWriter)
default: // table format (default)
return outputServiceTable(outputSvc, outputWriter)
}
}
// outputServices formats and outputs the services list based on the specified format
func outputServices(cmd *cobra.Command, services []api.Service, format string) error {
outputServices := prepareServicesForOutput(services, cmd.ErrOrStderr())
outputWriter := cmd.OutOrStdout()
switch strings.ToLower(format) {
case "json":
return util.SerializeToJSON(outputWriter, outputServices)
case "yaml":
return util.SerializeToYAML(outputWriter, outputServices, true)
case "env":
return fmt.Errorf("environment variable output is not supported for multiple services")
default: // table format (default)
return outputServicesTable(outputServices, outputWriter)
}
}
// outputServiceEnv outputs service details in environment variable format
func outputServiceEnv(service OutputService, output io.Writer) error {
fmt.Fprintf(output, "PGHOST=%s\n", service.Host)
fmt.Fprintf(output, "PGPORT=%d\n", service.Port)
fmt.Fprintf(output, "PGDATABASE=%s\n", service.Database)
fmt.Fprintf(output, "PGUSER=%s\n", service.Role)
if service.Password != "" {
fmt.Fprintf(output, "PGPASSWORD=%s\n", service.Password)
}
return nil
}
// outputServiceTable outputs detailed service information in a formatted table
func outputServiceTable(service OutputService, output io.Writer) error {
table := tablewriter.NewWriter(output)
table.Header("PROPERTY", "VALUE")
// Basic service information
table.Append("Service ID", util.Deref(service.ServiceId))
table.Append("Name", util.Deref(service.Name))
table.Append("Status", util.DerefStr(service.Status))
table.Append("Type", util.DerefStr(service.ServiceType))
table.Append("Region", util.Deref(service.RegionCode))
// Environment tag
if service.Metadata != nil && service.Metadata.Environment != nil {
table.Append("Environment", *service.Metadata.Environment)
}
// Resource information from Resources slice
if service.Resources != nil && len(*service.Resources) > 0 {
resource := (*service.Resources)[0] // Get first resource
if resource.Spec != nil {
if resource.Spec.CpuMillis != nil {
cpuCores := float64(*resource.Spec.CpuMillis) / 1000
if cpuCores == float64(int(cpuCores)) {
table.Append("CPU", fmt.Sprintf("%.0f cores (%dm)", cpuCores, *resource.Spec.CpuMillis))
} else {
table.Append("CPU", fmt.Sprintf("%.1f cores (%dm)", cpuCores, *resource.Spec.CpuMillis))
}
} else {
// CPU is null - this indicates a free tier service
table.Append("CPU", "shared")
}
if resource.Spec.MemoryGbs != nil {
table.Append("Memory", fmt.Sprintf("%d GB", *resource.Spec.MemoryGbs))
} else {
// Memory is null - this indicates a free tier service
table.Append("Memory", "shared")
}
}
}
// High availability replicas
if service.HaReplicas != nil {
if service.HaReplicas.ReplicaCount != nil {
table.Append("Replicas", fmt.Sprintf("%d", *service.HaReplicas.ReplicaCount))
}
}
// Endpoint information
if service.Endpoint != nil {
if service.Endpoint.Host != nil {
port := "5432"
if service.Endpoint.Port != nil {
port = fmt.Sprintf("%d", *service.Endpoint.Port)
}
table.Append("Direct Endpoint", fmt.Sprintf("%s:%s", *service.Endpoint.Host, port))
}
}
// Connection pooler information
if service.ConnectionPooler != nil && service.ConnectionPooler.Endpoint != nil {
if service.ConnectionPooler.Endpoint.Host != nil {
port := "6432"
if service.ConnectionPooler.Endpoint.Port != nil {
port = fmt.Sprintf("%d", *service.ConnectionPooler.Endpoint.Port)
}
table.Append("Pooler Endpoint", fmt.Sprintf("%s:%s", *service.ConnectionPooler.Endpoint.Host, port))
}
}
// Pause status
if service.Paused != nil && *service.Paused {
table.Append("Paused", "Yes")
}
// Timestamps
if service.Created != nil {
table.Append("Created", service.Created.Format("2006-01-02 15:04:05 MST"))
}
// Output password if available
if service.Password != "" {
table.Append("Password", service.Password)
}
// Output connection string if available
if service.ConnectionString != "" {
table.Append("Connection String", service.ConnectionString)
}
if service.ConsoleURL != "" {
table.Append("Console URL", service.ConsoleURL)
}
return table.Render()
}
// outputServicesTable outputs services in a formatted table using tablewriter
func outputServicesTable(services []OutputService, output io.Writer) error {
table := tablewriter.NewWriter(output)
table.Header("SERVICE ID", "NAME", "STATUS", "TYPE", "REGION", "CREATED")
for _, service := range services {
table.Append(
util.Deref(service.ServiceId),
util.Deref(service.Name),
util.DerefStr(service.Status),
util.DerefStr(service.ServiceType),
util.Deref(service.RegionCode),
formatTimePtr(service.Created),
)
}
return table.Render()
}
func prepareServiceForOutput(service api.Service, withPassword bool, output io.Writer) OutputService {
outputSvc := OutputService{
Service: service,
}
outputSvc.InitialPassword = nil
opts := password.ConnectionDetailsOptions{
Role: "tsdbadmin",
WithPassword: withPassword,
InitialPassword: util.Deref(service.InitialPassword),
}
if connectionDetails, err := password.GetConnectionDetails(service, opts); err != nil {
if output != nil {
fmt.Fprintf(output, "⚠️ Warning: Failed to get connection details: %v\n", err)
}
} else {
outputSvc.ConnectionDetails = *connectionDetails
outputSvc.ConnectionString = connectionDetails.String()
}
// Build console URL
if cfg, err := config.Load(); err == nil {
url := fmt.Sprintf("%s/dashboard/services/%s", cfg.ConsoleURL, *service.ServiceId)
outputSvc.ConsoleURL = url
}
return outputSvc
}
// prepareServicesForOutput creates copies of services with sensitive fields removed
func prepareServicesForOutput(services []api.Service, output io.Writer) []OutputService {
prepared := make([]OutputService, len(services))
for i, service := range services {
prepared[i] = prepareServiceForOutput(service, false, output)
}
return prepared
}
// formatTimePtr formats a time pointer, returning empty string if nil
func formatTimePtr(t *time.Time) string {
if t == nil {
return ""
}
return t.Format("2006-01-02 15:04")
}
// waitForServiceReady polls the service status until it's ready or timeout occurs
func waitForServiceReady(ctx context.Context, client *api.ClientWithResponses, projectID, serviceID string, waitTimeout time.Duration, initialStatus *api.DeployStatus, output io.Writer) (*api.DeployStatus, error) {
ctx, cancel := context.WithTimeout(ctx, waitTimeout)
defer cancel()
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
// Start the spinner
spinner := NewSpinner(output, "Service status: %s", util.DerefStr(initialStatus))
defer spinner.Stop()
lastStatus := initialStatus
for {
select {
case <-ctx.Done():
switch {
case errors.Is(ctx.Err(), context.DeadlineExceeded):
return lastStatus, exitWithCode(ExitTimeout, fmt.Errorf("wait timeout reached after %v - service may still be provisioning", waitTimeout))
case errors.Is(ctx.Err(), context.Canceled):
return lastStatus, exitWithCode(ExitGeneralError, fmt.Errorf("canceled waiting - service may still be provisioning"))
default:
return lastStatus, exitWithCode(ExitGeneralError, fmt.Errorf("error waiting - service may still be provisioning: %w", ctx.Err()))
}
case <-ticker.C:
resp, err := client.GetProjectsProjectIdServicesServiceIdWithResponse(ctx, projectID, serviceID)
if err != nil {
spinner.Update("Error checking service status: %v", err)
continue
}
if resp.StatusCode() != 200 || resp.JSON200 == nil {
spinner.Update("Service not found or error checking status")
continue
}
service := *resp.JSON200
lastStatus = service.Status
status := util.DerefStr(service.Status)
switch status {
case "READY":
return service.Status, nil
case "FAILED", "ERROR":
return service.Status, fmt.Errorf("service creation failed with status: %s", status)
default:
spinner.Update("Service status: %s", status)
}
}
}
}
// handlePasswordSaving handles saving password using the configured storage
// method and displaying appropriate messages. Returns true if the password was
// successfully saved, or false if not.
func handlePasswordSaving(service api.Service, initialPassword string, output io.Writer) bool {
// Note: We don't fail the service creation if password saving fails
// The error is handled by displaying the appropriate message below
result, _ := password.SavePasswordWithResult(service, initialPassword, "tsdbadmin")
if result.Method == "none" && result.Message == "No password provided" {
// Don't output anything for empty password
return false
}
// Output the message with appropriate emoji
if result.Success {
fmt.Fprintf(output, "🔐 %s\n", result.Message)
return true
} else if result.Method == "none" {
fmt.Fprintf(output, "💡 %s\n", result.Message)
} else {
fmt.Fprintf(output, "⚠️ %s\n", result.Message)
}
return false
}
// setDefaultService sets the given service as the default service in the configuration
func setDefaultService(cfg *config.Config, serviceID string, output io.Writer) error {
if err := cfg.Set("service_id", serviceID); err != nil {
return fmt.Errorf("failed to save config: %w", err)
}
fmt.Fprintf(output, "🎯 Set service '%s' as default service.\n", serviceID)
return nil
}
func printConnectMessage(output io.Writer, passwordSaved, noSetDefault bool, serviceID string) {
if !passwordSaved {
// We can't connect if no password was saved, so don't show message
return
} else if noSetDefault {
// If the service wasn't set as the default, include the serviceID in the command
fmt.Fprintf(output, "🔌 Run 'tiger db connect %s' to connect to your new service\n", serviceID)
} else {
// If the service was set as the default, no need to include the serviceID in the command
fmt.Fprintf(output, "🔌 Run 'tiger db connect' to connect to your new service\n")
}
}
// buildServiceDeleteCmd creates the delete subcommand
func buildServiceDeleteCmd() *cobra.Command {
var deleteNoWait bool
var deleteWaitTimeout time.Duration
var deleteConfirm bool
cmd := &cobra.Command{
Use: "delete [service-id]",
Short: "Delete a database service",
Long: `Delete a database service permanently.
This operation is irreversible. By default, you will be prompted to type the service ID
to confirm deletion, unless you use the --confirm flag.
Note for AI agents: Always confirm with the user before performing this destructive operation.
Examples:
# Delete a service (with confirmation prompt)
tiger service delete svc-12345
# Delete service without confirmation prompt
tiger service delete svc-12345 --confirm
# Delete service without waiting for completion
tiger service delete svc-12345 --no-wait
# Delete service with custom wait timeout
tiger service delete svc-12345 --wait-timeout 15m`,
Args: cobra.MaximumNArgs(1),
ValidArgsFunction: serviceIDCompletion,
RunE: func(cmd *cobra.Command, args []string) error {
// Require explicit service ID for safety
if len(args) < 1 {
return fmt.Errorf("service ID is required")
}
serviceID := args[0]
cmd.SilenceUsage = true
// Load config
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
// Get API key and project ID for authentication
apiKey, projectID, err := getCredentialsForService()
if err != nil {
return exitWithCode(ExitAuthenticationError, fmt.Errorf("authentication required: %w. Please run 'tiger auth login'", err))
}
statusOutput := cmd.ErrOrStderr()
// Prompt for confirmation unless --confirm is used
if !deleteConfirm {
fmt.Fprintf(statusOutput, "Are you sure you want to delete service '%s'? This operation cannot be undone.\n", serviceID)
fmt.Fprintf(statusOutput, "Type the service ID '%s' to confirm: ", serviceID)
confirmation, err := readString(cmd.Context(), func() (string, error) {
reader := bufio.NewReader(os.Stdin)
return reader.ReadString('\n')
})
if err != nil {
return fmt.Errorf("failed to read confirmation: %w", err)
}
if confirmation != serviceID {
fmt.Fprintln(statusOutput, "❌ Delete operation cancelled.")
return nil
}
}
// Create API client
client, err := api.NewTigerClient(cfg, apiKey)
if err != nil {
return fmt.Errorf("failed to create API client: %w", err)
}
// Make the delete request
resp, err := client.DeleteProjectsProjectIdServicesServiceIdWithResponse(
cmd.Context(),
api.ProjectId(projectID),
api.ServiceId(serviceID),
)
if err != nil {
return fmt.Errorf("failed to delete service: %w", err)
}
// Handle response
if resp.StatusCode() != 202 {
return exitWithErrorFromStatusCode(resp.StatusCode(), resp.JSON4XX)
}
fmt.Fprintf(statusOutput, "🗑️ Delete request accepted for service '%s'.\n", serviceID)
// If not waiting, return early
if deleteNoWait {
fmt.Fprintln(statusOutput, "💡 Use 'tiger service list' to check deletion status.")
return nil
}
// Wait for deletion to complete
if err := waitForServiceDeletion(client, projectID, serviceID, deleteWaitTimeout, cmd); err != nil {
// Return error for sake of exit code, but log ourselves for sake of icon
fmt.Fprintf(statusOutput, "❌ Error: %s\n", err)
cmd.SilenceErrors = true
return err
}
return nil
},
}
cmd.Flags().BoolVar(&deleteNoWait, "no-wait", false, "Don't wait for deletion to complete, return immediately")
cmd.Flags().DurationVar(&deleteWaitTimeout, "wait-timeout", 30*time.Minute, "Wait timeout duration (e.g., 30m, 1h30m, 90s)")
cmd.Flags().BoolVar(&deleteConfirm, "confirm", false, "Skip confirmation prompt (AI agents must confirm with user first)")
return cmd
}
// waitForServiceDeletion waits for a service to be fully deleted
func waitForServiceDeletion(client *api.ClientWithResponses, projectID string, serviceID string, timeout time.Duration, cmd *cobra.Command) error {
ctx, cancel := context.WithTimeout(cmd.Context(), timeout)
defer cancel()
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
statusOutput := cmd.ErrOrStderr()
// Start the spinner
spinner := NewSpinner(statusOutput, "Waiting for service '%s' to be deleted", serviceID)