~egtann/sjs

ref: 244f11278d79972028b907d640941ea0f687893c sjs/worker.go -rw-r--r-- 4.9 KiB
244f1127 — Evan Tann add isc license 7 months ago
                                                                                
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
package sjs

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"sync"
	"time"

	"github.com/pkg/errors"
)

type Worker struct {
	NotifyURL     string
	Jobs          []*Job
	APIKey        string
	lastHeartbeat time.Time
}

// WorkerMap maps job names to workers. It is thread-safe.
type WorkerMap struct {
	mu sync.RWMutex

	// data maps jobs to groups of workers performing that job
	data map[JobName]*workerGroup

	// set maps workers to NotifyURLs, ensuring we don't create duplicate
	// workers for any URL
	set map[string]*Worker
}

// Workers returns a slice of all workers active for the job server.
func (m *WorkerMap) Workers() []*Worker {
	workers := []*Worker{}
	for _, w := range m.set {
		workers = append(workers, w)
	}
	return workers
}

type workerGroup struct {
	workers []*Worker
	job     *Job
	ticker  *time.Ticker
	doneCh  chan bool

	// modIdx tracks the last index used in the worker slice. This is
	// incremented and never decremented, so use modulo to find the current
	// index.
	modIdx int
}

func NewWorkerMap() *WorkerMap {
	return &WorkerMap{
		data: map[JobName]*workerGroup{},
		set:  map[string]*Worker{},
	}
}

func (m *WorkerMap) AddWorker(
	ctx context.Context,
	lg *OptLogger,
	w *Worker,
	errCh *OptErr,
) {
	m.mu.Lock()
	w.lastHeartbeat = time.Now()
	if _, exist := m.set[w.NotifyURL]; exist {
		// We already have this worker. Nothing else to do
		m.mu.Unlock()
		return
	}
	m.set[w.NotifyURL] = w
	m.mu.Unlock()

	for _, j := range w.Jobs {
		m.mu.Lock()
		if _, exist := m.data[j.Name]; exist {
			// There's nothing else we need to do. A ticker is
			// already running.
			m.mu.Unlock()
			return
		}
		wg := newWorkerGroup(j)
		wg.workers = append(wg.workers, w)
		m.data[j.Name] = wg

		// Unlock ahead of Schedule, which acquires its own lock on a
		// timed loop
		m.mu.Unlock()
		Schedule(ctx, m, j, errCh)
		lg.Printf("added job %s (run every %d %s)", j.Name, j.RunEvery, j.RunEveryPeriod)
	}
}

// GetWorkerForJobName is not threadsafe. Guard the underlying WorkerMap with a
// lock.
func (m *WorkerMap) GetWorkerForJobName(name JobName) *Worker {
	wg, ok := m.data[name]
	if !ok || len(wg.workers) == 0 {
		return nil
	}
	wg.modIdx++
	return wg.workers[wg.modIdx%len(wg.workers)]
}

// GetOrCreateWorkerForNotifyURL does not add the worker to the WorkerMap. That
// happens when the worker is fully assembled by the calling function. This is
// threadsafe and never returns nil.
func (m *WorkerMap) GetOrCreateWorkerForNotifyURL(ul string) *Worker {
	m.mu.RLock()
	defer m.mu.RUnlock()

	worker, exist := m.set[ul]
	if exist {
		return worker
	}
	worker = &Worker{NotifyURL: ul}
	return worker
}

func (m *WorkerMap) PurgeWorkersEvery(dur time.Duration) {
	go func() {
		for t := range time.Tick(dur) {
			m.purgeWorkers(t)
		}
	}()
}

func (m *WorkerMap) purgeWorkers(t time.Time) {
	m.mu.Lock()
	defer m.mu.Unlock()

	// Find orphan candidates (jobs that may have no more workers) and a
	// new list of purged workers.
	newWorkers := []*Worker{}
	orphanCandidates := map[JobName]*Job{}
	for k := range m.set {
		worker := m.set[k]
		if worker.lastHeartbeat.Add(30 * time.Second).After(t) {
			newWorkers = append(newWorkers, worker)
			continue
		}
		for _, j := range worker.Jobs {
			orphanCandidates[j.Name] = j
		}
	}

	// Assemble our new worker groups
	set := map[string]*Worker{}
	workerData := map[JobName]*workerGroup{}
	clears := map[JobName]struct{}{}
	for _, w := range newWorkers {
		set[w.NotifyURL] = w
		for _, j := range w.Jobs {
			// We want to re-use our existing workgroup ticker and
			// done channel, but clear out workers. There are some
			// conditions in which workerGroup will be nil.
			wg := m.data[j.Name]
			if wg == nil {
				continue
			}
			if _, ok := clears[j.Name]; !ok {
				wg.workers = []*Worker{}
				clears[j.Name] = struct{}{}
			}
			wg.workers = append(wg.workers, w)
			workerData[j.Name] = wg
		}
	}

	// Halt ticking and free up resources from orphaned jobs.
	for jobName := range orphanCandidates {
		if _, exist := workerData[jobName]; !exist {
			m.data[jobName].doneCh <- true
		}
	}
	m.data = workerData
	m.set = set
}

func (w *Worker) Run(ctx context.Context, j *Job) error {
	byt, err := json.Marshal(j)
	if err != nil {
		return errors.Wrap(err, "marshal job")
	}
	req, err := http.NewRequest("POST", w.NotifyURL, bytes.NewReader(byt))
	if err != nil {
		return errors.Wrap(err, "new request")
	}
	req = req.WithContext(ctx)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-API-Key", w.APIKey)
	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return errors.Wrap(err, "post")
	}
	defer resp.Body.Close()
	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		return fmt.Errorf("worker responded %d: %s", resp.StatusCode,
			w.NotifyURL)
	}
	return nil
}

func newWorkerGroup(j *Job) *workerGroup {
	return &workerGroup{
		job:    j,
		ticker: time.NewTicker(jobDuration(j)),
		doneCh: make(chan bool),
	}
}