-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin_deploy.go
More file actions
1381 lines (1163 loc) · 39.2 KB
/
plugin_deploy.go
File metadata and controls
1381 lines (1163 loc) · 39.2 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 main
import (
"archive/tar"
"bytes"
"compress/gzip"
"debug/elf"
"debug/macho"
"debug/pe"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
)
// Plugin deployment commands
var pluginCmd = &cobra.Command{
Use: "plugin",
Short: "Manage plugins (create, deploy, update, list, status)",
Long: `Plugin management commands for creating, deploying, updating, and monitoring HashiCorp plugins`,
}
var pluginCreateCmd = &cobra.Command{
Use: "create",
Short: "Create a new plugin scaffold",
Long: `Create a new plugin scaffold from templates`,
Run: func(cmd *cobra.Command, args []string) {
createPluginScaffold()
},
}
var pluginDeployCmd = &cobra.Command{
Use: "deploy [plugin-directory]",
Short: "Deploy a plugin to the Apito server",
Long: `Build and deploy a plugin to the configured Apito server`,
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// Check for --dir flag first, then positional argument, then default to current dir
pluginDir, _ := cmd.Flags().GetString("dir")
if pluginDir == "" && len(args) > 0 {
pluginDir = args[0]
}
if pluginDir == "" {
pluginDir = "."
}
// Get account name from flag
accountName, _ := cmd.Flags().GetString("account")
// If no account specified, show interactive selection
if accountName == "" {
accountName = selectAccountInteractively()
if accountName == "" {
return // User cancelled
}
}
forceReplace, _ := cmd.Flags().GetBool("replace")
force, _ := cmd.Flags().GetBool("force")
forceReplace = forceReplace || force
deployPlugin(pluginDir, accountName, forceReplace)
},
}
var pluginUpdateCmd = &cobra.Command{
Use: "update [plugin-directory]",
Short: "Update an existing plugin on the server",
Long: `Build and update an existing plugin on the configured Apito server`,
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// Check for --dir flag first, then positional argument, then default to current dir
pluginDir, _ := cmd.Flags().GetString("dir")
if pluginDir == "" && len(args) > 0 {
pluginDir = args[0]
}
if pluginDir == "" {
pluginDir = "."
}
// Get account name from flag
accountName, _ := cmd.Flags().GetString("account")
// If no account specified, show interactive selection
if accountName == "" {
accountName = selectAccountInteractively()
if accountName == "" {
return // User cancelled
}
}
updatePlugin(pluginDir, accountName)
},
}
var pluginListCmd = &cobra.Command{
Use: "list",
Short: "List all plugins on the server",
Long: `List all plugins and their status on the configured Apito server`,
Run: func(cmd *cobra.Command, args []string) {
// Get account name from flag
accountName, _ := cmd.Flags().GetString("account")
// If no account specified, show interactive selection
if accountName == "" {
accountName = selectAccountInteractively()
if accountName == "" {
return // User cancelled
}
}
listPlugins(accountName)
},
}
var pluginStatusCmd = &cobra.Command{
Use: "status [plugin-id]",
Short: "Get status of a specific plugin",
Long: `Get detailed status information for a specific plugin`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// Get account name from flag
accountName, _ := cmd.Flags().GetString("account")
// If no account specified, show interactive selection
if accountName == "" {
accountName = selectAccountInteractively()
if accountName == "" {
return // User cancelled
}
}
getPluginStatus(args[0], accountName)
},
}
var pluginRestartCmd = &cobra.Command{
Use: "restart [plugin-id]",
Short: "Restart a specific plugin",
Long: `Restart a specific plugin on the server`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// Get account name from flag
accountName, _ := cmd.Flags().GetString("account")
// If no account specified, show interactive selection
if accountName == "" {
accountName = selectAccountInteractively()
if accountName == "" {
return // User cancelled
}
}
restartPlugin(args[0], accountName)
},
}
var pluginStopCmd = &cobra.Command{
Use: "stop [plugin-id]",
Short: "Stop a specific plugin",
Long: `Stop a specific plugin on the server`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// Get account name from flag
accountName, _ := cmd.Flags().GetString("account")
// If no account specified, show interactive selection
if accountName == "" {
accountName = selectAccountInteractively()
if accountName == "" {
return // User cancelled
}
}
stopPlugin(args[0], accountName)
},
}
var pluginDeleteCmd = &cobra.Command{
Use: "delete [plugin-id]",
Short: "Delete a specific plugin",
Long: `Delete a specific plugin from the server`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// Get account name from flag
accountName, _ := cmd.Flags().GetString("account")
// If no account specified, show interactive selection
if accountName == "" {
accountName = selectAccountInteractively()
if accountName == "" {
return // User cancelled
}
}
deletePlugin(args[0], accountName)
},
}
// PluginConfig represents the plugin configuration structure (matches config.yml)
type PluginConfig struct {
Plugin struct {
ID string `yaml:"id"`
Language string `yaml:"language"`
Title string `yaml:"title"`
Description string `yaml:"description"`
Type string `yaml:"type"`
Version string `yaml:"version"`
Author string `yaml:"author"`
RepositoryURL string `yaml:"repository_url"`
Branch string `yaml:"branch"`
BinaryPath string `yaml:"binary_path"`
ExportedVariable string `yaml:"exported_variable"`
Enable bool `yaml:"enable"`
Debug bool `yaml:"debug"`
HandshakeConfig struct {
ProtocolVersion int `yaml:"protocol_version"`
MagicCookieKey string `yaml:"magic_cookie_key"`
MagicCookieValue string `yaml:"magic_cookie_value"`
} `yaml:"handshake_config"`
EnvVars []struct {
Key string `yaml:"key"`
Value string `yaml:"value"`
} `yaml:"env_vars"`
UIConfig *struct {
Enable bool `yaml:"enable"`
DistPath string `yaml:"dist_path"`
} `yaml:"ui_config,omitempty"`
} `yaml:"plugin"`
}
// PluginOperationResponse represents the API response structures
type PluginOperationResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
PluginID string `json:"plugin_id,omitempty"`
Status string `json:"status,omitempty"`
Error string `json:"error,omitempty"`
}
type PluginListResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
Plugins []PluginStatusInfo `json:"plugins"`
}
type PluginStatusInfo struct {
ID string `json:"id"`
Title string `json:"title"`
Version string `json:"version"`
Status string `json:"status"`
Language string `json:"language"`
Type string `json:"type"`
Enable bool `json:"enable"`
Debug bool `json:"debug"`
LastUpdated string `json:"last_updated"`
Error string `json:"error,omitempty"`
}
func init() {
// Add --dir flags to commands that accept plugin directories
pluginDeployCmd.Flags().StringP("dir", "d", "", "Plugin directory (alternative to positional argument)")
pluginUpdateCmd.Flags().StringP("dir", "d", "", "Plugin directory (alternative to positional argument)")
// Add --account flags to all plugin commands
pluginDeployCmd.Flags().StringP("account", "a", "", "Account to use for deployment")
pluginDeployCmd.Flags().Bool("replace", false, "Delete existing plugin before deployment (force replace)")
pluginDeployCmd.Flags().BoolP("force", "f", false, "Same as --replace: delete existing plugin before deployment")
pluginUpdateCmd.Flags().StringP("account", "a", "", "Account to use for update")
pluginListCmd.Flags().StringP("account", "a", "", "Account to use for listing")
pluginStatusCmd.Flags().StringP("account", "a", "", "Account to use for status check")
pluginRestartCmd.Flags().StringP("account", "a", "", "Account to use for restart")
pluginStopCmd.Flags().StringP("account", "a", "", "Account to use for stop")
pluginDeleteCmd.Flags().StringP("account", "a", "", "Account to use for deletion")
// Add plugin commands to plugin group
pluginCmd.AddCommand(pluginAddCmd)
pluginCmd.AddCommand(pluginCreateCmd)
pluginCmd.AddCommand(pluginDeployCmd)
pluginCmd.AddCommand(pluginUpdateCmd)
pluginCmd.AddCommand(pluginListCmd)
pluginCmd.AddCommand(pluginStatusCmd)
pluginCmd.AddCommand(pluginRestartCmd)
pluginCmd.AddCommand(pluginStopCmd)
pluginCmd.AddCommand(pluginDeleteCmd)
// Build commands are added in plugin_build.go
// pluginCmd is added to rootCmd in main.go
}
func createPluginScaffold() {
print_step("🔌 Create Plugin Scaffold")
// Language selection
languages := []string{"Go (recommended)", "JavaScript", "Python"}
langPrompt := promptui.Select{
Label: "Select plugin language",
Items: languages,
}
langIdx, _, err := langPrompt.Run()
if err != nil {
print_error("Language selection cancelled")
return
}
var repoURL string
switch langIdx {
case 0:
repoURL = "https://github.com/apito-io/apito-hello-world-go-plugin.git"
case 1:
repoURL = "https://github.com/apito-io/apito-hello-world-js-plugin.git"
case 2:
repoURL = "https://github.com/apito-io/apito-hello-world-python-plugin.git"
}
// Plugin name input
namePrompt := promptui.Prompt{
Label: "Plugin name (will be prefixed with 'hc-')",
Validate: validatePluginName,
}
pluginName, err := namePrompt.Run()
if err != nil {
print_error("Plugin name input cancelled")
return
}
// Add hc- prefix if not present
if !strings.HasPrefix(pluginName, "hc-") {
pluginName = "hc-" + pluginName
}
print_status(fmt.Sprintf("Creating plugin scaffold: %s", pluginName))
print_status("Cloning template from: " + repoURL)
// Clone the template repository
if err := runGitClone(repoURL, pluginName); err != nil {
print_error("Failed to clone template: " + err.Error())
return
}
// Remove .git directory to start fresh
gitDir := filepath.Join(pluginName, ".git")
if err := os.RemoveAll(gitDir); err != nil {
print_warning("Failed to remove .git directory: " + err.Error())
}
print_success(fmt.Sprintf("Plugin scaffold created successfully: %s", pluginName))
print_status("Next steps:")
print_status("1. cd " + pluginName)
print_status("2. Customize your plugin code")
print_status("3. Test locally: make build")
print_status("4. Deploy: apito plugin deploy")
}
func deployPlugin(pluginDir, accountName string, forceReplace bool) {
if !checkServerConfig(accountName) {
return
}
// Load plugin configuration
config, err := readPluginConfig(pluginDir)
if err != nil {
print_error("Failed to load plugin configuration: " + err.Error())
return
}
pluginID := config.Plugin.ID
// Ask for confirmation before deployment
extraInfo := []string{
fmt.Sprintf("Version: %s", config.Plugin.Version),
fmt.Sprintf("Language: %s", config.Plugin.Language),
fmt.Sprintf("Type: %s", config.Plugin.Type),
}
if forceReplace {
extraInfo = append(extraInfo, "Replace Mode: enabled (existing deployment will be deleted first)")
}
if !confirmSensitiveOperation("deploy", pluginID, accountName, extraInfo...) {
return
}
if forceReplace {
if err := deleteExistingPluginBeforeDeploy(pluginID, accountName); err != nil {
print_error("Failed to delete existing plugin: " + err.Error())
return
}
}
print_step("🚀 Deploying Plugin")
print_status(fmt.Sprintf("Deploying plugin: %s (version: %s)", pluginID, config.Plugin.Version))
// Note: Build plugin separately using 'apito plugin build' before deployment
print_status("Tip: Run 'apito plugin build' first to ensure your plugin is built")
// Create deployment package
packagePath, err := createDeploymentPackage(pluginDir, config)
if err != nil {
print_error("Failed to create deployment package: " + err.Error())
return
}
defer os.Remove(packagePath) // Clean up
// Deploy to server (includes platform validation)
response, err := deployToServer(packagePath, config, false, pluginDir, accountName)
if err != nil {
print_error("Failed to deploy plugin: " + err.Error())
return
}
if response.Success {
print_success(response.Message)
print_status(fmt.Sprintf("Plugin %s is now %s", pluginID, response.Status))
} else {
print_error("Deployment failed: " + response.Message)
if response.Error != "" {
print_error("Error details: " + response.Error)
}
if strings.Contains(strings.ToLower(response.Message+response.Error), "failed to load") {
print_warning("Tip: If the previous deployment is stuck, use '--replace' or '--force' to delete and redeploy.")
}
}
}
func updatePlugin(pluginDir, accountName string) {
if !checkServerConfig(accountName) {
return
}
// Load plugin configuration
config, err := readPluginConfig(pluginDir)
if err != nil {
print_error("Failed to load plugin configuration: " + err.Error())
return
}
pluginID := config.Plugin.ID
// Ask for confirmation before update
if !confirmSensitiveOperation("update", pluginID, accountName,
fmt.Sprintf("Version: %s", config.Plugin.Version),
fmt.Sprintf("Language: %s", config.Plugin.Language),
fmt.Sprintf("Type: %s", config.Plugin.Type)) {
return
}
print_step("🔄 Updating Plugin")
print_status(fmt.Sprintf("Updating plugin: %s (version: %s)", pluginID, config.Plugin.Version))
// Note: Build plugin separately using 'apito plugin build' before update
print_status("Tip: Run 'apito plugin build' first to ensure your plugin is built")
// Create deployment package
packagePath, err := createDeploymentPackage(pluginDir, config)
if err != nil {
print_error("Failed to create deployment package: " + err.Error())
return
}
defer os.Remove(packagePath)
// Deploy to server (update mode, includes platform validation)
response, err := deployToServer(packagePath, config, true, pluginDir, accountName)
if err != nil {
print_error("Failed to update plugin: " + err.Error())
return
}
if response.Success {
print_success(response.Message)
print_status(fmt.Sprintf("Plugin %s is now %s", pluginID, response.Status))
} else {
print_error("Update failed: " + response.Message)
if response.Error != "" {
print_error("Error details: " + response.Error)
}
}
}
func listPlugins(accountName string) {
if !checkServerConfig(accountName) {
return
}
account, err := getAccountConfig(accountName)
if err != nil {
print_error("Failed to get account configuration: " + err.Error())
return
}
// Display which account is being used
print_step(fmt.Sprintf("📋 Listing Plugins from Account: %s", accountName))
print_status(fmt.Sprintf("Server: %s", account.ServerURL))
print_status("")
serverURL := account.ServerURL
cloudSyncKey := account.CloudSyncKey
// Make API request
req, err := http.NewRequest("GET", serverURL+"/system/plugin", nil)
if err != nil {
print_error("Failed to create request: " + err.Error())
return
}
req.Header.Set("X-Apito-Sync-Key", cloudSyncKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
print_error("Failed to connect to server: " + err.Error())
return
}
defer resp.Body.Close()
var response PluginListResponse
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
print_error("Failed to decode response: " + err.Error())
return
}
if !response.Success {
print_error("API error: " + response.Message)
return
}
// Display results
if len(response.Plugins) == 0 {
print_status(fmt.Sprintf("No plugins found in account '%s'", accountName))
return
}
print_success(fmt.Sprintf("Found %d plugins in account '%s':", len(response.Plugins), accountName))
for _, plugin := range response.Plugins {
status := plugin.Status
if plugin.Error != "" {
status += " (error: " + plugin.Error + ")"
}
enabledStr := "disabled"
if plugin.Enable {
enabledStr = "enabled"
}
debugStr := ""
if plugin.Debug {
debugStr = " [debug]"
}
print_status(fmt.Sprintf(" 📦 %s v%s (%s) - %s - %s%s",
plugin.ID, plugin.Version, plugin.Language, status, enabledStr, debugStr))
if plugin.Title != "" {
print_status(fmt.Sprintf(" Title: %s", plugin.Title))
}
if plugin.LastUpdated != "" {
print_status(fmt.Sprintf(" Updated: %s", plugin.LastUpdated))
}
}
}
func getPluginStatus(pluginID, accountName string) {
if !checkServerConfig(accountName) {
return
}
print_step(fmt.Sprintf("🔍 Plugin Status: %s", pluginID))
account, err := getAccountConfig(accountName)
if err != nil {
print_error("Failed to get account configuration: " + err.Error())
return
}
serverURL := account.ServerURL
cloudSyncKey := account.CloudSyncKey
req, err := http.NewRequest("GET", fmt.Sprintf("%s/system/plugin/%s", serverURL, pluginID), nil)
if err != nil {
print_error("Failed to create request: " + err.Error())
return
}
req.Header.Set("X-Apito-Sync-Key", cloudSyncKey)
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
print_error("Failed to connect to server: " + err.Error())
return
}
defer resp.Body.Close()
// Check for non-200 status codes
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
print_error(fmt.Sprintf("Server returned status %d: %s", resp.StatusCode, string(body)))
return
}
// Read response body for better error handling
body, err := io.ReadAll(resp.Body)
if err != nil {
print_error("Failed to read response body: " + err.Error())
return
}
var response struct {
Success bool `json:"success"`
Message string `json:"message"`
Plugin PluginStatusInfo `json:"plugin"`
}
if err := json.Unmarshal(body, &response); err != nil {
print_error(fmt.Sprintf("Failed to decode JSON response: %s", err.Error()))
print_error(fmt.Sprintf("Server response: %s", string(body)))
return
}
if !response.Success {
print_error("API error: " + response.Message)
return
}
// Display detailed status
plugin := response.Plugin
print_success(fmt.Sprintf("Plugin Status: %s", plugin.ID))
print_status(fmt.Sprintf(" Title: %s", plugin.Title))
print_status(fmt.Sprintf(" Version: %s", plugin.Version))
print_status(fmt.Sprintf(" Language: %s", plugin.Language))
print_status(fmt.Sprintf(" Type: %s", plugin.Type))
print_status(fmt.Sprintf(" Status: %s", plugin.Status))
print_status(fmt.Sprintf(" Enabled: %v", plugin.Enable))
print_status(fmt.Sprintf(" Debug Mode: %v", plugin.Debug))
if plugin.LastUpdated != "" {
print_status(fmt.Sprintf(" Last Updated: %s", plugin.LastUpdated))
}
if plugin.Error != "" {
print_error(fmt.Sprintf(" Error: %s", plugin.Error))
}
}
func restartPlugin(pluginID, accountName string) {
controlPlugin(pluginID, "restart", accountName)
}
func stopPlugin(pluginID, accountName string) {
controlPlugin(pluginID, "stop", accountName)
}
func deletePlugin(pluginID, accountName string) {
if !checkServerConfig(accountName) {
return
}
// Ask for confirmation before deletion
if !confirmSensitiveOperation("delete", pluginID, accountName) {
return
}
print_step(fmt.Sprintf("🗑️ Deleting Plugin: %s", pluginID))
statusCode, body, err := performPluginDeleteRequest(pluginID, accountName)
if err != nil {
print_error("Failed to delete plugin: " + err.Error())
return
}
if statusCode == http.StatusNotFound {
print_warning("Plugin not found on server")
return
}
if len(body) == 0 {
print_error("Server returned empty response during deletion")
return
}
var response PluginOperationResponse
if err := json.Unmarshal(body, &response); err != nil {
print_error(fmt.Sprintf("Failed to decode response: %v", err))
print_error(fmt.Sprintf("Server response: %s", strings.TrimSpace(string(body))))
return
}
if response.Success {
print_success(response.Message)
} else {
print_error("Delete failed: " + response.Message)
if response.Error != "" {
print_error("Error details: " + response.Error)
}
}
}
// Helper functions
// confirmSensitiveOperation asks for confirmation before performing sensitive operations
func confirmSensitiveOperation(operation, pluginID, accountName string, pluginInfo ...string) bool {
cfg, err := loadCLIConfig()
if err != nil {
print_error("Failed to load configuration: " + err.Error())
return false
}
// Get account info
var account AccountConfig
var actualAccountName string
if accountName != "" {
if acc, exists := cfg.Accounts[accountName]; exists {
account = acc
actualAccountName = accountName
} else {
print_error(fmt.Sprintf("Account '%s' does not exist", accountName))
return false
}
} else {
// Use default account
if cfg.DefaultAccount != "" {
if acc, exists := cfg.Accounts[cfg.DefaultAccount]; exists {
account = acc
actualAccountName = cfg.DefaultAccount
}
}
}
// Display operation details
print_step(fmt.Sprintf("⚠️ Confirmation Required: %s", strings.Title(operation)))
print_status("")
print_status("Operation Details:")
print_status(fmt.Sprintf(" Action: %s", strings.Title(operation)))
print_status(fmt.Sprintf(" Plugin: %s", pluginID))
// Show account info
if actualAccountName != "" {
print_status(fmt.Sprintf(" Account: %s", actualAccountName))
print_status(fmt.Sprintf(" Server: %s", account.ServerURL))
} else {
print_status(" Account: (default - none set)")
}
// Show additional plugin info if provided
if len(pluginInfo) > 0 {
for _, info := range pluginInfo {
print_status(fmt.Sprintf(" %s", info))
}
}
print_status("")
print_warning("This operation cannot be undone!")
// Confirmation prompt
confirmPrompt := promptui.Prompt{
Label: fmt.Sprintf("Are you sure you want to %s plugin '%s'? (y/N)", operation, pluginID),
IsConfirm: true,
Default: "n",
}
if _, err := confirmPrompt.Run(); err != nil {
print_status("Operation cancelled")
return false
}
return true
}
func controlPlugin(pluginID, action, accountName string) {
if !checkServerConfig(accountName) {
return
}
// Ask for confirmation before control operations
if !confirmSensitiveOperation(action, pluginID, accountName) {
return
}
print_step(fmt.Sprintf("🎛️ %s Plugin: %s", strings.Title(action), pluginID))
account, err := getAccountConfig(accountName)
if err != nil {
print_error("Failed to get account configuration: " + err.Error())
return
}
serverURL := account.ServerURL
cloudSyncKey := account.CloudSyncKey
req, err := http.NewRequest("POST", fmt.Sprintf("%s/system/plugin/%s/%s", serverURL, pluginID, action), nil)
if err != nil {
print_error("Failed to create request: " + err.Error())
return
}
req.Header.Set("X-Apito-Sync-Key", cloudSyncKey)
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
print_error("Failed to connect to server: " + err.Error())
return
}
defer resp.Body.Close()
var response PluginOperationResponse
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
print_error("Failed to decode response: " + err.Error())
return
}
if response.Success {
print_success(response.Message)
} else {
print_error(fmt.Sprintf("%s failed: %s", strings.Title(action), response.Message))
if response.Error != "" {
print_error("Error details: " + response.Error)
}
}
}
func deleteExistingPluginBeforeDeploy(pluginID, accountName string) error {
print_status("🔁 Replace flag detected: deleting existing deployment before uploading new version...")
statusCode, body, err := performPluginDeleteRequest(pluginID, accountName)
if err != nil {
return err
}
if statusCode == http.StatusNotFound {
print_warning("No existing deployment found on server – continuing with deploy")
return nil
}
if statusCode != http.StatusOK {
message := extractAPIMessage(body)
if message == "" {
message = fmt.Sprintf("server returned status %d during delete", statusCode)
}
return fmt.Errorf("%s", message)
}
if len(body) == 0 {
return fmt.Errorf("empty response from server during delete")
}
var response PluginOperationResponse
if err := json.Unmarshal(body, &response); err != nil {
return fmt.Errorf("failed to decode delete response: %w", err)
}
if !response.Success {
message := response.Message
if message == "" {
message = "delete request failed"
}
return fmt.Errorf("%s", message)
}
print_success("Existing deployment removed")
return nil
}
func performPluginDeleteRequest(pluginID, accountName string) (int, []byte, error) {
account, err := getAccountConfig(accountName)
if err != nil {
return 0, nil, err
}
serverURL := account.ServerURL
cloudSyncKey := account.CloudSyncKey
req, err := http.NewRequest("DELETE", fmt.Sprintf("%s/system/plugin/%s", serverURL, pluginID), nil)
if err != nil {
return 0, nil, err
}
req.Header.Set("X-Apito-Sync-Key", cloudSyncKey)
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return resp.StatusCode, nil, err
}
return resp.StatusCode, body, nil
}
func extractAPIMessage(body []byte) string {
trimmed := strings.TrimSpace(string(body))
if trimmed == "" {
return ""
}
var payload map[string]interface{}
if err := json.Unmarshal(body, &payload); err == nil {
if msg, ok := payload["message"]; ok {
switch v := msg.(type) {
case string:
if v != "" {
return v
}
default:
if marshaled, err := json.Marshal(v); err == nil {
text := strings.TrimSpace(string(marshaled))
if text != "" && text != "null" {
return text
}
}
}
}
if errMsg, ok := payload["error"].(string); ok && errMsg != "" {
return errMsg
}
}
return trimmed
}
func checkServerConfig(accountName string) bool {
// Get account configuration
_, err := getAccountConfig(accountName)
if err != nil {
print_error("Account configuration error: " + err.Error())
return false
}
// Account config is already validated in getAccountConfig
return true
}
func validatePluginName(input string) error {
if len(input) < 3 {
return fmt.Errorf("plugin name must be at least 3 characters long")
}
if strings.Contains(input, " ") {
return fmt.Errorf("plugin name cannot contain spaces")
}
return nil
}
func runGitClone(repoURL, targetDir string) error {
// Implementation would use git clone command
// For now, return a placeholder
return fmt.Errorf("git clone not implemented - please clone manually: git clone %s %s", repoURL, targetDir)
}
// buildPlugin is now implemented in plugin_build.go
func createDeploymentPackage(pluginDir string, config *PluginConfig) (string, error) {
// Validate required files exist before creating package
configPath := filepath.Join(pluginDir, "config.yml")
binaryPath := filepath.Join(pluginDir, config.Plugin.BinaryPath)
// Check if config.yml exists
if _, err := os.Stat(configPath); os.IsNotExist(err) {
return "", fmt.Errorf("config.yml not found in plugin directory %s - this is not a valid plugin", pluginDir)
}
// Check if binary exists
if _, err := os.Stat(binaryPath); os.IsNotExist(err) {
return "", fmt.Errorf("binary file %s not found in plugin directory %s - plugin deployment requires both config.yml and binary", config.Plugin.BinaryPath, pluginDir)
}
// Create a tar.gz package with plugin files
packagePath := filepath.Join(os.TempDir(), fmt.Sprintf("%s-deploy-%d.tar.gz", config.Plugin.ID, time.Now().Unix()))
file, err := os.Create(packagePath)
if err != nil {
return "", fmt.Errorf("failed to create deployment package: %w", err)
}
defer file.Close()
gw := gzip.NewWriter(file)
defer gw.Close()
tw := tar.NewWriter(gw)
defer tw.Close()
// Add config.yml to tar
if err := addFileToTar(tw, configPath, "config.yml"); err != nil {
return "", fmt.Errorf("failed to add config.yml to deployment package: %w", err)
}
// Add binary to tar
binaryName := filepath.Base(config.Plugin.BinaryPath)
if err := addFileToTar(tw, binaryPath, binaryName); err != nil {