DrainNode drains a node by evicting all pods
(c *gin.Context)
| 32 | |
| 33 | // DrainNode drains a node by evicting all pods |
| 34 | func (h *NodeHandler) DrainNode(c *gin.Context) { |
| 35 | nodeName := c.Param("name") |
| 36 | ctx := c.Request.Context() |
| 37 | cs := c.MustGet("cluster").(*cluster.ClientSet) |
| 38 | // Parse the request body for drain options |
| 39 | var drainRequest struct { |
| 40 | Force bool `json:"force" binding:"required"` |
| 41 | GracePeriod int `json:"gracePeriod" binding:"min=0"` |
| 42 | DeleteLocal bool `json:"deleteLocalData"` |
| 43 | IgnoreDaemonsets bool `json:"ignoreDaemonsets"` |
| 44 | } |
| 45 | |
| 46 | if err := c.ShouldBindJSON(&drainRequest); err != nil { |
| 47 | c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()}) |
| 48 | return |
| 49 | } |
| 50 | |
| 51 | // Get the node first to ensure it exists |
| 52 | var node corev1.Node |
| 53 | if err := cs.K8sClient.Get(ctx, types.NamespacedName{Name: nodeName}, &node); err != nil { |
| 54 | if errors.IsNotFound(err) { |
| 55 | c.JSON(http.StatusNotFound, gin.H{"error": "Node not found"}) |
| 56 | return |
| 57 | } |
| 58 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) |
| 59 | return |
| 60 | } |
| 61 | |
| 62 | drainer := &drain.Helper{ |
| 63 | Ctx: ctx, |
| 64 | Client: cs.K8sClient.ClientSet, |
| 65 | Force: drainRequest.Force, |
| 66 | GracePeriodSeconds: drainRequest.GracePeriod, |
| 67 | IgnoreAllDaemonSets: drainRequest.IgnoreDaemonsets, |
| 68 | DeleteEmptyDirData: drainRequest.DeleteLocal, |
| 69 | Out: io.Discard, |
| 70 | ErrOut: io.Discard, |
| 71 | } |
| 72 | |
| 73 | if err := drain.RunCordonOrUncordon(drainer, &node, false); err != nil { |
| 74 | c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to cordon node: " + err.Error()}) |
| 75 | return |
| 76 | } |
| 77 | |
| 78 | podDeleteList, errs := drainer.GetPodsForDeletion(nodeName) |
| 79 | if len(errs) > 0 { |
| 80 | errMsg := "" |
| 81 | for i, item := range errs { |
| 82 | if i > 0 { |
| 83 | errMsg += "; " |
| 84 | } |
| 85 | errMsg += item.Error() |
| 86 | } |
| 87 | c.JSON(http.StatusConflict, gin.H{"error": errMsg}) |
| 88 | return |
| 89 | } |
| 90 | |
| 91 | if err := drainer.DeleteOrEvictPods(podDeleteList.Pods()); err != nil { |