-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner.go
323 lines (246 loc) · 6.68 KB
/
runner.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
package glcm
import (
"context"
"fmt"
"io"
"math"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/achu-1612/glcm/log"
fig "github.com/common-nighthawk/go-figure"
)
// runner implements the Base interface.
type runner struct {
// swg is a wait group to wait for all the services to stop.
swg *sync.WaitGroup
// mu is a mutex to protect the runner state.
mu *sync.Mutex
// svc is a map of services registered with the runner.
svc map[string]*Wrapper
// isRunning is a flag to indicate if the runner is running or not.
isRunning bool
// ctx is the base context for the runner.
ctx context.Context
// hideBanner is a flag to indicate if the banner should be hidden or not.
hideBanner bool
// verbose represents if the logs should be suppressed or not.
verbose bool
// socket represents if the socket should be enabled or not for the runner.
socket bool
// socketPath represents the path to the socket file.
socketPath string
// allowedUIDs represents the allowed user ids to interact with the socket.
allowedUIDs []int
}
// RunnerStatus represents the status of the runner.
type RunnerStatus struct {
IsRunning bool `json:"isRunning"`
Services map[string]ServiceStatus `json:"services"`
}
// New returns a new instance of the runner.
func NewRunner(ctx context.Context, opts RunnerOptions) Runner {
r := &runner{
svc: make(map[string]*Wrapper),
mu: &sync.Mutex{},
swg: &sync.WaitGroup{},
ctx: ctx,
verbose: opts.Verbose,
hideBanner: opts.HideBanner,
socket: opts.Socket,
socketPath: opts.SocketPath,
allowedUIDs: opts.AllowedUID,
}
if !r.verbose {
log.SetOutput(io.Discard)
}
log.Infof("%v", r)
return r
}
// IsRunning returns true if the runner is running, otherwise false.
func (r *runner) IsRunning() bool {
r.mu.Lock()
defer r.mu.Unlock()
return r.isRunning
}
// RegisterService registers a service with the runner.
func (r *runner) RegisterService(svc Service, opts ServiceOptions) error {
if svc == nil {
return ErrRegisterNilService
}
if r.IsRunning() {
return ErrRunnerAlreadyRunning
}
r.mu.Lock()
defer r.mu.Unlock()
if _, ok := r.svc[svc.Name()]; ok {
return ErrRegisterServiceAlreadyExists
}
r.svc[svc.Name()] = NewWrapper(svc, r.swg, opts)
return nil
}
// BootUp boots up the runner.
func (r *runner) BootUp() error {
if r.IsRunning() {
return ErrRunnerAlreadyRunning
}
if !r.hideBanner {
fig.NewColorFigure("GLCM", "isometric1", "green", true).Print()
}
if r.ctx == nil {
log.Warn("Base Context is empty. Using the background context.")
r.ctx = context.Background()
}
log.Info("Booting up the Runner ...")
r.isRunning = true
quit := make(chan os.Signal, 1)
signal.Notify(quit,
syscall.SIGTERM, syscall.SIGINT,
syscall.SIGQUIT, syscall.SIGHUP)
// TODO: run the reconciler only if there is service state change.
if r.socket {
s, err := newSocket(r, r.socketPath, r.allowedUIDs)
if err != nil {
return fmt.Errorf("failed to create socket: %v", err)
}
// start the socket inside a go-routine, as Start is a blocking call.,
// it will be shutdown automatically when we receive the signal.
go func() {
if err := s.start(quit); err != nil {
log.Errorf("failed to start socket: %v", err)
}
}()
}
func() {
t := time.NewTicker(time.Second)
for {
select {
case <-quit:
return
case <-r.ctx.Done():
return
case <-t.C:
r.reconcile()
}
}
}()
log.Info("Received shutdown signal !!!")
r.Shutdown()
log.Info("All services stopped. Exiting ...")
return nil
}
// reconcile takes necessary actions on the services based on their state.
func (r *runner) reconcile() {
r.mu.Lock()
defer r.mu.Unlock()
for _, w := range r.svc {
// The services are expected to be in the registered state at first.
// If the service is registered, then start the service on fist rec cycle.
if w.Status == ServiceStatusRegistered {
go w.Start()
}
// skip the service if it is already pending start.
if w.AutoRestartPendingStart.Load() {
continue
}
// auto restart the service if it is exited (not stopped) and auto-restart is enabled for the service
// the service will not be started automatically if it stopped by the runner.
if w.Status == ServiceStatusExited && w.AutoRestartEnabled {
if w.AutoRestartRetryCount >= w.AutoRestartMaxRetries {
log.Infof("Service %s reached max retries. Not restarting ...", w.Name())
continue
}
backoffDuration := time.Duration(0)
if w.AutoRestartBackoff {
backoffDuration = time.Duration(
math.Pow(float64(w.AutoRestartBackoffExponent), float64(w.AutoRestartRetryCount)),
) * time.Second
}
w.AutoRestartRetryCount++
// using same flow for both immediate and backoff restarts.
w.AutoRestartPendingStart.Store(true)
go func() {
if backoffDuration > 0 {
log.Infof("Service %s backing-off. Restarting in %s ...", w.Name(), backoffDuration)
<-time.After(backoffDuration)
}
w.Start()
}()
}
}
}
// Shutdown shuts down the runner. This will stop all the registered services.
func (r *runner) Shutdown() {
r.mu.Lock()
defer r.mu.Unlock()
log.Info("Shutting down Runner...")
for _, svc := range r.svc {
if svc.Status == ServiceStatusRunning {
svc.Stop()
}
}
log.Infof("Waiting for %d service(s) to stop ...", len(r.svc))
r.swg.Wait()
r.isRunning = false
}
// StopAllServices stops all the registered/running services.
func (r *runner) StopAllServices() {
r.mu.Lock()
defer r.mu.Unlock()
for _, svc := range r.svc {
if svc.Status == ServiceStatusRunning {
svc.Stop()
}
}
r.swg.Wait()
}
// StopService stops the given list of services.
func (r *runner) StopService(name ...string) error {
r.mu.Lock()
defer r.mu.Unlock()
for _, n := range name {
if svc, ok := r.svc[n]; ok && svc.Status == ServiceStatusRunning {
svc.StopAndWait()
}
}
return nil
}
// RestartService restarts the given list of services.
func (r *runner) RestartService(name ...string) error {
r.mu.Lock()
defer r.mu.Unlock()
for _, n := range name {
if svc, ok := r.svc[n]; ok {
if svc.Status == ServiceStatusRunning {
svc.StopAndWait()
}
go svc.Start()
}
}
return nil
}
// RestartAllServices restarts all the registered/running services.
func (r *runner) RestartAllServices() {
r.mu.Lock()
defer r.mu.Unlock()
for _, svc := range r.svc {
if svc.Status == ServiceStatusRunning {
svc.StopAndWait()
}
go svc.Start()
}
}
func (r *runner) Status() *RunnerStatus {
r.mu.Lock()
defer r.mu.Unlock()
status := &RunnerStatus{
IsRunning: r.isRunning,
Services: make(map[string]ServiceStatus),
}
for _, svc := range r.svc {
status.Services[svc.Name()] = svc.Status
}
return status
}