-
Notifications
You must be signed in to change notification settings - Fork 765
/
comman.go
587 lines (529 loc) · 13.2 KB
/
comman.go
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
// Copyright (C) 2014-2018 Goodrain Co., Ltd.
// RAINBOND, Application Management Platform
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. For any non-GPL usage of Rainbond,
// one or multiple Commercial Licenses authorized by Goodrain Co., Ltd.
// must be obtained first.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package util
import (
"archive/zip"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/twinj/uuid"
)
//CheckAndCreateDir check and create dir
func CheckAndCreateDir(path string) error {
if subPathExists, err := FileExists(path); err != nil {
return fmt.Errorf("Could not determine if subPath %s exists; will not attempt to change its permissions", path)
} else if !subPathExists {
// Create the sub path now because if it's auto-created later when referenced, it may have an
// incorrect ownership and mode. For example, the sub path directory must have at least g+rwx
// when the pod specifies an fsGroup, and if the directory is not created here, Docker will
// later auto-create it with the incorrect mode 0750
if err := os.MkdirAll(path, 0755); err != nil {
return fmt.Errorf("failed to mkdir:%s", path)
}
if err := os.Chmod(path, 0755); err != nil {
return err
}
}
return nil
}
//DirIsEmpty 验证目录是否为空
func DirIsEmpty(dir string) bool {
infos, err := ioutil.ReadDir(dir)
if len(infos) == 0 || err != nil {
return true
}
return false
}
//OpenOrCreateFile open or create file
func OpenOrCreateFile(filename string) (*os.File, error) {
return os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0777)
}
//FileExists check file exist
func FileExists(filename string) (bool, error) {
if _, err := os.Stat(filename); os.IsNotExist(err) {
return false, nil
} else if err != nil {
return false, err
}
return true, nil
}
//SearchFileBody 搜索文件中是否含有指定字符串
func SearchFileBody(filename, searchStr string) bool {
body, _ := ioutil.ReadFile(filename)
return strings.Contains(string(body), searchStr)
}
//IsHaveFile 指定目录是否含有文件
//.开头文件除外
func IsHaveFile(path string) bool {
files, _ := ioutil.ReadDir(path)
for _, file := range files {
if !strings.HasPrefix(file.Name(), ".") {
return true
}
}
return false
}
//SearchFile 搜索指定目录是否有指定文件,指定搜索目录层数,-1为全目录搜索
func SearchFile(pathDir, name string, level int) bool {
if level == 0 {
return false
}
files, _ := ioutil.ReadDir(pathDir)
var dirs []os.FileInfo
for _, file := range files {
if file.IsDir() {
dirs = append(dirs, file)
continue
}
if file.Name() == name {
return true
}
}
if level == 1 {
return false
}
for _, dir := range dirs {
ok := SearchFile(path.Join(pathDir, dir.Name()), name, level-1)
if ok {
return ok
}
}
return false
}
//FileExistsWithSuffix 指定目录是否含有指定后缀的文件
func FileExistsWithSuffix(pathDir, suffix string) bool {
files, _ := ioutil.ReadDir(pathDir)
for _, file := range files {
if strings.HasSuffix(file.Name(), suffix) {
return true
}
}
return false
}
//CmdRunWithTimeout exec cmd with timeout
func CmdRunWithTimeout(cmd *exec.Cmd, timeout time.Duration) (bool, error) {
done := make(chan error)
if cmd.Process != nil { //还原执行状态
cmd.Process = nil
cmd.ProcessState = nil
}
if err := cmd.Start(); err != nil {
return false, err
}
go func() {
done <- cmd.Wait()
}()
var err error
select {
case <-time.After(timeout):
// timeout
if err = cmd.Process.Kill(); err != nil {
logrus.Errorf("failed to kill: %s, error: %s", cmd.Path, err.Error())
}
go func() {
<-done // allow goroutine to exit
}()
logrus.Info("process:%s killed", cmd.Path)
return true, err
case err = <-done:
return false, err
}
}
//ReadHostID 读取当前机器ID
//ID是节点的唯一标识,acp_node将把ID与机器信息的绑定关系维护于etcd中
func ReadHostID(filePath string) (string, error) {
if filePath == "" {
filePath = "/opt/rainbond/etc/node/node_host_uuid.conf"
}
_, err := os.Stat(filePath)
if err != nil {
if strings.HasSuffix(err.Error(), "no such file or directory") {
uid := uuid.NewV4().String()
err = ioutil.WriteFile(filePath, []byte("host_uuid="+uid), 0777)
if err != nil {
logrus.Error("Write host_uuid file error.", err.Error())
}
return uid, nil
}
return "", err
}
body, err := ioutil.ReadFile(filePath)
if err != nil {
return "", err
}
info := strings.Split(strings.TrimSpace(string(body)), "=")
if len(info) == 2 {
return info[1], nil
}
return "", fmt.Errorf("Invalid host uuid from file")
}
//LocalIP 获取本机 ip
// 获取第一个非 loopback ip
func LocalIP() (net.IP, error) {
tables, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, t := range tables {
addrs, err := t.Addrs()
if err != nil {
return nil, err
}
for _, a := range addrs {
ipnet, ok := a.(*net.IPNet)
if !ok || ipnet.IP.IsLoopback() {
continue
}
if v4 := ipnet.IP.To4(); v4 != nil {
return v4, nil
}
}
}
return nil, fmt.Errorf("cannot find local IP address")
}
//GetIDFromKey 从 etcd 的 key 中取 id
func GetIDFromKey(key string) string {
index := strings.LastIndex(key, "/")
if index < 0 {
return ""
}
if strings.Contains(key, "-") { //build in任务,为了给不同node做一个区分
return strings.Split(key[index+1:], "-")[0]
}
return key[index+1:]
}
//Deweight 去除数组重复
func Deweight(data *[]string) {
var result []string
if len(*data) < 1024 {
// 切片长度小于1024的时候,循环来过滤
for i := range *data {
flag := true
for j := range result {
if result[j] == (*data)[i] {
flag = false // 存在重复元素,标识为false
break
}
}
if flag && (*data)[i] != "" { // 标识为false,不添加进结果
result = append(result, (*data)[i])
}
}
} else {
// 大于的时候,通过map来过滤
var tmp = make(map[string]byte)
for _, d := range *data {
l := len(tmp)
tmp[d] = 0
if len(tmp) != l && d != "" { // 加入map后,map长度变化,则元素不重复
result = append(result, d)
}
}
}
*data = result
}
//GetDirSizeByCmd get dir sizes by du command
//return kb
func GetDirSizeByCmd(path string) float64 {
out, err := CmdExec(fmt.Sprintf("du -sk %s", path))
if err != nil {
fmt.Println(err)
return 0
}
info := strings.Split(out, " ")
fmt.Println(info)
if len(info) < 2 {
return 0
}
i, _ := strconv.Atoi(info[0])
return float64(i)
}
//GetFileSize get file size
func GetFileSize(path string) int64 {
if fileInfo, err := os.Stat(path); err == nil {
return fileInfo.Size()
}
return 0
}
//GetDirSize kb为单位
func GetDirSize(path string) float64 {
if ok, err := FileExists(path); err != nil || !ok {
return 0
}
fileSizes := make(chan int64)
concurrent := make(chan int, 10)
var wg sync.WaitGroup
wg.Add(1)
go walkDir(path, &wg, fileSizes, concurrent)
go func() {
wg.Wait() //等待goroutine结束
close(fileSizes)
}()
var nfiles, nbytes int64
loop:
for {
select {
case size, ok := <-fileSizes:
if !ok {
break loop
}
nfiles++
nbytes += size
}
}
return float64(nbytes / 1024)
}
//获取目录dir下的文件大小
func walkDir(dir string, wg *sync.WaitGroup, fileSizes chan<- int64, concurrent chan int) {
defer wg.Done()
concurrent <- 1
defer func() {
<-concurrent
}()
for _, entry := range dirents(dir) {
if entry.IsDir() { //目录
wg.Add(1)
subDir := filepath.Join(dir, entry.Name())
go walkDir(subDir, wg, fileSizes, concurrent)
} else {
fileSizes <- entry.Size()
}
}
}
//sema is a counting semaphore for limiting concurrency in dirents
var sema = make(chan struct{}, 20)
//读取目录dir下的文件信息
func dirents(dir string) []os.FileInfo {
sema <- struct{}{}
defer func() { <-sema }()
entries, err := ioutil.ReadDir(dir)
if err != nil {
logrus.Errorf("get file sizt: %v\n", err)
return nil
}
return entries
}
//RemoveSpaces 去除空格项
func RemoveSpaces(sources []string) (re []string) {
for _, s := range sources {
if s != " " && s != "" {
re = append(re, s)
}
}
return
}
//CmdExec CmdExec
func CmdExec(args string) (string, error) {
out, err := exec.Command("bash", "-c", args).Output()
if err != nil {
return "", err
}
return string(out), nil
}
//Zip zip compressing source dir to target file
func Zip(source, target string) error {
if err := CheckAndCreateDir(filepath.Dir(target)); err != nil {
return err
}
zipfile, err := os.Create(target)
if err != nil {
return err
}
defer zipfile.Close()
archive := zip.NewWriter(zipfile)
defer archive.Close()
info, err := os.Stat(source)
if err != nil {
return nil
}
var baseDir string
if info.IsDir() {
baseDir = filepath.Base(source)
}
filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
if baseDir != "" {
header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
}
if info.IsDir() {
header.Name += "/"
} else {
header.Method = zip.Deflate
}
writer, err := archive.CreateHeader(header)
if err != nil {
return err
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
return err
})
return err
}
//Unzip archive file to target dir
func Unzip(archive, target string) error {
reader, err := zip.OpenReader(archive)
if err != nil {
return err
}
if err := os.MkdirAll(target, 0755); err != nil {
return err
}
for _, file := range reader.File {
run := func() error {
path := filepath.Join(target, file.Name)
if file.FileInfo().IsDir() {
os.MkdirAll(path, file.Mode())
return nil
}
fileReader, err := file.Open()
if err != nil {
return err
}
defer fileReader.Close()
targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
if err != nil {
return err
}
defer targetFile.Close()
if _, err := io.Copy(targetFile, fileReader); err != nil {
return err
}
return nil
}
if err := run(); err != nil {
return err
}
}
return nil
}
//GetParentDirectory GetParentDirectory
func GetParentDirectory(dirctory string) string {
return substr(dirctory, 0, strings.LastIndex(dirctory, "/"))
}
func substr(s string, pos, length int) string {
runes := []rune(s)
l := pos + length
if l > len(runes) {
l = len(runes)
}
return string(runes[pos:l])
}
//Rename move file
func Rename(old, new string) error {
_, err := os.Stat(GetParentDirectory(new))
if err != nil {
if err == os.ErrNotExist || strings.Contains(err.Error(), "no such file or directory") {
if err := os.MkdirAll(GetParentDirectory(new), 0755); err != nil {
return err
}
} else {
return err
}
}
return os.Rename(old, new)
}
//CreateVersionByTime create version number
func CreateVersionByTime() string {
now := time.Now()
re := fmt.Sprintf("%d%d%d%d%d%d%d", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second(), now.Nanosecond())
return re
}
// GetDirList get all lower level dir
func GetDirList(dirpath string, level int) ([]string, error) {
var dirlist []string
list, err := ioutil.ReadDir(dirpath)
if err != nil {
return nil, err
}
for _, f := range list {
if f.IsDir() {
if level <= 1 {
dirlist = append(dirlist, filepath.Join(dirpath, f.Name()))
} else {
list, err := GetDirList(filepath.Join(dirpath, f.Name()), level-1)
if err != nil {
return nil, err
}
dirlist = append(dirlist, list...)
}
}
}
return dirlist, nil
}
func GetFileList(dirpath string, level int) ([]string, error) {
var dirlist []string
list, err := ioutil.ReadDir(dirpath)
if err != nil {
return nil, err
}
for _, f := range list {
if !f.IsDir() && level <= 1 {
dirlist = append(dirlist, filepath.Join(dirpath, f.Name()))
} else if level > 1 && f.IsDir() {
list, err := GetFileList(filepath.Join(dirpath, f.Name()), level-1)
if err != nil {
return nil, err
}
dirlist = append(dirlist, list...)
}
}
return dirlist, nil
}
// GetDirNameList get all lower level dir
func GetDirNameList(dirpath string, level int) ([]string, error) {
var dirlist []string
list, err := ioutil.ReadDir(dirpath)
if err != nil {
return nil, err
}
for _, f := range list {
if f.IsDir() {
if level <= 1 {
dirlist = append(dirlist, f.Name())
} else {
list, err := GetDirList(filepath.Join(dirpath, f.Name()), level-1)
if err != nil {
return nil, err
}
dirlist = append(dirlist, list...)
}
}
}
return dirlist, nil
}