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
|
// Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"archive/tar"
"bufio"
"compress/gzip"
"crypto/sha1"
"encoding/hex"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"github.com/pingcap/errors"
)
var (
fileLocks = make(map[string]*sync.Mutex)
filesLock = sync.Mutex{}
)
// IsSymExist check whether a symbol link is exist
func IsSymExist(path string) bool {
_, err := os.Lstat(path)
return !os.IsNotExist(err)
}
// IsExist check whether a path is exist
func IsExist(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
// IsNotExist check whether a path is not exist
func IsNotExist(path string) bool {
_, err := os.Stat(path)
return os.IsNotExist(err)
}
// IsEmptyDir check whether a path is an empty directory
func IsEmptyDir(path string) (bool, error) {
f, err := os.Open(path)
if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdirnames(1)
if err == io.EOF {
return true, nil
}
return false, err
}
// IsExecBinary check whether a path is a valid executable
func IsExecBinary(path string) bool {
info, err := os.Stat(path)
if err != nil {
return false
}
return !info.IsDir() && info.Mode()&0o111 == 0o111
}
// IsSubDir returns if sub is a sub directory of parent
func IsSubDir(parent, sub string) bool {
up := ".." + string(os.PathSeparator)
rel, err := filepath.Rel(parent, sub)
if err != nil {
return false
}
if !strings.HasPrefix(rel, up) && rel != ".." {
return true
}
return false
}
// Tar compresses the folder to tarball with gzip
func Tar(writer io.Writer, from string) error {
compressW := gzip.NewWriter(writer)
defer compressW.Close()
tarW := tar.NewWriter(compressW)
defer tarW.Close()
// NOTE: filepath.Walk does not follow the symbolic link.
return filepath.Walk(from, func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
link := ""
if info.Mode()&fs.ModeSymlink != 0 {
link, err = os.Readlink(path)
if err != nil {
return err
}
}
header, _ := tar.FileInfoHeader(info, link)
header.Name, _ = filepath.Rel(from, path)
// skip "."
if header.Name == "." {
return nil
}
err = tarW.WriteHeader(header)
if err != nil {
return err
}
if info.Mode().IsRegular() {
fd, err := os.Open(path)
if err != nil {
return err
}
defer fd.Close()
_, err = io.Copy(tarW, fd)
return err
}
return nil
})
}
// Untar decompresses the tarball
func Untar(reader io.Reader, to string) error {
gr, err := gzip.NewReader(reader)
if err != nil {
return errors.Trace(err)
}
defer gr.Close()
tr := tar.NewReader(gr)
decFile := func(hdr *tar.Header) error {
file := path.Join(to, hdr.Name)
err := MkdirAll(filepath.Dir(file), 0o755)
if err != nil {
return err
}
fw, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, hdr.FileInfo().Mode())
if err != nil {
return errors.Trace(err)
}
defer fw.Close()
_, err = io.Copy(fw, tr)
return errors.Trace(err)
}
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return errors.Trace(err)
}
switch hdr.Typeflag {
case tar.TypeDir:
if err := MkdirAll(path.Join(to, hdr.Name), hdr.FileInfo().Mode()); err != nil {
return errors.Trace(err)
}
case tar.TypeSymlink:
if err = os.Symlink(hdr.Linkname, filepath.Join(to, hdr.Name)); err != nil {
return errors.Trace(err)
}
default:
if err := decFile(hdr); err != nil {
return errors.Trace(err)
}
}
}
return nil
}
// Copy copies a file or directory from src to dst
func Copy(src, dst string) error {
fi, err := os.Stat(src)
if err != nil {
return err
}
if fi.IsDir() {
// use os.CopyFS to copy a directory
srcFS := os.DirFS(src)
return os.CopyFS(dst, srcFS)
}
// for regular files
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
if err != nil {
return err
}
err = out.Close()
if err != nil {
return err
}
err = os.Chmod(dst, fi.Mode())
if err != nil {
return err
}
// Make sure the created dst's modify time is newer (at least equal) than src
// this is used to workaround github action virtual filesystem
ofi, err := os.Stat(dst)
if err != nil {
return err
}
if fi.ModTime().After(ofi.ModTime()) {
return os.Chtimes(dst, fi.ModTime(), fi.ModTime())
}
return nil
}
// Move moves a file from src to dst, this is done by copying the file and then
// delete the old one. Use os.Rename() to rename file within the same filesystem
// instead this, it's more lightweight but can not be used across devices.
func Move(src, dst string) error {
if err := Copy(src, dst); err != nil {
return errors.Trace(err)
}
return errors.Trace(os.RemoveAll(src))
}
// Checksum returns the sha1 sum of target file
func Checksum(file string) (string, error) {
tarball, err := os.OpenFile(file, os.O_RDONLY, 0)
if err != nil {
return "", err
}
defer tarball.Close()
sha1Writter := sha1.New()
if _, err := io.Copy(sha1Writter, tarball); err != nil {
return "", err
}
checksum := hex.EncodeToString(sha1Writter.Sum(nil))
return checksum, nil
}
// TailN try get the latest n line of the file.
func TailN(fname string, n int) (lines []string, err error) {
file, err := os.Open(fname)
if err != nil {
return nil, errors.AddStack(err)
}
defer file.Close()
estimateLineSize := 1024
stat, err := os.Stat(fname)
if err != nil {
return nil, errors.AddStack(err)
}
start := max(int(stat.Size())-n*estimateLineSize, 0)
_, err = file.Seek(int64(start), 0 /*means relative to the origin of the file*/)
if err != nil {
return nil, errors.AddStack(err)
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if len(lines) > n {
lines = lines[len(lines)-n:]
}
return
}
func fileLock(path string) *sync.Mutex {
filesLock.Lock()
defer filesLock.Unlock()
if _, ok := fileLocks[path]; !ok {
fileLocks[path] = &sync.Mutex{}
}
return fileLocks[path]
}
// SaveFileWithBackup will backup the file before save it.
// e.g., backup meta.yaml as meta-2006-01-02T15:04:05Z07:00.yaml
// backup the files in the same dir of path if backupDir is empty.
func SaveFileWithBackup(path string, data []byte, backupDir string) error {
fileLock(path).Lock()
defer fileLock(path).Unlock()
info, err := os.Stat(path)
if err != nil && !os.IsNotExist(err) {
return errors.AddStack(err)
}
if info != nil && info.IsDir() {
return errors.Errorf("%s is directory", path)
}
// backup file
if !os.IsNotExist(err) {
base := filepath.Base(path)
dir := filepath.Dir(path)
var backupName string
timestr := time.Now().Format(time.RFC3339Nano)
p := strings.Split(base, ".")
if len(p) == 1 {
backupName = base + "-" + timestr
} else {
backupName = strings.Join(p[0:len(p)-1], ".") + "-" + timestr + "." + p[len(p)-1]
}
backupData, err := os.ReadFile(path)
if err != nil {
return errors.AddStack(err)
}
var backupPath string
if backupDir != "" {
backupPath = filepath.Join(backupDir, backupName)
} else {
backupPath = filepath.Join(dir, backupName)
}
err = os.WriteFile(backupPath, backupData, 0o644)
if err != nil {
return errors.AddStack(err)
}
}
err = os.WriteFile(path, data, 0o644)
if err != nil {
return errors.AddStack(err)
}
return nil
}
// MkdirAll basically copied from os.MkdirAll, but use max(parent permission,minPerm)
func MkdirAll(path string, minPerm os.FileMode) error {
// Fast path: if we can tell whether path is a directory or file, stop with success or error.
dir, err := os.Stat(path)
if err == nil {
if dir.IsDir() {
return nil
}
return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR}
}
// Slow path: make sure parent exists and then call Mkdir for path.
i := len(path)
for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator.
i--
}
j := i
for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element.
j--
}
if j > 1 {
// Create parent.
err = MkdirAll(path[:j-1], minPerm)
if err != nil {
return err
}
}
perm := minPerm
fi, err := os.Stat(filepath.Dir(path))
if err == nil {
perm |= fi.Mode().Perm()
}
// Parent now exists; invoke Mkdir and use its result; inheritance parent perm.
err = os.Mkdir(path, perm)
if err != nil {
// Handle arguments like "foo/." by
// double-checking that directory doesn't exist.
dir, err1 := os.Lstat(path)
if err1 == nil && dir.IsDir() {
return nil
}
return err
}
return nil
}
// WriteFile call os.WriteFile, but use max(parent permission,minPerm)
func WriteFile(name string, data []byte, perm os.FileMode) error {
fi, err := os.Stat(filepath.Dir(name))
if err == nil {
perm |= (fi.Mode().Perm() & 0o666)
}
return os.WriteFile(name, data, perm)
}
|