yanghui
2021-06-28 b568d251606f82968b8103c485a0d70027c1d57e
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
package monitor
 
import (
    "basic.com/valib/logger.git"
    "bee-config/config"
    "bee-config/models"
    "bee-config/utils"
    "context"
    "os"
    "strings"
    "sync"
    "time"
)
 
func Init(ctx context.Context, wg *sync.WaitGroup) {
    wg.Add(1)
    go monitorLoop(ctx, wg)
}
 
func monitorLoop(ctx context.Context, wg *sync.WaitGroup) {
    t := time.NewTicker(time.Second * 2)
    for {
        select {
        case <-ctx.Done():
            t.Stop()
            wg.Done()
            return
        case <- t.C:
            syncStatus()
        }
    }
}
 
func syncStatus() {
    var node models.BeeNode
    arr, err := node.FindAll()
    if nil != err {
        logger.Error("syncStatus failed to read all data, err:", err)
        return
    }
 
    nodes := make([]*models.BeeNode, len(arr))
 
    for _, v := range arr {
        nodes = append(nodes, &v)
 
        id := uint8(v.Id)
        dir := config.GetNodeDir(id)
        if _, err := os.Stat(dir); os.IsNotExist(err) {
            continue
        }
 
        output, err := utils.ShellExecute(dir, "docker-compose", "ps", "-a")
        if nil != err {
            logger.Error("syncStatus failed to invoke docker-compose, err:", err)
            continue
        }
 
        containers := parseDockerCompose(output)
        if len(containers) < 2 {
            logger.Error("syncStatus no enough containers")
            continue
        }
 
        var beeStatus, clefStatus string
        for _, v := range containers {
            words := strings.Split(v, " ")
            if len(words) < 5 {
                continue
            }
 
            if strings.Contains(words[0], "bee-1") {
                beeStatus = words[3]
            }
 
            if strings.Contains(words[0], "clef-1") {
                clefStatus = words[3]
            }
        }
 
        if len(beeStatus) < 1 {
            logger.Error("syncStatus failed to find bee container")
            continue
        }
 
        if len(clefStatus) < 1 {
            logger.Error("syncStatus failed to find clefStatus container")
            continue
        }
    }
}
 
func parseDockerCompose(output string) []string {
    lines := strings.Split(output, "\n")
    for i, v := range lines {
        if strings.HasPrefix(v, "------") {
            index := i + 1
            return lines[index:]
        }
    }
 
    return []string{}
}