github.com/alibaba/sealer@v0.8.6-0.20220430115802-37a2bdaa8173/apply/applydriver/utils.go (about) 1 // Copyright © 2021 Alibaba Group Holding Ltd. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package applydriver 16 17 import ( 18 "fmt" 19 20 "github.com/Masterminds/semver/v3" 21 corev1 "k8s.io/api/core/v1" 22 23 "github.com/alibaba/sealer/common" 24 "github.com/alibaba/sealer/pkg/client/k8s" 25 v2 "github.com/alibaba/sealer/types/api/v2" 26 27 "github.com/alibaba/sealer/logger" 28 "github.com/alibaba/sealer/utils" 29 ) 30 31 const MasterRoleLabel = "node-role.kubernetes.io/master" 32 33 func GetCurrentCluster(client *k8s.Client) (*v2.Cluster, error) { 34 if client == nil { 35 return nil, nil 36 } 37 nodes, err := client.ListNodes() 38 if err != nil { 39 return nil, err 40 } 41 42 cluster := &v2.Cluster{} 43 var masterIPList []string 44 var nodeIPList []string 45 46 for _, node := range nodes.Items { 47 addr := getNodeAddress(node) 48 if addr == "" { 49 continue 50 } 51 if _, ok := node.Labels[MasterRoleLabel]; ok { 52 masterIPList = append(masterIPList, addr) 53 continue 54 } 55 nodeIPList = append(nodeIPList, addr) 56 } 57 cluster.Spec.Hosts = []v2.Host{{IPS: masterIPList, Roles: []string{common.MASTER}}, {IPS: nodeIPList, Roles: []string{common.NODE}}} 58 59 return cluster, nil 60 } 61 62 func DeleteNodes(client *k8s.Client, nodeIPs []string) error { 63 logger.Info("delete nodes %s", nodeIPs) 64 nodes, err := client.ListNodes() 65 if err != nil { 66 return err 67 } 68 for _, node := range nodes.Items { 69 addr := getNodeAddress(node) 70 if addr == "" || utils.NotIn(addr, nodeIPs) { 71 continue 72 } 73 if err := client.DeleteNode(node.Name); err != nil { 74 return fmt.Errorf("failed to delete node %v", err) 75 } 76 } 77 return nil 78 } 79 80 func getNodeAddress(node corev1.Node) string { 81 if len(node.Status.Addresses) < 1 { 82 return "" 83 } 84 return node.Status.Addresses[0].Address 85 } 86 87 func VersionCompatible(version, constraint string) bool { 88 if constraint == "" { 89 return true 90 } 91 // ">= 1.19.8, <= 1.21.0" 92 c, err := semver.NewConstraint(constraint) 93 if err != nil { 94 return false 95 } 96 97 v, err := semver.NewVersion(version) 98 if err != nil { 99 return false 100 } 101 102 return c.Check(v) 103 }