-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeployment_handler.go
More file actions
671 lines (587 loc) · 22.2 KB
/
deployment_handler.go
File metadata and controls
671 lines (587 loc) · 22.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
package app
import (
"errors"
"fmt"
"kubecloud/internal"
"kubecloud/internal/activities"
"kubecloud/internal/constants"
"kubecloud/internal/statemanager"
"kubecloud/kubedeployer"
"net/http"
"os"
"kubecloud/internal/logger"
"github.com/gin-gonic/gin"
"github.com/xmonader/ewf"
"gorm.io/gorm"
)
// Response represents the response structure for deployment requests
type Response struct {
WorkflowID string `json:"task_id"`
Status string `json:"status"`
Message string `json:"message"`
}
// DeploymentResponse represents the response for deployment operations
type DeploymentResponse struct {
ID int `json:"id"`
ProjectName string `json:"project_name"`
Cluster interface{} `json:"cluster"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// DeploymentListResponse represents the response for listing deployments
type DeploymentListResponse struct {
Deployments []DeploymentResponse `json:"deployments"`
Count int `json:"count"`
}
// KubeconfigResponse represents the response for kubeconfig requests
type KubeconfigResponse struct {
Kubeconfig string `json:"kubeconfig"`
}
// ClusterInput represents the simplified input structure for cluster creation
type ClusterInput struct {
Name string `json:"name" binding:"required"`
Token string `json:"token"`
Nodes []NodeInput `json:"nodes" binding:"required"`
}
// NodeInput represents the input structure for node configuration
type NodeInput struct {
Name string `json:"name" binding:"required"`
Type string `json:"type" binding:"required" enums:"worker,master,leader"`
NodeID uint32 `json:"node_id" binding:"required"`
CPU uint8 `json:"cpu" binding:"required"`
Memory uint64 `json:"memory" binding:"required"` // Memory in MB
RootSize uint64 `json:"root_size" binding:"required"` // Storage in MB
DiskSize uint64 `json:"disk_size"` // Storage in MB
EnvVars map[string]string `json:"env_vars"` // SSH_KEY, etc.
GPUIDs []string `json:"gpu_ids,omitempty"` // List of GPU IDs
Flist string `json:"flist,omitempty"`
Entrypoint string `json:"entrypoint,omitempty"`
}
// @Summary List deployments
// @Description Retrieves a list of all deployments (clusters) for the authenticated user
// @Tags deployments
// @Security BearerAuth
// @Produce json
// @Success 200 {object} DeploymentListResponse "Deployments retrieved successfully"
// @Failure 401 {object} APIResponse "Unauthorized"
// @Failure 500 {object} APIResponse "Internal server error"
// @Router /deployments [get]
func (h *Handler) HandleListDeployments(c *gin.Context) {
userID := c.GetInt("user_id")
if userID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
clusters, err := h.db.ListUserClusters(userID)
if err != nil {
logger.GetLogger().Error().Err(err).Int("user_id", userID).Msg("Failed to list user clusters")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve deployments"})
return
}
deployments := make([]gin.H, 0, len(clusters))
for _, cluster := range clusters {
clusterResult, err := cluster.GetClusterResult()
if err != nil {
logger.GetLogger().Error().Err(err).Int("cluster_id", cluster.ID).Msg("Failed to deserialize cluster result")
continue
}
deployments = append(deployments, gin.H{
"id": cluster.ID,
"project_name": cluster.ProjectName,
"cluster": clusterResult,
"created_at": cluster.CreatedAt,
"updated_at": cluster.UpdatedAt,
})
}
c.JSON(http.StatusOK, gin.H{
"deployments": deployments,
"count": len(deployments),
})
}
// @Summary List deployments (paginated)
// @Description Retrieves a paginated list of deployments for the authenticated user
// @Tags deployments
// @Security BearerAuth
// @Produce json
// @Param limit query int false "Limit"
// @Param offset query int false "Offset"
// @Success 200 {object} APIResponse{data=PaginatedData[DeploymentResponse]} "Deployments retrieved successfully"
// @Failure 401 {object} APIResponse "Unauthorized"
// @Failure 500 {object} APIResponse "Internal server error"
// @Router /deployments/paginated [get]
func (h *Handler) HandleListDeploymentsPaginated(c *gin.Context) {
userID := c.GetInt("user_id")
if userID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
limit, offset, ok := bindPagination(c)
if !ok {
return
}
clusters, total, err := h.db.ListUserClustersPaginated(userID, limit, offset)
if err != nil {
logger.GetLogger().Error().Err(err).Int("user_id", userID).Msg("Failed to list user clusters")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve deployments"})
return
}
deployments := make([]gin.H, 0, len(clusters))
for _, cluster := range clusters {
clusterResult, err := cluster.GetClusterResult()
if err != nil {
logger.GetLogger().Error().Err(err).Int("cluster_id", cluster.ID).Msg("Failed to deserialize cluster result")
continue
}
deployments = append(deployments, gin.H{
"id": cluster.ID,
"project_name": cluster.ProjectName,
"cluster": clusterResult,
"created_at": cluster.CreatedAt,
"updated_at": cluster.UpdatedAt,
})
}
Success(c, http.StatusOK, "Deployments retrieved successfully", PaginatedData[gin.H]{
Items: deployments,
Total: total,
Limit: limit,
Offset: offset,
})
}
// @Summary Get deployment
// @Description Retrieves details of a specific deployment by name
// @Tags deployments
// @Security BearerAuth
// @Produce json
// @Param name path string true "Deployment name"
// @Success 200 {object} DeploymentResponse "Deployment details retrieved successfully"
// @Failure 400 {object} APIResponse "Invalid request"
// @Failure 401 {object} APIResponse "Unauthorized"
// @Failure 404 {object} APIResponse "Deployment not found"
// @Failure 500 {object} APIResponse "Internal server error"
// @Router /deployments/{name} [get]
func (h *Handler) HandleGetDeployment(c *gin.Context) {
userID := c.GetInt("user_id")
if userID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
projectName := c.Param("name")
if projectName == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "project name is required"})
return
}
projectName = kubedeployer.GetProjectName(userID, projectName)
cluster, err := h.db.GetClusterByName(userID, projectName)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
logger.GetLogger().Error().Err(err).Int("user_id", userID).Str("project_name", projectName).Msg("Deployment not found")
c.JSON(http.StatusNotFound, gin.H{"error": "deployment not found"})
} else {
logger.GetLogger().Error().Err(err).Int("user_id", userID).Str("project_name", projectName).Msg("Database error when looking up deployment")
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to lookup deployment"})
}
return
}
clusterResult, err := cluster.GetClusterResult()
if err != nil {
logger.GetLogger().Error().Err(err).Int("cluster_id", cluster.ID).Msg("Failed to deserialize cluster result")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve deployment details"})
return
}
response := gin.H{
"id": cluster.ID,
"project_name": cluster.ProjectName,
"cluster": clusterResult,
"created_at": cluster.CreatedAt,
"updated_at": cluster.UpdatedAt,
}
c.JSON(http.StatusOK, response)
}
// @Summary Get kubeconfig
// @Description Retrieves the kubeconfig file for a specific deployment
// @Tags deployments
// @Security BearerAuth
// @Produce json
// @Param name path string true "Deployment name"
// @Success 200 {object} KubeconfigResponse "Kubeconfig retrieved successfully"
// @Failure 400 {object} APIResponse "Invalid request"
// @Failure 401 {object} APIResponse "Unauthorized"
// @Failure 404 {object} APIResponse "Deployment not found"
// @Failure 500 {object} APIResponse "Internal server error"
// @Router /deployments/{name}/kubeconfig [get]
func (h *Handler) HandleGetKubeconfig(c *gin.Context) {
userID := c.GetInt("user_id")
if userID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
projectName := c.Param("name")
if projectName == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "project name is required"})
return
}
projectName = kubedeployer.GetProjectName(userID, projectName)
cluster, err := h.db.GetClusterByName(userID, projectName)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
logger.GetLogger().Error().Err(err).Int("user_id", userID).Str("project_name", projectName).Msg("Deployment not found")
c.JSON(http.StatusNotFound, gin.H{"error": "deployment not found"})
} else {
logger.GetLogger().Error().Err(err).Int("user_id", userID).Str("project_name", projectName).Msg("Database error when looking up deployment for kubeconfig")
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to lookup deployment"})
}
return
}
if cluster.Kubeconfig != "" {
c.JSON(http.StatusOK, gin.H{"kubeconfig": cluster.Kubeconfig})
return
}
clusterResult, err := cluster.GetClusterResult()
if err != nil {
logger.GetLogger().Error().Err(err).Int("cluster_id", cluster.ID).Msg("Failed to deserialize cluster result")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve deployment details"})
return
}
var targetNode *kubedeployer.Node
for _, node := range clusterResult.Nodes {
if node.Type == kubedeployer.NodeTypeLeader {
targetNode = &node
break
}
}
if targetNode == nil {
for _, node := range clusterResult.Nodes {
if node.Type == kubedeployer.NodeTypeMaster {
targetNode = &node
break
}
}
}
if targetNode == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "No leader or master node found in deployment"})
return
}
privateKeyBytes, err := os.ReadFile(h.config.SSH.PrivateKeyPath)
if err != nil {
logger.GetLogger().Error().Err(err).Str("key_path", h.config.SSH.PrivateKeyPath).Msg("Failed to read SSH private key")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to read SSH configuration"})
return
}
kubeconfig, err := internal.GetKubeconfigViaSSH(string(privateKeyBytes), targetNode)
if err != nil {
logger.GetLogger().Error().Err(err).Str("node_name", targetNode.Name).Msg("Failed to retrieve kubeconfig via SSH")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve kubeconfig: " + err.Error()})
return
}
cluster.Kubeconfig = kubeconfig
if err := h.db.UpdateCluster(&cluster); err != nil {
logger.GetLogger().Error().Err(err).Int("cluster_id", cluster.ID).Msg("Failed to save kubeconfig to database")
}
c.JSON(http.StatusOK, gin.H{"kubeconfig": kubeconfig})
}
func (h *Handler) getClientConfig(c *gin.Context) (statemanager.ClientConfig, error) {
userID := c.GetInt("user_id")
if userID == 0 {
return statemanager.ClientConfig{}, fmt.Errorf("user_id not found in context")
}
user, err := h.db.GetUserByID(userID)
if err != nil {
return statemanager.ClientConfig{}, fmt.Errorf("failed to get user: %v", err)
}
return statemanager.ClientConfig{
SSHPublicKey: h.sshPublicKey,
Mnemonic: user.Mnemonic,
UserID: userID,
Network: h.config.SystemAccount.Network,
Debug: h.config.Debug,
}, nil
}
// @Summary Deploy cluster
// @Description Creates and deploys a new Kubernetes cluster
// @Tags deployments
// @Security BearerAuth
// @Accept json
// @Produce json
// @Param cluster body ClusterInput true "Cluster configuration"
// @Success 202 {object} Response "Deployment workflow started successfully"
// @Failure 400 {object} APIResponse "Invalid request format"
// @Failure 401 {object} APIResponse "Unauthorized"
// @Failure 500 {object} APIResponse "Internal server error"
// @Router /deployments [post]
func (h *Handler) HandleDeployCluster(c *gin.Context) {
config, err := h.getClientConfig(c)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
var cluster kubedeployer.Cluster
if err := c.ShouldBindJSON(&cluster); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request json format"})
return
}
if err := cluster.Validate(); err != nil {
Error(c, http.StatusBadRequest, "Validation failed", err.Error())
return
}
projectName := kubedeployer.GetProjectName(config.UserID, cluster.Name)
_, err = h.db.GetClusterByName(config.UserID, projectName)
if err == nil {
c.JSON(http.StatusConflict, gin.H{"error": "deployment already exists"})
return
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
logger.GetLogger().Error().Err(err).Int("user_id", config.UserID).Str("project_name", projectName).Msg("Database error when checking for existing deployment")
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to check existing deployments"})
return
}
wfName := fmt.Sprintf("deploy-%d-nodes", len(cluster.Nodes))
activities.NewDynamicDeployWorkflowTemplate(h.ewfEngine, h.metrics, h.notificationService, wfName, len(cluster.Nodes))
// Get the workflow
wf, err := h.ewfEngine.NewWorkflow(wfName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create workflow"})
return
}
wf.State = ewf.State{
"config": config,
"cluster": cluster,
}
h.ewfEngine.RunAsync(c, wf)
c.JSON(http.StatusAccepted, Response{
WorkflowID: wf.UUID,
Status: string(wf.Status),
Message: "Deployment workflow started successfully",
})
}
// @Summary Delete deployment
// @Description Deletes a specific deployment and all its resources
// @Tags deployments
// @Security BearerAuth
// @Produce json
// @Param name path string true "Deployment name"
// @Success 202 {object} Response "Deployment deletion workflow started successfully"
// @Failure 400 {object} APIResponse "Invalid request"
// @Failure 401 {object} APIResponse "Unauthorized"
// @Failure 404 {object} APIResponse "Deployment not found"
// @Failure 500 {object} APIResponse "Internal server error"
// @Router /deployments/{name} [delete]
func (h *Handler) HandleDeleteCluster(c *gin.Context) {
config, err := h.getClientConfig(c)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
deploymentName := c.Param("name")
if deploymentName == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "deployment name is required"})
return
}
projectName := kubedeployer.GetProjectName(config.UserID, deploymentName)
_, err = h.db.GetClusterByName(config.UserID, projectName)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "deployment not found"})
} else {
logger.GetLogger().Error().Err(err).Int("user_id", config.UserID).Str("project_name", projectName).Msg("Database error when looking up deployment for deletion")
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to lookup deployment"})
}
return
}
wf, err := h.ewfEngine.NewWorkflow(constants.WorkflowDeleteCluster)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create workflow"})
return
}
wf.State = ewf.State{
"config": config,
"project_name": projectName,
}
h.ewfEngine.RunAsync(c, wf)
c.JSON(http.StatusAccepted, Response{
WorkflowID: wf.UUID,
Status: string(wf.Status),
Message: "Deployment deletion workflow started successfully",
})
}
// @Summary Delete all deployments
// @Description Deletes all deployments and their resources for the authenticated user
// @Tags deployments
// @Security BearerAuth
// @Produce json
// @Success 202 {object} Response "Delete all deployments workflow started successfully"
// @Failure 401 {object} APIResponse "Unauthorized"
// @Failure 500 {object} APIResponse "Internal server error"
// @Router /deployments [delete]
func (h *Handler) HandleDeleteAllDeployments(c *gin.Context) {
config, err := h.getClientConfig(c)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
clusters, err := h.db.ListUserClusters(config.UserID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve deployments"})
return
}
if len(clusters) == 0 {
c.JSON(http.StatusOK, gin.H{"message": "No deployments found to delete"})
return
}
wf, err := h.ewfEngine.NewWorkflow(constants.WorkflowDeleteAllClusters)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create workflow"})
return
}
wf.State = ewf.State{
"config": config,
}
h.ewfEngine.RunAsync(c, wf)
c.JSON(http.StatusAccepted, Response{
WorkflowID: wf.UUID,
Status: string(wf.Status),
Message: "Delete all deployments workflow started successfully",
})
}
// @Summary Add node to deployment
// @Description Adds a new node to an existing deployment
// @Tags deployments
// @Security BearerAuth
// @Accept json
// @Produce json
// @Param cluster body ClusterInput true "Cluster configuration with new node"
// @Success 202 {object} Response "Node addition workflow started successfully"
// @Failure 400 {object} APIResponse "Invalid request format"
// @Failure 401 {object} APIResponse "Unauthorized"
// @Failure 404 {object} APIResponse "Deployment not found"
// @Failure 500 {object} APIResponse "Internal server error"
// @Router /deployments/{name}/nodes [post]
func (h *Handler) HandleAddNode(c *gin.Context) {
config, err := h.getClientConfig(c)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
var cluster kubedeployer.Cluster
if err := c.ShouldBindJSON(&cluster); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request json format"})
return
}
projectName := kubedeployer.GetProjectName(config.UserID, cluster.Name)
existingCluster, err := h.db.GetClusterByName(config.UserID, projectName)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "deployment not found"})
} else {
logger.GetLogger().Error().Err(err).Int("user_id", config.UserID).Str("project_name", projectName).Msg("Database error when looking up deployment for adding node")
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to lookup deployment"})
}
return
}
cl, err := existingCluster.GetClusterResult()
if err != nil {
logger.GetLogger().Error().Err(err).Int("cluster_id", existingCluster.ID).Msg("Failed to deserialize cluster result")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve deployment details"})
return
}
// TODO: find a better place for this
cluster.Nodes[0].OriginalName = cluster.Nodes[0].Name
for _, node := range cl.Nodes {
if node.OriginalName == cluster.Nodes[0].OriginalName {
c.JSON(http.StatusConflict, gin.H{"error": "Node with the same name already exists"})
return
}
if node.NodeID == cluster.Nodes[0].NodeID {
c.JSON(http.StatusConflict, gin.H{"error": fmt.Sprintf("node id %d is already assigned to this cluster", node.NodeID)})
return
}
}
wf, err := h.ewfEngine.NewWorkflow(constants.WorkflowAddNode)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create workflow"})
return
}
wf.State = ewf.State{
"config": config,
"cluster": cl,
"node": cluster.Nodes[0],
}
h.ewfEngine.RunAsync(c, wf)
c.JSON(http.StatusAccepted, Response{
WorkflowID: wf.UUID,
Status: string(wf.Status),
Message: "Node addition workflow started successfully",
})
}
// @Summary Remove node from deployment
// @Description Removes a specific node from an existing deployment
// @Tags deployments
// @Security BearerAuth
// @Produce json
// @Param name path string true "Deployment name"
// @Param node_name path string true "Node name to remove"
// @Success 202 {object} Response "Node removal workflow started successfully"
// @Failure 400 {object} APIResponse "Invalid request"
// @Failure 401 {object} APIResponse "Unauthorized"
// @Failure 404 {object} APIResponse "Deployment not found"
// @Failure 500 {object} APIResponse "Internal server error"
// @Router /deployments/{name}/nodes/{node_name} [delete]
func (h *Handler) HandleRemoveNode(c *gin.Context) {
config, err := h.getClientConfig(c)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
deploymentName := c.Param("name")
nodeName := c.Param("node_name")
if deploymentName == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "deployment name is required"})
return
}
if nodeName == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "node name is required"})
return
}
projectName := kubedeployer.GetProjectName(config.UserID, deploymentName)
cluster, err := h.db.GetClusterByName(config.UserID, projectName)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
logger.GetLogger().Error().Err(err).Int("user_id", config.UserID).Str("deployment_name", deploymentName).Msg("Deployment not found")
c.JSON(http.StatusNotFound, gin.H{"error": "deployment not found"})
} else {
logger.GetLogger().Error().Err(err).Int("user_id", config.UserID).Str("deployment_name", deploymentName).Msg("Database error when looking up deployment for node removal")
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to lookup deployment"})
}
return
}
cl, err := cluster.GetClusterResult()
if err != nil {
logger.GetLogger().Error().Err(err).Int("cluster_id", cluster.ID).Msg("Failed to deserialize cluster result")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve deployment details"})
return
}
nodeExists := false
for _, node := range cl.Nodes {
if node.OriginalName == nodeName {
nodeExists = true
}
}
if !nodeExists {
c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("node %q not found in cluster %q", nodeName, deploymentName)})
return
}
wf, err := h.ewfEngine.NewWorkflow(constants.WorkflowRemoveNode)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create workflow"})
return
}
wf.State = ewf.State{
"config": config,
"cluster": cl,
"node_name": nodeName,
}
h.ewfEngine.RunAsync(c, wf)
c.JSON(http.StatusAccepted, Response{
WorkflowID: wf.UUID,
Status: string(wf.Status),
Message: "Node removal workflow started successfully",
})
}