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
|
package goctl
import (
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"os"
"strings"
"sync/atomic"
"time"
"gopkg.in/inconshreveable/log15.v2"
)
// How long to wait for a response before returning an error.
const timeout = 100 * time.Millisecond
var builtinHandlers []Handler
// Error returned if handler already exists.
var HandlerExists error
var (
lastid uint64
Logger log15.Logger
)
type Goctl struct {
logger log15.Logger
path string
listener net.Listener
handlers map[string]Handler
}
type Handler interface {
Name() string
Help() string
Run(*Goctl, []string) string
}
func init() {
Logger = log15.New()
Logger.SetHandler(log15.DiscardHandler())
HandlerExists = errors.New("handler exists")
}
func NewGoctl(path string) Goctl {
handlers := make(map[string]Handler)
for _, h := range builtinHandlers {
handlers[h.Name()] = h
}
return Goctl{
logger: Logger.New("id", atomic.AddUint64(&lastid, 1)),
path: path,
handlers: handlers,
}
}
func (gc *Goctl) Start() error {
gc.logger.Info("Starting command listener.")
if pid := gc.isAlreadyRunning(); pid != "" {
gc.logger.Crit("Command listener already running.", "pid", pid)
return fmt.Errorf("already running on pid %s", pid)
} else {
os.Remove(gc.path)
}
var err error
gc.listener, err = net.Listen("unix", gc.path)
if err != nil {
gc.logger.Crit("Couldn't listen on socket.", "path", gc.path, "error", err)
return err
}
go gc.acceptor()
return nil
}
func (gc *Goctl) Stop() {
gc.logger.Info("Stopping command listener.")
if gc.listener != nil {
gc.listener.Close()
os.Remove(gc.path)
}
}
func (gc *Goctl) AddHandlers(handlers ...Handler) error {
for _, h := range handlers {
if gc.handlers[h.Name()] != nil {
return HandlerExists
}
gc.handlers[h.Name()] = h
}
return nil
}
func Read(r io.Reader) ([]byte, error) {
var n uint16
if err := binary.Read(r, binary.BigEndian, &n); err != nil {
return nil, err
}
p := make([]byte, n)
if n == 0 {
// Don't attempt to read no data or EOF will be
// returned. Instead, just return an empty byte slice.
return p, nil
}
if _, err := r.Read(p[:]); err != nil {
return nil, err
}
return p, nil
}
func Write(w io.Writer, p []byte) error {
if err := binary.Write(w, binary.BigEndian, uint16(len(p))); err != nil {
return err
}
if _, err := w.Write(p); err != nil {
return err
}
return nil
}
func (gc *Goctl) acceptor() {
for {
c, err := gc.listener.Accept()
if err != nil {
gc.logger.Error("Error accepting connection.", "error", err)
return
}
go gc.reader(c)
}
}
func (gc *Goctl) reader(c io.ReadWriteCloser) error {
defer gc.logger.Info("Connection closed.")
defer c.Close()
gc.logger.Info("New connection.")
for {
buf, err := Read(c)
if err != nil {
gc.logger.Error("Error reading from connection.", "error", err)
return err
}
cmd := strings.Split(string(buf), "\u0000")
gc.logger.Debug("Got command.", "cmd", cmd)
var resp string
if h := gc.handlers[cmd[0]]; h != nil {
resp = h.Run(gc, cmd[1:])
} else {
resp = fmt.Sprintf("ERROR: unknown command: '%s'.", cmd[0])
}
gc.logger.Debug("Responding.", "resp", resp)
Write(c, []byte(resp))
}
/* NOTREACHED */
}
func (gc *Goctl) isAlreadyRunning() string {
c, err := net.Dial("unix", gc.path)
if err != nil {
return ""
}
defer c.Close()
dataChan := make(chan []byte, 1)
c.Write([]byte("pid"))
go func() {
buf := make([]byte, 1024)
n, err := c.Read(buf[:])
if err == nil {
dataChan <- buf[0:n]
}
}()
select {
case buf := <-dataChan:
return string(buf)
case <-time.After(timeout):
gc.logger.Info("Timed out checking PID of existing service.", "path", gc.path)
return ""
}
}
|