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

import (
	"sync"

	"github.com/spiral/errors"
	"github.com/spiral/roadrunner/v2/pkg/state/process"
	"github.com/spiral/roadrunner/v2/plugins/config"
	"github.com/spiral/roadrunner/v2/plugins/logger"
)

const PluginName string = "service"

type Plugin struct {
	sync.Mutex

	logger logger.Logger
	cfg    Config

	// all processes attached to the service
	processes []*Process
}

func (service *Plugin) Init(cfg config.Configurer, log logger.Logger) error {
	const op = errors.Op("service_plugin_init")
	if !cfg.Has(PluginName) {
		return errors.E(errors.Disabled)
	}
	err := cfg.UnmarshalKey(PluginName, &service.cfg.Services)
	if err != nil {
		return errors.E(op, err)
	}

	// init default parameters if not set by user
	service.cfg.InitDefault()
	// save the logger
	service.logger = log

	return nil
}

func (service *Plugin) Serve() chan error {
	errCh := make(chan error, 1)

	// start processing
	go func() {
		// lock here, because Stop command might be invoked during the Serve
		service.Lock()
		defer service.Unlock()

		service.processes = make([]*Process, 0, len(service.cfg.Services))
		// for the every service
		for k := range service.cfg.Services {
			// create needed number of the processes
			for i := 0; i < service.cfg.Services[k].ProcessNum; i++ {
				// create processor structure, which will process all the services
				service.processes = append(service.processes, NewServiceProcess(
					service.cfg.Services[k].RemainAfterExit,
					service.cfg.Services[k].ExecTimeout,
					service.cfg.Services[k].RestartSec,
					service.cfg.Services[k].Command,
					service.logger,
					errCh,
				))
			}
		}

		// start all processes
		for i := 0; i < len(service.processes); i++ {
			service.processes[i].start()
		}
	}()

	return errCh
}

func (service *Plugin) Workers() []process.State {
	service.Lock()
	defer service.Unlock()
	states := make([]process.State, 0, len(service.processes))
	for i := 0; i < len(service.processes); i++ {
		st, err := process.GeneralProcessState(service.processes[i].Pid, service.processes[i].rawCmd)
		if err != nil {
			continue
		}
		states = append(states, st)
	}
	return states
}

func (service *Plugin) Stop() error {
	service.Lock()
	defer service.Unlock()

	if len(service.processes) > 0 {
		for i := 0; i < len(service.processes); i++ {
			service.processes[i].stop()
		}
	}
	return nil
}

// Name contains service name.
func (service *Plugin) Name() string {
	return PluginName
}

// Available interface implementation
func (service *Plugin) Available() {
}