github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/pkg/checker/host_checker.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 checker 16 17 import ( 18 "fmt" 19 "net" 20 "strconv" 21 "time" 22 23 v2 "github.com/sealerio/sealer/types/api/v2" 24 25 "github.com/sealerio/sealer/utils/ssh" 26 ) 27 28 type HostChecker struct { 29 } 30 31 func (a HostChecker) Check(cluster *v2.Cluster, phase string) error { 32 var ipList []net.IP 33 for _, hosts := range cluster.Spec.Hosts { 34 ipList = append(ipList, hosts.IPS...) 35 } 36 37 if err := checkHostnameUnique(cluster, ipList); err != nil { 38 return err 39 } 40 return checkTimeSync(cluster, ipList) 41 } 42 43 func checkHostnameUnique(cluster *v2.Cluster, ipList []net.IP) error { 44 hostnameList := map[string]bool{} 45 for _, ip := range ipList { 46 s, err := ssh.GetHostSSHClient(ip, cluster) 47 if err != nil { 48 return fmt.Errorf("checker: failed to get ssh client of host(%s): %v", ip, err) 49 } 50 hostname, err := s.CmdToString(ip, nil, "hostname", "") 51 if err != nil { 52 return fmt.Errorf("checker: failed to get hostname of host(%s): %v", ip, err) 53 } 54 if hostnameList[hostname] { 55 return fmt.Errorf("checker: hostname of host(%s) cannot be repeated, please set diffent hostname", ip) 56 } 57 hostnameList[hostname] = true 58 } 59 return nil 60 } 61 62 // Check whether the node time is synchronized 63 func checkTimeSync(cluster *v2.Cluster, ipList []net.IP) error { 64 for _, ip := range ipList { 65 s, err := ssh.GetHostSSHClient(ip, cluster) 66 if err != nil { 67 return fmt.Errorf("checker: failed to get ssh client of host(%s): %v", ip, err) 68 } 69 timeStamp, err := s.CmdToString(ip, nil, "date +%s", "") 70 if err != nil { 71 return fmt.Errorf("checker: failed to get timestamp of host(%s): %v", ip, err) 72 } 73 ts, err := strconv.Atoi(timeStamp) 74 if err != nil { 75 return fmt.Errorf("checker: failed to reverse timestamp %s of host(%s): %v", timeStamp, ip, err) 76 } 77 timeDiff := time.Since(time.Unix(int64(ts), 0)).Minutes() 78 if timeDiff < -1 || timeDiff > 1 { 79 return fmt.Errorf("checker: time of host(%s) is not synchronized", ip) 80 } 81 } 82 return nil 83 }