-
Notifications
You must be signed in to change notification settings - Fork 52
/
daemon.go
91 lines (84 loc) · 2.15 KB
/
daemon.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
// Package daemon program is installed as a system service to achieve process daemon
package daemon
import (
"context"
"errors"
)
const (
optionKeepAlive = "KeepAlive"
optionKeepAliveDefault = true
optionRunAtLoad = "RunAtLoad"
optionRunAtLoadDefault = true
optionUserService = "UserService"
optionUserServiceDefault = false
optionSessionCreate = "SessionCreate"
optionSessionCreateDefault = false
optionRunWait = "RunWait"
)
type (
// ServiceIface represents a service that can be run or controlled
ServiceIface interface {
Run() error
Start() error
Stop() error
Restart() error
Install() error
Uninstall() error
Status() string
String() string
}
Iface interface {
Start(s ServiceIface) error
Stop(s ServiceIface) error
}
SystemIface interface {
String() string
Interactive() bool
Detect() bool
New(i Iface, c *Config) (ServiceIface, error)
}
// Config provides the setup for a ServiceIface. The Name field is required.
Config struct {
Options map[string]interface{}
Name string
DisplayName string
Description string
UserName string
Executable string
WorkingDir string
RootDir string
Arguments []string
Context context.Context
}
)
var (
system SystemIface
systemRegistry []SystemIface
ErrNameFieldRequired = errors.New("config.name field is required")
ErrNoServiceSystemDetected = errors.New("no service system detected")
ErrNotAnRootUser = errors.New("need to execute with sudo permission")
ErrNotAnAdministrator = errors.New("please operate with administrator rights")
)
// New creates a new service based on a service interface and configuration
func New(i Iface, c *Config) (ServiceIface, error) {
if len(c.Name) == 0 {
return nil, ErrNameFieldRequired
}
if system == nil {
return nil, ErrNoServiceSystemDetected
}
return system.New(i, c)
}
func newSystem() SystemIface {
for _, choice := range systemRegistry {
if !choice.Detect() {
continue
}
return choice
}
return nil
}
func chooseSystem(a ...SystemIface) {
systemRegistry = a
system = newSystem()
}