summaryrefslogtreecommitdiff
path: root/plugins/jobs/plugin.go
blob: c3f766b97fcd1c84a6365b7b15fe62dc56f21c24 (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
package jobs

import (
	"context"
	"sync"

	endure "github.com/spiral/endure/pkg/container"
	"github.com/spiral/errors"
	"github.com/spiral/roadrunner/v2/common/jobs"
	"github.com/spiral/roadrunner/v2/pkg/events"
	"github.com/spiral/roadrunner/v2/pkg/payload"
	"github.com/spiral/roadrunner/v2/pkg/pool"
	"github.com/spiral/roadrunner/v2/pkg/priorityqueue"
	"github.com/spiral/roadrunner/v2/plugins/config"
	"github.com/spiral/roadrunner/v2/plugins/jobs/pipeline"
	"github.com/spiral/roadrunner/v2/plugins/jobs/structs"
	"github.com/spiral/roadrunner/v2/plugins/logger"
	"github.com/spiral/roadrunner/v2/plugins/server"
	"github.com/spiral/roadrunner/v2/utils"
)

const (
	// RrJobs env variable
	RrJobs     string = "rr_jobs"
	PluginName string = "jobs"
)

type Plugin struct {
	cfg *Config `mapstructure:"jobs"`
	log logger.Logger

	sync.RWMutex

	workersPool pool.Pool
	server      server.Server

	jobConstructors map[string]jobs.Constructor
	consumers       map[string]jobs.Consumer

	events events.Handler

	// priority queue implementation
	queue priorityqueue.Queue

	// parent config for broken options.
	pipelines pipeline.Pipelines
}

func (p *Plugin) Init(cfg config.Configurer, log logger.Logger, server server.Server) error {
	const op = errors.Op("jobs_plugin_init")
	if !cfg.Has(PluginName) {
		return errors.E(op, errors.Disabled)
	}

	err := cfg.UnmarshalKey(PluginName, &p.cfg)
	if err != nil {
		return errors.E(op, err)
	}

	p.cfg.InitDefaults()

	p.server = server
	p.events = events.NewEventsHandler()
	p.jobConstructors = make(map[string]jobs.Constructor)
	p.consumers = make(map[string]jobs.Consumer)

	// initial set of pipelines
	p.pipelines, err = pipeline.InitPipelines(p.cfg.Pipelines)
	if err != nil {
		return errors.E(op, err)
	}

	// initialize priority queue
	p.queue = priorityqueue.NewBinHeap()
	p.log = log

	return nil
}

func (p *Plugin) Serve() chan error {
	errCh := make(chan error, 1)
	const op = errors.Op("jobs_plugin_serve")

	for name := range p.jobConstructors {
		jb, err := p.jobConstructors[name].JobsConstruct("", p.queue)
		if err != nil {
			errCh <- err
			return errCh
		}

		p.consumers[name] = jb
	}

	// register initial pipelines
	for i := 0; i < len(p.pipelines); i++ {
		pipe := p.pipelines[i]

		if jb, ok := p.consumers[pipe.Driver()]; ok {
			err := jb.Register(pipe.Name())
			if err != nil {
				errCh <- errors.E(op, errors.Errorf("pipe register failed for the driver: %s with pipe name: %s", pipe.Driver(), pipe.Name()))
				return errCh
			}
		}
	}

	var err error
	p.workersPool, err = p.server.NewWorkerPool(context.Background(), p.cfg.Pool, map[string]string{RrJobs: "true"})
	if err != nil {
		errCh <- err
		return errCh
	}

	// start listening
	go func() {
		for i := uint8(0); i < p.cfg.NumPollers; i++ {
			go func() {
				for {
					// get data JOB from the queue
					job := p.queue.GetMax()

					exec := payload.Payload{
						Context: job.Context(),
						Body:    job.Body(),
					}

					_, err := p.workersPool.Exec(exec)
					if err != nil {
						job.Nack()
						p.log.Error("job execute", "error", err)
						continue
					}

					job.Ack()
				}
			}()
		}
	}()

	return errCh
}

func (p *Plugin) Stop() error {
	return nil
}

func (p *Plugin) Collects() []interface{} {
	return []interface{}{
		p.CollectMQBrokers,
	}
}

func (p *Plugin) CollectMQBrokers(name endure.Named, c jobs.Constructor) {
	p.jobConstructors[name.Name()] = c
}

func (p *Plugin) Available() {}

func (p *Plugin) Name() string {
	return PluginName
}

func (p *Plugin) Push(j *structs.Job) (*string, error) {
	const op = errors.Op("jobs_plugin_push")
	pipe := p.pipelines.Get(j.Options.Pipeline)

	broker, ok := p.consumers[pipe.Driver()]
	if !ok {
		return nil, errors.E(op, errors.Errorf("consumer not registered for the requested driver: %s", pipe.Driver()))
	}

	id, err := broker.Push(j)
	if err != nil {
		panic(err)
	}

	return id, nil
}

func (p *Plugin) PushBatch(j []*structs.Job) (*string, error) {
	const op = errors.Op("jobs_plugin_push")

	for i := 0; i < len(j); i++ {
		pipe := p.pipelines.Get(j[i].Options.Pipeline)

		broker, ok := p.consumers[pipe.Driver()]
		if !ok {
			return nil, errors.E(op, errors.Errorf("consumer not registered for the requested driver: %s", pipe.Driver()))
		}

		_, err := broker.Push(j[i])
		if err != nil {
			return nil, errors.E(op, err)
		}
	}

	return utils.AsStringPtr("test"), nil
}

func (p *Plugin) RPC() interface{} {
	return &rpc{
		log: p.log,
		p:   p,
	}
}