/
service.go
232 lines (195 loc) · 5.34 KB
/
service.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
package worker
import (
"context"
"encoding/json"
"errors"
"io/ioutil"
"os"
"path/filepath"
"sync"
"github.com/govice/golinksd/pkg/chaintracker"
"github.com/govice/golinksd/pkg/config"
"github.com/govice/golinksd/pkg/golinks"
"github.com/govice/golinksd/pkg/log"
"github.com/govice/golinksd/pkg/scheduler"
"github.com/spf13/viper"
"golang.org/x/sync/errgroup"
)
type Service struct {
errorGroup errgroup.Group
WorkerConfig *Config
ctx context.Context
mu *sync.Mutex
scheduler *scheduler.Scheduler
servicer Servicer
}
type ConfigServicer interface {
ConfigService() *config.Service
}
type GolinksServicer interface {
GolinksService() *golinks.Service
}
type ChainTrackerServicer interface {
ChainTrackerService() *chaintracker.Service
}
type WorkerServicer interface {
WorkerService() *Service
}
type Servicer interface {
ConfigServicer
GolinksServicer
ChainTrackerServicer
WorkerServicer
}
func New(servicer Servicer) (*Service, error) {
s, err := scheduler.New(viper.GetInt("concurrent_task_limit"))
if err != nil {
return nil, err
}
m := &Service{
mu: &sync.Mutex{},
scheduler: s,
servicer: servicer,
}
workerConfig, err := m.loadWorkerConfig()
if err != nil {
log.Errln("failed to load worker config", err)
return nil, err
}
m.WorkerConfig = workerConfig
return m, nil
}
func (w *Service) loadWorkerConfig() (*Config, error) {
w.mu.Lock()
defer w.mu.Unlock()
log.Logln("loading worker config...")
workerConfigPath := filepath.Join(w.servicer.ConfigService().HomeDir(), "workers.json")
_, err := os.Stat(workerConfigPath)
if os.IsNotExist(err) {
log.Logln("no worker configuration defined, initializing with empty config")
return &Config{}, nil
}
configBytes, err := ioutil.ReadFile(workerConfigPath)
if err != nil {
return nil, err
}
workerConfig := &Config{}
if err := json.Unmarshal(configBytes, workerConfig); err != nil {
return nil, err
}
// reinitialize with initialized worker
configOut := &Config{}
for _, worker := range workerConfig.Workers {
w, err := NewWorker(w.servicer, worker.RootPath, worker.GenerationPeriod, worker.IgnorePaths)
if err != nil {
log.Errln("failed to create new worker", err)
return nil, err
}
configOut.Workers = append(configOut.Workers, w)
}
return configOut, nil
}
func (w *Service) saveWorkerConfig() error {
log.Logln("saving worker config...")
workerConfigPath := filepath.Join(w.servicer.ConfigService().HomeDir(), "workers.json")
configBytes, err := json.MarshalIndent(w.WorkerConfig, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(workerConfigPath, configBytes, 0666)
}
func (w *Service) Execute(ctx context.Context) error {
w.ctx = ctx
log.Logln("starting workers...")
if err := w.startWorkers(ctx); err != nil {
return err
}
go w.scheduler.Run(w.ctx)
for {
select {
case <-ctx.Done():
log.Logln("worker manager terminating...")
for _, worker := range w.WorkerConfig.Workers {
worker.cancelFunc()
}
return nil
}
}
}
func (w *Service) startWorkers(ctx context.Context) error {
w.mu.Lock()
defer w.mu.Unlock()
for _, worker := range w.WorkerConfig.Workers {
if worker.running {
continue
}
workerCtx, workerCancelFunc := context.WithCancel(ctx)
worker.AddCancelFunc(func() {
workerCancelFunc()
worker.running = false
})
w.errorGroup.Go(func() error { return worker.Execute(workerCtx) })
worker.running = true
}
return nil
}
var ErrWorkerManagerNotStarted = errors.New("worker cannot be restarted without an existing context")
func (w *Service) startNewWorkers() error {
if w.ctx == nil {
return ErrWorkerManagerNotStarted
}
return w.startWorkers(w.ctx)
}
func (w *Service) removeWorker(index int) error {
w.mu.Lock()
defer w.mu.Unlock()
worker := w.WorkerConfig.Workers[index]
worker.cancelFunc()
w.WorkerConfig.Workers = append(w.WorkerConfig.Workers[:index], w.WorkerConfig.Workers[index+1:]...)
return w.saveWorkerConfig()
}
func (w *Service) getWorker(index int) *Worker {
w.mu.Lock()
defer w.mu.Unlock()
return w.WorkerConfig.Workers[index]
}
func (w *Service) addWorker(rootPath string, generationPeriod int, ignorePaths []string) (*Worker, error) {
w.mu.Lock()
defer w.mu.Unlock()
worker, err := NewWorker(w.servicer, rootPath, generationPeriod, ignorePaths)
if err != nil {
return nil, err
}
w.WorkerConfig.Workers = append(w.WorkerConfig.Workers, worker)
if err := w.saveWorkerConfig(); err != nil {
log.Errln("failed to save worker config after adding worker")
return nil, err
}
return worker, nil
}
func (w *Service) ScheduleWork(workerID string, task func() error) error {
t := &WorkerTask{
id: workerID,
work: task,
}
return w.scheduler.Schedule(t)
}
var ErrWorkerIndexOutOfBonds = errors.New("worker index out of bounds")
func (w *Service) GetWorkerByIndex(index int) (*Worker, error) {
if index < 0 || index > w.WorkerConfig.Length()-1 {
return nil, ErrWorkerIndexOutOfBonds
}
return w.WorkerConfig.Workers[index], nil
}
func (w *Service) DeleteWorkerByIndex(index int) error {
if index < 0 || index > w.WorkerConfig.Length()-1 {
return ErrWorkerIndexOutOfBonds
}
return w.removeWorker(index)
}
func (w *Service) AddWorker(rootPath string, generationPeriod int, ignorePaths []string) error {
if _, err := w.addWorker(rootPath, generationPeriod, ignorePaths); err != nil {
return err
}
return w.startNewWorkers()
}