Skip to content

Commit 2be2bac

Browse files
committed
refactor
1 parent fa0b2c6 commit 2be2bac

File tree

5 files changed

+43
-39
lines changed

5 files changed

+43
-39
lines changed

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2418,3 +2418,15 @@ The code is available as open source under the terms of the [Apache License 2.0]
24182418
<a href = "https://github.com/civo/cli/graphs/contributors">
24192419
<img src = "https://contrib.rocks/image?repo=civo/cli"/>
24202420
</a>
2421+
2422+
# Get the status of the console for an instance
2423+
civo instance console status INSTANCE_ID/HOSTNAME
2424+
2425+
# Stop the console session for an instance
2426+
civo instance console stop INSTANCE_ID/HOSTNAME
2427+
2428+
# Open console (default duration)
2429+
civo instance console INSTANCE_ID/HOSTNAME
2430+
2431+
# Open console with custom duration
2432+
civo instance console INSTANCE_ID/HOSTNAME --duration 2h

cmd/instance/instance_vnc.go renamed to cmd/instance/console.go

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,42 +14,38 @@ import (
1414
"github.com/spf13/cobra"
1515
)
1616

17-
// maxAttempts represents the max number of attempts (each one every 7s) to connect to the vnc URL
17+
// maxAttempts represents the max number of attempts (each one every 7s) to connect to the console URL
1818
const maxAttempts = 5
1919

2020
var duration string
2121

22-
var instanceVncCmd = &cobra.Command{
22+
var instanceConsoleCmd = &cobra.Command{
2323
Use: "console",
24-
Aliases: []string{"vnc", "access"},
25-
Example: "civo instance vnc INSTANCE-ID/NAME [--duration 2h]",
24+
Aliases: []string{"connect"},
25+
Example: "civo instance console INSTANCE-ID/NAME [--duration 2h]",
2626
Args: cobra.MinimumNArgs(1),
27-
Short: "Enable and access the noVNC console on an instance",
28-
Long: `Enable and access the console (through the VNC protocol via the default browser) on an instance with optional duration.
27+
Short: "Connect to the console of an instance",
28+
Long: `Enable and access the console (through the default browser) on an instance with optional duration.
2929
Duration follows Go's duration format (e.g. "30m", "1h", "24h")`,
3030
Run: func(cmd *cobra.Command, args []string) {
3131
utility.EnsureCurrentRegion()
3232

33-
// Create the API client
3433
client, err := config.CivoAPIClient()
3534
if err != nil {
3635
utility.Error("Failed to connect to Civo's API: %s", err)
3736
os.Exit(1)
3837
}
3938

40-
// Set the region if specified by the user
4139
if common.RegionSet != "" {
4240
client.Region = common.RegionSet
4341
}
4442

45-
// Locate the instance
4643
instance, err := client.FindInstance(args[0])
4744
if err != nil {
4845
utility.Error("Unable to find instance with ID/Name '%s': %s", args[0], err)
4946
os.Exit(1)
5047
}
5148

52-
// Enable VNC for the instance with optional duration
5349
var vnc civogo.InstanceVnc
5450
if duration != "" {
5551
vnc, err = client.GetInstanceVnc(instance.ID, duration)
@@ -61,19 +57,16 @@ Duration follows Go's duration format (e.g. "30m", "1h", "24h")`,
6157
os.Exit(1)
6258
}
6359

64-
// Display VNC details
6560
utility.Info("Console access successfully enabled for instance: %s", instance.Hostname)
6661
utility.Info("Console access URL: %s", vnc.URI)
6762
utility.Info("We're preparing console access. This may take a while...")
6863

69-
// exchange apikey with a valid JWT (accessing the VNC url is allowed only via JWTs)
7064
exchangeTokenResp, err := client.ExchangeAuthToken(&civogo.ExchangeAuthTokenRequest{})
7165
if err != nil {
7266
utility.Error("Failed to exchange your apikey with a valid Civo JWT '%s': %s", instance.Hostname, err)
7367
os.Exit(1)
7468
}
7569

76-
// chain the bearer token to the URI to let it be opened via the default browser:
7770
vnc.URI = fmt.Sprintf("%s&token=%s", vnc.URI, exchangeTokenResp.AccessToken)
7871

7972
err = waitEndpointReady(vnc.URI)
@@ -85,7 +78,6 @@ Duration follows Go's duration format (e.g. "30m", "1h", "24h")`,
8578
utility.Info("Opening the console in your default browser...")
8679
time.Sleep(3 * time.Second)
8780

88-
// Open VNC in the browser
8981
err = browser.OpenInBrowser(vnc.URI)
9082
if err != nil {
9183
utility.Error("Failed to open the console access URL in the browser: %s", err)
@@ -95,8 +87,6 @@ Duration follows Go's duration format (e.g. "30m", "1h", "24h")`,
9587
},
9688
}
9789

98-
// endpointReady checks if the given URL endpoint is ready by sending a GET request
99-
// and returning true if the HTTP status code is 200 OK.
10090
func endpointReady(url string) bool {
10191
utility.Info("New attempt to reach the console URL...")
10292
resp, err := http.Get(url)
@@ -108,8 +98,6 @@ func endpointReady(url string) bool {
10898
return resp.StatusCode == http.StatusOK
10999
}
110100

111-
// waitEndpointReady continuously checks the given URL endpoint every 5 seconds
112-
// until it becomes ready (i.e., it does not return an HTTP 503 status).
113101
func waitEndpointReady(url string) error {
114102
var attempt int
115103
for {

cmd/instance/instance_vnc_status.go renamed to cmd/instance/console_status.go

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,10 @@ import (
1010
"github.com/spf13/cobra"
1111
)
1212

13-
var instanceVncStatusCmd = &cobra.Command{
14-
Use: "vnc-status <INSTANCE_ID_OR_NAME>",
15-
Aliases: []string{"vncstatus"},
16-
Short: "Get the status of the VNC console for an instance",
17-
Example: "civo instance vnc-status my-instance",
13+
var instanceConsoleStatusCmd = &cobra.Command{
14+
Use: "status",
15+
Short: "Get the status of the console for an instance",
16+
Example: "civo instance console status my-instance",
1817
Args: cobra.ExactArgs(1),
1918
Run: func(cmd *cobra.Command, args []string) {
2019
utility.EnsureCurrentRegion()
@@ -37,10 +36,10 @@ var instanceVncStatusCmd = &cobra.Command{
3736
vnc, err := client.GetInstanceVncStatus(instance.ID)
3837
if err != nil {
3938
if strings.Contains(err.Error(), "404") {
40-
utility.Info("The VNC session for instance %s (%s) does not exist or has expired.", instance.Hostname, instance.ID)
39+
utility.Info("The console session for instance %s (%s) does not exist or has expired.", instance.Hostname, instance.ID)
4140
os.Exit(0)
4241
}
43-
utility.Error("Getting VNC status for instance %s: %s", instance.ID, err)
42+
utility.Error("Getting console status for instance %s: %s", instance.ID, err)
4443
os.Exit(1)
4544
}
4645

@@ -59,3 +58,7 @@ var instanceVncStatusCmd = &cobra.Command{
5958
}
6059
},
6160
}
61+
62+
func init() {
63+
instanceConsoleCmd.AddCommand(instanceConsoleStatusCmd)
64+
}

cmd/instance/instance_vnc_stop.go renamed to cmd/instance/console_stop.go

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,10 @@ import (
1111
"github.com/spf13/cobra"
1212
)
1313

14-
var instanceVncStopCmd = &cobra.Command{
15-
Use: "vnc-stop <INSTANCE_ID_OR_NAME>",
16-
Aliases: []string{"vncstop"},
17-
Short: "Stop the VNC console session for an instance",
18-
Example: "civo instance vnc-stop my-instance",
14+
var instanceConsoleStopCmd = &cobra.Command{
15+
Use: "stop",
16+
Short: "Stop the console session for an instance",
17+
Example: "civo instance console stop my-instance",
1918
Args: cobra.ExactArgs(1),
2019
Run: func(cmd *cobra.Command, args []string) {
2120
utility.EnsureCurrentRegion()
@@ -38,10 +37,10 @@ var instanceVncStopCmd = &cobra.Command{
3837
resp, err := client.DeleteInstanceVncSession(instance.ID)
3938
if err != nil {
4039
if strings.Contains(err.Error(), "404") {
41-
utility.Info("There is no active VNC session for instance %s (%s) to stop.", instance.Hostname, instance.ID)
40+
utility.Info("There is no active console session for instance %s (%s) to stop.", instance.Hostname, instance.ID)
4241
os.Exit(0)
4342
}
44-
utility.Error("Stopping VNC session for instance %s: %s", instance.ID, err)
43+
utility.Error("Stopping console session for instance %s: %s", instance.ID, err)
4544
os.Exit(1)
4645
}
4746

@@ -53,14 +52,18 @@ var instanceVncStopCmd = &cobra.Command{
5352

5453
if common.OutputFormat == "human" {
5554
if string(resp.Result) == "ok" {
56-
fmt.Printf("VNC session for instance %s (%s) was stopped successfully.\n",
55+
fmt.Printf("Console session for instance %s (%s) was stopped successfully.\n",
5756
utility.Green(instance.Hostname), instance.ID)
5857
} else {
59-
fmt.Printf("Failed to stop VNC session for instance %s (%s). Result: %s\n",
58+
fmt.Printf("Failed to stop console session for instance %s (%s). Result: %s\n",
6059
utility.Red(instance.Hostname), instance.ID, string(resp.Result))
6160
}
6261
} else {
6362
ow.WriteSingleObjectJSON(common.PrettySet)
6463
}
6564
},
6665
}
66+
67+
func init() {
68+
instanceConsoleCmd.AddCommand(instanceConsoleStopCmd)
69+
}

cmd/instance/instance.go

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,7 @@ func init() {
3838
InstanceCmd.AddCommand(instancePublicIPCmd)
3939
InstanceCmd.AddCommand(instancePasswordCmd)
4040
InstanceCmd.AddCommand(instanceTagCmd)
41-
InstanceCmd.AddCommand(instanceVncCmd)
42-
InstanceCmd.AddCommand(instanceVncStatusCmd)
43-
InstanceCmd.AddCommand(instanceVncStopCmd)
41+
InstanceCmd.AddCommand(instanceConsoleCmd)
4442
InstanceCmd.AddCommand(instanceRecoveryCmd)
4543
InstanceCmd.AddCommand(instanceRecoveryStatusCmd)
4644
InstanceCmd.AddCommand(snapshotCmd)
@@ -71,10 +69,10 @@ func init() {
7169
instanceCreateCmd.Flags().StringArrayVar(&allowedIPs, "allowed-ips", []string{}, "A comma separated list of IP addresses that the instance is allowed to use")
7270
instanceCreateCmd.Flags().IntVar(&networkBandwidthLimit, "network-bandwidth-limit", 0, "The network bandwidth limit for the instance in Mbps (0 for unlimited)")
7371

74-
instanceVncCmd.Flags().StringVarP(&duration, "duration", "d", "", "Duration for VNC access (e.g. 30m, 1h, 24h)")
75-
7672
instanceStopCmd.Flags().BoolVarP(&waitStop, "wait", "w", false, "wait until the instance's is stoped")
7773

74+
instanceConsoleCmd.Flags().StringVarP(&duration, "duration", "", "", "The duration for the console session (e.g., '30m', '1h'). Default is provider-dependent.")
75+
7876
instanceAllowedIPsUpdateCmd.Flags().StringSliceVarP(&allowedIPsUpdate, "ips", "", []string{}, "Comma-separated list of IP addresses to allow (e.g., --ips 1.2.3.4,5.6.7.8). To clear all IPs, provide an empty string.")
7977

8078
instanceBandwidthUpdateCmd.Flags().IntVarP(&bandwidthLimitUpdate, "limit", "l", 0, "Network bandwidth limit in Mbps (e.g., 1000). Use 0 for unlimited")

0 commit comments

Comments
 (0)