agent.go 2.12 KB
Newer Older
Lei Li's avatar
Lei Li committed
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
package main

import "C"
import (
	"encoding/json"
	"fmt"
	"os"
	"path"
	"path/filepath"
	"syscall"
	"time"

	"linkfog.com/public/lib/file"
	"linkfog.com/public/lib/l"
)

//export start
func start() {
	RootDir = GetCurrentDirectory()
	for {
		if file.Exists(filepath.Join(RootDir, agentFileName)) {
			go startAgent()
			break
		} else {
			err := DownloadFile(agentVersionReportFileName, agentVersionURL)
			if err != nil {
				l.Errorf("DownloadFile err: %v", err)
				time.Sleep(5 * time.Second)
				continue
			}
			content, err := os.ReadFile(path.Join(RootDir, agentVersionReportFileName))
			if err != nil {
				l.Errorf("ReadFile err: %v", err)
				time.Sleep(5 * time.Second)
				continue
			}
			data := make(map[string]string)
			err = json.Unmarshal(content, &data)
			if err != nil {
				time.Sleep(5 * time.Second)
				l.Error("unmarshal VersionReport content failed...")
				return
			}

			l.Info("look up new version proc,updating...")
			newFileURL := data["url"]
			newExecFile := fmt.Sprintf("%s-new", agentFileName)
			err = DownloadFile(newExecFile, newFileURL)
			if err != nil {
				time.Sleep(5 * time.Second)
				l.Error("download Agent failed...")
				continue
			}

			err = os.Rename(filepath.Join(RootDir, newExecFile), filepath.Join(RootDir, agentFileName))
			if err != nil {
				l.Errorf("copy Agent failed...err:%v", err)
				time.Sleep(5 * time.Second)
				continue
			}
			err = os.Chmod(filepath.Join(RootDir, agentFileName), 0755)
			if err != nil {
				l.Errorf("chmod Agent failed...err:%v", err)
				time.Sleep(5 * time.Second)
				continue
			}
			md5, err := file.GetFileMD5(filepath.Join(RootDir, agentFileName))
			if err != nil {
				l.Warnf("GetFileMD5 err: %v", err)
			}
			if md5 != data["md5"] {
				time.Sleep(5 * time.Second)
				l.Error("update new agent failed, check md5sum err!")
				continue
			}

			os.Remove(filepath.Join(RootDir, newExecFile))
			os.Remove(filepath.Join(RootDir, agentVersionReportFileName))

			go startAgent()
			break
		}
	}
	l.Info("start")
}

//export stop
func stop() {
	err := syscall.Kill(childPID, syscall.SIGTERM)
	if err != nil {
		l.Error(err)
	}
	l.Info("stop")
}

func main() {}