summaryrefslogtreecommitdiff
path: root/plugins/jobs/oooold/service.go
blob: 4244ed1ab28fd1bedbe3dcc8b1f982f22a7a7e99 (plain)
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
package oooold

import (
	"fmt"
	//"github.com/sirupsen/logrus"
	//"github.com/spiral/roadrunner"
	//"github.com/spiral/roadrunner/service"
	//"github.com/spiral/roadrunner/service/env"
	//"github.com/spiral/roadrunner/service/rpc"
	"sync"
	"sync/atomic"
	"time"
)

// ID defines public service name.
const ID = "jobs"

// Service wraps roadrunner container and manage set of parent within it.
type Service struct {
	// Associated parent
	Brokers map[string]Broker

	// brokers and routing config
	cfg *Config

	// environment, logger and listeners
	//env env.Environment
	//log *logrus.Logger
	lsn []func(event int, ctx interface{})

	// server and server controller
	//rr *roadrunner.Server
	//cr roadrunner.Controller

	// task balancer
	execPool chan Handler

	// registered brokers
	serving int32
	//brokers service.Container

	// pipelines pipelines
	mup       sync.Mutex
	pipelines map[*Pipeline]bool
}

// Attach attaches cr. Currently only one cr is supported.
func (svc *Service) Attach(ctr roadrunner.Controller) {
	svc.cr = ctr
}

// AddListener attaches event listeners to the service and all underlying brokers.
func (svc *Service) AddListener(l func(event int, ctx interface{})) {
	svc.lsn = append(svc.lsn, l)
}

// Init configures job service.
func (svc *Service) Init(
	cfg service.Config,
	log *logrus.Logger,
	env env.Environment,
	rpc *rpc.Service,
) (ok bool, err error) {
	svc.cfg = &Config{}
	if err := svc.cfg.Hydrate(cfg); err != nil {
		return false, err
	}

	svc.env = env
	svc.log = log

	if rpc != nil {
		if err := rpc.Register(ID, &rpcServer{svc}); err != nil {
			return false, err
		}
	}

	// limit the number of parallel threads
	if svc.cfg.Workers.Command != "" {
		svc.execPool = make(chan Handler, svc.cfg.Workers.Pool.NumWorkers)
		for i := int64(0); i < svc.cfg.Workers.Pool.NumWorkers; i++ {
			svc.execPool <- svc.exec
		}

		svc.rr = roadrunner.NewServer(svc.cfg.Workers)
	}

	svc.pipelines = make(map[*Pipeline]bool)
	for _, p := range svc.cfg.pipelines {
		svc.pipelines[p] = false
	}

	// run all brokers in nested container
	svc.brokers = service.NewContainer(log)
	for name, b := range svc.Brokers {
		svc.brokers.Register(name, b)
		if ep, ok := b.(EventProvider); ok {
			ep.Listen(svc.throw)
		}
	}

	// init all broker configs
	if err := svc.brokers.Init(svc.cfg); err != nil {
		return false, err
	}

	// register all pipelines (per broker)
	for name, b := range svc.Brokers {
		for _, pipe := range svc.cfg.pipelines.Broker(name) {
			if err := b.Register(pipe); err != nil {
				return false, err
			}
		}
	}

	return true, nil
}

// Serve serves local rr server and creates broker association.
func (svc *Service) Serve() error {
	if svc.rr != nil {
		if svc.env != nil {
			if err := svc.env.Copy(svc.cfg.Workers); err != nil {
				return err
			}
		}

		// ensure that workers aware of running within jobs
		svc.cfg.Workers.SetEnv("rr_jobs", "true")
		svc.rr.Listen(svc.throw)

		if svc.cr != nil {
			svc.rr.Attach(svc.cr)
		}

		if err := svc.rr.Start(); err != nil {
			return err
		}
		defer svc.rr.Stop()

		// start pipelines of all the pipelines
		for _, p := range svc.cfg.pipelines.Names(svc.cfg.Consume...) {
			// start pipeline consuming
			if err := svc.Consume(p, svc.execPool, svc.error); err != nil {
				svc.Stop()

				return err
			}
		}
	}

	atomic.StoreInt32(&svc.serving, 1)
	defer atomic.StoreInt32(&svc.serving, 0)

	return svc.brokers.Serve()
}

// Stop all pipelines and rr server.
func (svc *Service) Stop() {
	if atomic.LoadInt32(&svc.serving) == 0 {
		return
	}

	wg := sync.WaitGroup{}
	for _, p := range svc.cfg.pipelines.Names(svc.cfg.Consume...).Reverse() {
		wg.Add(1)

		go func(p *Pipeline) {
			defer wg.Done()
			if err := svc.Consume(p, nil, nil); err != nil {
				svc.throw(EventPipeError, &PipelineError{Pipeline: p, Caused: err})
			}
		}(p)
	}

	wg.Wait()
	svc.brokers.Stop()
}

// Server returns associated rr server (if any).
func (svc *Service) Server() *roadrunner.Server {
	return svc.rr
}

// Stat returns list of pipelines workers and their stats.
func (svc *Service) Stat(pipe *Pipeline) (stat *Stat, err error) {
	b, ok := svc.Brokers[pipe.Broker()]
	if !ok {
		return nil, fmt.Errorf("undefined broker `%s`", pipe.Broker())
	}

	stat, err = b.Stat(pipe)
	if err != nil {
		return nil, err
	}

	stat.Pipeline = pipe.Name()
	stat.Broker = pipe.Broker()

	svc.mup.Lock()
	stat.Consuming = svc.pipelines[pipe]
	svc.mup.Unlock()

	return stat, err
}

// Consume enables or disables pipeline pipelines using given handlers.
func (svc *Service) Consume(pipe *Pipeline, execPool chan Handler, errHandler ErrorHandler) error {
	svc.mup.Lock()

	if execPool != nil {
		if svc.pipelines[pipe] {
			svc.mup.Unlock()
			return nil
		}

		svc.throw(EventPipeConsume, pipe)
		svc.pipelines[pipe] = true
	} else {
		if !svc.pipelines[pipe] {
			svc.mup.Unlock()
			return nil
		}

		svc.throw(EventPipeStop, pipe)
		svc.pipelines[pipe] = false
	}

	broker, ok := svc.Brokers[pipe.Broker()]
	if !ok {
		svc.mup.Unlock()
		return fmt.Errorf("undefined broker `%s`", pipe.Broker())
	}
	svc.mup.Unlock()

	if err := broker.Consume(pipe, execPool, errHandler); err != nil {
		svc.mup.Lock()
		svc.pipelines[pipe] = false
		svc.mup.Unlock()

		svc.throw(EventPipeError, &PipelineError{Pipeline: pipe, Caused: err})

		return err
	}

	if execPool != nil {
		svc.throw(EventPipeActive, pipe)
	} else {
		svc.throw(EventPipeStopped, pipe)
	}

	return nil
}

// Push job to associated broker and return job id.
func (svc *Service) Push(job *Job) (string, error) {
	pipe, pOpts, err := svc.cfg.MatchPipeline(job)
	if err != nil {
		return "", err
	}

	if pOpts != nil {
		job.Options.Merge(pOpts)
	}

	broker, ok := svc.Brokers[pipe.Broker()]
	if !ok {
		return "", fmt.Errorf("undefined broker `%s`", pipe.Broker())
	}

	id, err := broker.Push(pipe, job)

	if err != nil {
		svc.throw(EventPushError, &JobError{Job: job, Caused: err})
	} else {
		svc.throw(EventPushOK, &JobEvent{ID: id, Job: job})
	}

	return id, err
}

// exec executed job using local RR server. Make sure that service is started.
func (svc *Service) exec(id string, j *Job) error {
	start := time.Now()
	svc.throw(EventJobStart, &JobEvent{ID: id, Job: j, start: start})

	// ignore response for now, possibly add more routing options
	_, err := svc.rr.Exec(&roadrunner.Payload{
		Body:    j.Body(),
		Context: j.Context(id),
	})

	if err == nil {
		svc.throw(EventJobOK, &JobEvent{
			ID:      id,
			Job:     j,
			start:   start,
			elapsed: time.Since(start),
		})
	} else {
		svc.throw(EventJobError, &JobError{
			ID:     id,
			Job:    j,
			Caused: err, start: start,
			elapsed: time.Since(start),
		})
	}

	return err
}

// register died job, can be used to move to fallback testQueue or log
func (svc *Service) error(id string, j *Job, err error) {
	// nothing for now, possibly route to another pipeline
}

// throw handles service, server and pool events.
func (svc *Service) throw(event int, ctx interface{}) {
	for _, l := range svc.lsn {
		l(event, ctx)
	}

	if event == roadrunner.EventServerFailure {
		// underlying rr server is dead, stop everything
		svc.Stop()
	}
}