github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/cli/cmd/infrastructure/utils/checksum.go (about) 1 /* 2 Copyright (C) 2022-2023 ApeCloud Co., Ltd 3 4 This file is part of KubeBlocks project 5 6 This program is free software: you can redistribute it and/or modify 7 it under the terms of the GNU Affero General Public License as published by 8 the Free Software Foundation, either version 3 of the License, or 9 (at your option) any later version. 10 11 This program is distributed in the hope that it will be useful 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU Affero General Public License for more details. 15 16 You should have received a copy of the GNU Affero General Public License 17 along with this program. If not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 package utils 21 22 import ( 23 "crypto/sha256" 24 "fmt" 25 "io" 26 "os" 27 "strings" 28 29 "github.com/kubesphere/kubekey/v3/cmd/kk/pkg/core/util" 30 "github.com/kubesphere/kubekey/v3/cmd/kk/pkg/files" 31 32 cfgcore "github.com/1aal/kubeblocks/pkg/configuration/core" 33 ) 34 35 func getSha256sumFile(binary *files.KubeBinary) string { 36 return fmt.Sprintf("%s.sum.%s", binary.Path(), "sha256") 37 } 38 39 func CheckSha256sum(binary *files.KubeBinary) error { 40 checksumFile := getSha256sumFile(binary) 41 if !util.IsExist(checksumFile) { 42 return cfgcore.MakeError("checksum file %s is not exist", checksumFile) 43 } 44 45 checksum, err := calSha256sum(binary.Path()) 46 if err != nil { 47 return err 48 } 49 50 data, err := os.ReadFile(checksumFile) 51 if err != nil { 52 return err 53 } 54 if strings.TrimSpace(string(data)) == checksum { 55 return nil 56 } 57 return cfgcore.MakeError("checksum of %s is not match, [%s] vs [%s]", binary.ID, string(data), checksum) 58 } 59 60 func calSha256sum(path string) (string, error) { 61 file, err := os.Open(path) 62 if err != nil { 63 return "", err 64 } 65 defer file.Close() 66 67 data, err := io.ReadAll(file) 68 if err != nil { 69 return "", err 70 } 71 return fmt.Sprintf("%x", sha256.Sum256(data)), nil 72 } 73 74 func WriteSha256sum(binary *files.KubeBinary) error { 75 checksumFile := getSha256sumFile(binary) 76 sum, err := calSha256sum(binary.Path()) 77 if err != nil { 78 return err 79 } 80 return util.WriteFile(checksumFile, []byte(sum)) 81 }