-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.go
More file actions
226 lines (189 loc) · 5.71 KB
/
agent.go
File metadata and controls
226 lines (189 loc) · 5.71 KB
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
package agent
import (
"cattery/agent/catteryClient"
"cattery/agent/githubListener"
"cattery/agent/runner"
"cattery/agent/tools"
"cattery/lib/agents"
"cattery/lib/messages"
"context"
"errors"
"os"
"os/signal"
"path"
"syscall"
"time"
"github.com/fsnotify/fsnotify"
log "github.com/sirupsen/logrus"
)
var RunnerFolder string
var CatteryServerUrl string
var Id string
// shutdownCause is used as context.Cause to carry the termination reason.
type shutdownCause struct {
reason messages.UnregisterReason
message string
}
func (s *shutdownCause) Error() string { return s.message }
func Start() {
var catteryAgent = NewCatteryAgent(RunnerFolder, CatteryServerUrl, Id)
catteryAgent.Start()
}
type CatteryAgent struct {
logger *log.Entry
catteryClient *catteryClient.CatteryClient
agent *agents.Agent
agentId string
runnerFolder string
listenerExecPath string
}
func NewCatteryAgent(runnerFolder string, catteryServerUrl string, agentId string) *CatteryAgent {
return &CatteryAgent{
logger: log.WithFields(log.Fields{"name": "agent", "agentId": agentId}),
catteryClient: catteryClient.NewCatteryClient(catteryServerUrl, agentId),
runnerFolder: runnerFolder,
listenerExecPath: path.Join(runnerFolder, "bin", "Runner.Listener"),
agentId: agentId,
}
}
func (a *CatteryAgent) Start() {
a.logger.Info("Starting Cattery Agent")
resp, err := a.catteryClient.RegisterAgent(a.agentId)
if err != nil {
a.logger.Errorf("Failed to register agent: %v", err)
return
}
a.agent = &resp.Agent
jitConfig := &resp.JitConfig
// Ensure the GH Actions runner distribution is present on disk before we
// try to launch Runner.Listener. No-op when the runner is pre-baked.
if err := runner.EnsureRunner(a.runnerFolder, resp.RunnerVersion); err != nil {
a.logger.Errorf("Failed to ensure runner: %v", err)
return
}
a.logger.Info("Agent registered, starting Listener")
ctx, cancel := context.WithCancelCause(context.Background())
defer cancel(nil)
a.watchSignal(ctx, cancel)
a.watchFile(ctx, cancel)
a.watchPing(ctx, cancel)
var ghListener = githubListener.NewGithubListener(a.listenerExecPath)
ghListener.Start(ctx, cancel, jitConfig)
// Block until any source triggers cancellation
<-ctx.Done()
// Determine what happened
reason, msg := a.resolveShutdownCause(ctx)
a.logger.Infof("Shutdown: reason=%d, message=%s", reason, msg)
// Kill listener if it wasn't the one that finished
if reason != messages.UnregisterReasonDone {
ghListener.Stop()
}
a.unregisterAndShutdown(reason, msg)
}
// resolveShutdownCause extracts the termination reason from the context cause.
// - shutdownCause: a watcher triggered shutdown (signal, file, ping)
// - nil cause: listener exited cleanly
// - other error: listener exited with error
func (a *CatteryAgent) resolveShutdownCause(ctx context.Context) (messages.UnregisterReason, string) {
cause := context.Cause(ctx)
var sc *shutdownCause
if errors.As(cause, &sc) {
return sc.reason, sc.message
}
// Listener finished (cancel was called with nil or a process error)
if cause == nil {
return messages.UnregisterReasonDone, "Listener finished"
}
return messages.UnregisterReasonDone, "Listener exited: " + cause.Error()
}
func (a *CatteryAgent) unregisterAndShutdown(reason messages.UnregisterReason, msg string) {
log.Infof("Stopping Cattery Agent with reason: %d, message: `%s`", reason, msg)
err := a.catteryClient.UnregisterAgent(a.agent, reason, msg)
if err != nil {
a.logger.Errorf("Failed to unregister agent: %v", err)
}
if a.agent.Shutdown {
a.logger.Debugf("Shutdown now")
tools.Shutdown()
}
}
func (a *CatteryAgent) watchSignal(ctx context.Context, cancel context.CancelCauseFunc) {
go func() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
select {
case <-ctx.Done():
return
case sig := <-sigs:
a.logger.Info("Got signal ", sig)
cancel(&shutdownCause{
reason: messages.UnregisterReasonSigTerm,
message: "Got signal " + sig.String(),
})
}
}()
}
func (a *CatteryAgent) watchFile(ctx context.Context, cancel context.CancelCauseFunc) {
const shutdownFile = "./shutdown_file"
go func() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
a.logger.Fatalf("Failed to create file watcher: %v", err)
}
defer watcher.Close()
// Create the shutdown file if it doesn't exist
f, err := os.OpenFile(shutdownFile, os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
a.logger.Fatalf("Failed to create shutdown file: %v", err)
}
f.Close()
if err := watcher.Add(shutdownFile); err != nil {
a.logger.Fatalf("Failed to watch shutdown file: %v", err)
}
select {
case <-ctx.Done():
return
case event := <-watcher.Events:
msg := "Shutdown file changed: " + event.Name
a.logger.Info(msg)
cancel(&shutdownCause{
reason: messages.UnregisterReasonPreempted,
message: msg,
})
case watchErr := <-watcher.Errors:
msg := "File watcher error: " + watchErr.Error()
a.logger.Error(msg)
cancel(&shutdownCause{
reason: messages.UnregisterReasonPreempted,
message: msg,
})
}
}()
}
func (a *CatteryAgent) watchPing(ctx context.Context, cancel context.CancelCauseFunc) {
go func() {
for {
select {
case <-ctx.Done():
return
default:
}
pingResponse, err := a.catteryClient.Ping()
if err != nil {
a.logger.Errorf("Error pinging controller: %v", err)
time.Sleep(60 * time.Second)
continue
}
if pingResponse.Terminate {
msg := "Controller requested termination: " + pingResponse.Message
a.logger.Info(msg)
cancel(&shutdownCause{
reason: messages.UnregisterReasonControllerKill,
message: msg,
})
return
}
time.Sleep(60 * time.Second)
}
}()
}