-
Notifications
You must be signed in to change notification settings - Fork 3
/
sysward-agent.go
387 lines (327 loc) · 10.2 KB
/
sysward-agent.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
package main
import (
"bytes"
"crypto/tls"
"flag"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
// "./debian"
"math/rand"
"github.com/sysward/sysward-agent/logging"
)
type Agent struct {
runner Runner
fileReader SystemFileReader
fileWriter SystemFileWriter
packageManager SystemPackageManager
api WebApi
linux string
}
func NewAgent() *Agent {
agent = Agent{
runner: SyswardRunner{},
fileReader: SyswardFileReader{},
fileWriter: SyswardFileWriter{},
api: SyswardApi{httpClient: GetHttpClient()},
}
runner = agent.runner
fileReader = agent.fileReader
fileWriter = agent.fileWriter
api = agent.api
return &agent
}
var interval *time.Duration
func (a *Agent) Startup() {
verifyRoot()
if fileReader.FileExists("/etc/apt") {
a.packageManager = DebianPackageManager{}
a.linux = "debian"
} else if fileReader.FileExists("/usr/bin/yum") {
a.packageManager = CentosPackageManager{}
a.linux = "centos"
release, err := a.fileReader.ReadFile("/etc/os-release")
if err != nil {
logging.LogMsg("Error reading /etc/os-release: " + err.Error())
}
if strings.Contains(string(release), "Amazon Linux") &&
!fileReader.FileExists("/usr/bin/dnf") {
a.packageManager = CentosPackageManager{ForceYum: true}
logging.LogMsg("Using Amazon Linux, forcing yum")
}
} else if fileReader.FileExists("/usr/bin/zypper") {
a.packageManager = ZypperPackageManager{}
a.linux = "suse"
} else if fileReader.FileExists("/usr/bin/pacman") {
a.packageManager = ArchPackageManager{}
a.linux = "arch"
}
packageManager = agent.packageManager
checkPreReqs()
logging.LogMsg("pre-reqs verified")
configSettings := NewConfig("config.json")
config = SyswardConfig{AgentConfig: configSettings}
}
var DefaultDialer = &net.Dialer{Timeout: 2 * time.Second, KeepAlive: 2 * time.Second}
func GetHttpClient() http.Client {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
Dial: DefaultDialer.Dial,
TLSHandshakeTimeout: 2 * time.Second,
}
if os.Getenv("HTTPS_PROXY") != "" {
proxyUrl, _ := url.Parse(os.Getenv("HTTPS_PROXY"))
tr.Proxy = http.ProxyURL(proxyUrl)
}
client := http.Client{Transport: tr}
return client
}
func PingApi() {
logging.LogMsg(fmt.Sprintf("pinging %s", time.Now()))
client := GetHttpClient()
data := url.Values{}
data.Set("version", fmt.Sprintf("%d", CurrentVersion()))
req, err := http.NewRequest("POST", config.agentPingUrl(), bytes.NewBufferString(data.Encode()))
if err != nil {
logging.LogMsg(fmt.Sprintf("[fatal ping]: %s", err))
return
}
req.Header.Add("X-Sysward-Uid", getSystemUID())
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
_, err = client.Do(req)
if err != nil {
logging.LogMsg(fmt.Sprintf("[fatal ping]: %s", err))
}
logging.LogMsg(fmt.Sprintf("finished pinging %s", time.Now()))
}
func UnregisterAgent() {
logging.LogMsg(fmt.Sprintf("unregister %s", time.Now()))
client := GetHttpClient()
data := url.Values{}
data.Set("version", fmt.Sprintf("%d", CurrentVersion()))
req, err := http.NewRequest("POST", config.unregisterAgentUrl(), bytes.NewBufferString(data.Encode()))
if err != nil {
logging.LogMsg(fmt.Sprintf("[fatal unregister]: %s", err))
return
}
req.Header.Add("X-Sysward-Uid", getSystemUID())
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
_, err = client.Do(req)
if err != nil {
logging.LogMsg(fmt.Sprintf("[fatal unregister]: %s", err))
}
logging.LogMsg(fmt.Sprintf("finished unregistering %s", time.Now()))
}
func (a *Agent) Run() {
var err error
CheckForUpdate()
PingApi()
logging.LogMsg("package list update - start")
packageManager.UpdatePackageLists()
logging.LogMsg("package list update - finish")
PingApi()
logging.LogMsg("checking jobs - start")
jobs := getJobs(config.Config())
runAllJobs(jobs)
logging.LogMsg("checking jobs - finish")
counts := packageManager.UpdateCounts()
operatingSystem := getOsInformation()
packages := packageManager.BuildPackageList()
sources := packageManager.GetSourcesList()
installedPackages := packageManager.BuildInstalledPackageList()
agentData := AgentData{
Packages: packages,
SystemUpdates: counts,
OperatingSystem: operatingSystem,
Sources: sources,
InstalledPackages: installedPackages,
RebootRequired: rebootRequired(),
}
if len(hostname) > 0 {
agentData.Hostname = hostname
}
if len(group) > 0 {
agentData.Group = group
}
if len(customHostname) > 0 {
agentData.CustomHostname = customHostname
}
err = api.CheckIn(agentData)
if err != nil {
logging.LogMsg(fmt.Sprintf("[fatal] %s", err))
}
logging.LogMsg("Agent finished")
}
func (a *Agent) InstallCron() {
if !fileReader.FileExists("/etc/crontab") {
if a.linux == "debian" {
out, err := runner.Run("apt-get", "install", "cron", "-y")
logging.LogMsg("+ installing cron package: " + string(out))
if err != nil {
logging.LogMsg("Error installing cron: " + err.Error())
}
} else if a.linux == "arch" {
out, err := runner.Run("pacman", "-S", "cron", "--noconfirm")
logging.LogMsg("+ installing cron package: " + string(out))
if err != nil {
logging.LogMsg("Error installing cron: " + err.Error())
}
}
if err := os.WriteFile("/etc/crontab", []byte(""), 0644); err != nil {
logging.LogMsg("Error creating crontab: " + err.Error())
}
}
cronString := "*/5 * * * * root cd /opt/sysward/bin && ./sysward >> /dev/null\n"
cronTab, _ := fileReader.ReadFile("/etc/crontab")
if strings.Contains(string(cronTab), "bin && ./sysward") {
logging.LogMsg("+ Cron already installed")
} else {
logging.LogMsg("+ CRON missing - installing")
fileWriter.AppendToFile("/etc/crontab", cronString)
logging.LogMsg("CRON installed.")
}
if fileReader.FileExists("/etc/init/sysward-agent.conf") {
logging.LogMsg("+ Removing upstart config and converting to CRON job...")
runner.Run("/sbin/stop", "sysward-agent")
runner.Run("rm", "-rf", "/etc/init/sysward-agent.conf")
logging.LogMsg("+ Upstart configs removed and service stopped.")
}
}
var (
Version string = "38"
group string
customHostname string
hostname string
displayVersion bool
unregisterAgent bool
installingAgent bool
config Config
runner Runner
fileReader SystemFileReader
fileWriter SystemFileWriter
packageManager SystemPackageManager
api WebApi
agent Agent
)
func CurrentVersion() int64 {
i, err := strconv.ParseInt(Version, 10, 64)
if err != nil {
panic(err)
}
return i
}
func CheckScriptUpdates() {
}
func CheckForUpdate() {
if os.Getenv("SKIP_UPDATES") == "true" {
return
}
CheckScriptUpdates()
version := CurrentVersion()
resp, err := http.Get("https://updates.sysward.com/version")
if err != nil {
logging.LogMsg(err.Error())
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
latestVersion, err := strconv.ParseInt(string(body), 10, 64)
if err != nil {
panic(err)
}
architecture, err := runner.Run("uname", "-m")
if err != nil {
logging.LogMsg("Error getting architecture: " + err.Error())
os.Exit(1)
}
architecture = strings.TrimSpace(architecture)
if latestVersion > version {
logging.LogMsg(fmt.Sprintf("Current Version: %d", version))
logging.LogMsg("Downloading latest version: " + string(body) + " | arch: " + architecture)
runner.Run("mv", "/opt/sysward/bin/sysward", "/opt/sysward/bin/sysward.old")
runner.Run("curl", "-o", "sysward", "https://updates.sysward.com/sysward_"+architecture)
runner.Run("mv", "sysward", "/opt/sysward/bin/")
runner.Run("chmod", "+x", "/opt/sysward/bin/sysward")
logging.LogMsg("Upgrade finished, exiting")
os.Exit(0)
} else {
logging.LogMsg("Versions match - nothing to update")
}
}
func CheckIfAgentIsRunning() {
procList, _ := runner.Run("ps", "ax")
out := strings.Split(procList, "\n")
counter := 0
for _, proc := range out {
if strings.Contains(proc, "./sysward") && !strings.Contains(proc, "cd") && !strings.Contains(proc, "sudo") {
counter++
}
}
if counter > 1 {
logging.LogMsg(fmt.Sprintf("Sysward already running, exiting. Running: %d", counter))
panic("Sysward already running, exiting.")
} else {
logging.LogMsg("Sysward is starting.")
}
}
func main() {
flag.StringVar(&group, "group", "", "join this group automatically or create it")
flag.StringVar(&customHostname, "custom-hostname", "", "set the custom hostname for this machine")
flag.StringVar(&hostname, "hostname", "", "set the hostname for this machine")
flag.BoolVar(&displayVersion, "version", false, "display current version")
flag.BoolVar(&unregisterAgent, "unregister", false, "unregister the agent at the dashboard")
flag.BoolVar(&installingAgent, "install", false, "used when initially installing agent, disables random backoff")
flag.Parse()
agent := NewAgent()
if displayVersion {
fmt.Printf("SysWard Agent v%d\n", CurrentVersion())
os.Exit(0)
}
// if we're not installing the agent, back off
if !installingAgent {
rand.Seed(time.Now().Unix())
sleepTime := rand.Intn(59) + 1
logging.LogMsg(fmt.Sprintf("Random backoff time: %d", sleepTime))
time.Sleep(time.Duration(sleepTime) * time.Second)
}
// TODO: moving this into Startup() caused panics, investigate
CheckIfAgentIsRunning()
agent.InstallCron()
agent.Startup()
if unregisterAgent {
UnregisterAgent()
os.Exit(0)
}
// set Protocol to https if getting a 301 moved
client := GetHttpClient()
apiEndpoint := fmt.Sprintf("%s://%s", config.Config().Protocol, config.Config().Host)
logging.LogMsg("Protocol: " + config.Config().Protocol)
resp, err := client.Get(apiEndpoint)
if err != nil {
logging.LogMsg("Error connecting to the API")
}
if err == nil {
if resp.TLS != nil {
logging.LogMsg("API using https, switching config protocol")
newConfig := ConfigSettings{
Host: config.Config().Host,
Protocol: "https",
Interval: config.Config().Interval,
ApiKey: config.Config().ApiKey,
}
config = SyswardConfig{AgentConfig: newConfig}
logging.LogMsg("Config protocol: " + config.Config().Protocol)
}
}
agent.Run()
}