/
main_agent.go
349 lines (282 loc) · 8.69 KB
/
main_agent.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
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"time"
"github.com/spf13/cobra"
"golang.org/x/sys/unix"
"github.com/lxc/lxd/lxd/instance/instancetype"
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/lxd/vsock"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/logger"
)
var servers = make(map[string]*http.Server, 2)
var errChan = make(chan error)
type cmdAgent struct {
global *cmdGlobal
}
func (c *cmdAgent) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = "lxd-agent [--debug]"
cmd.Short = "LXD virtual machine agent"
cmd.Long = `Description:
LXD virtual machine agent
This daemon is to be run inside virtual machines managed by LXD.
It will normally be started through init scripts present or injected
into the virtual machine.
`
cmd.RunE = c.Run
return cmd
}
func (c *cmdAgent) Run(cmd *cobra.Command, args []string) error {
// Setup logger.
err := logger.InitLogger("", "", c.global.flagLogVerbose, c.global.flagLogDebug, nil)
if err != nil {
os.Exit(1)
}
logger.Info("Starting")
defer logger.Info("Stopped")
// Apply the templated files.
files, err := templatesApply("files/")
if err != nil {
return err
}
// Sync the hostname.
if shared.PathExists("/proc/sys/kernel/hostname") && shared.StringInSlice("/etc/hostname", files) {
// Open the two files.
src, err := os.Open("/etc/hostname")
if err != nil {
return err
}
dst, err := os.Create("/proc/sys/kernel/hostname")
if err != nil {
return err
}
// Copy the data.
_, err = io.Copy(dst, src)
if err != nil {
return err
}
// Close the files.
_ = src.Close()
err = dst.Close()
if err != nil {
return err
}
}
// Run cloud-init.
if shared.PathExists("/etc/cloud") && shared.StringInSlice("/var/lib/cloud/seed/nocloud-net/meta-data", files) {
logger.Info("Seeding cloud-init")
cloudInitPath := "/run/cloud-init"
if shared.PathExists(cloudInitPath) {
logger.Info(fmt.Sprintf("Removing %q", cloudInitPath))
err = os.RemoveAll(cloudInitPath)
if err != nil {
return err
}
}
logger.Info("Rebooting")
_, _ = shared.RunCommand("reboot")
// Wait up to 5min for the reboot to actually happen, if it doesn't, then move on to allowing connections.
time.Sleep(300 * time.Second)
}
reconfigureNetworkInterfaces()
// Load the kernel driver.
logger.Info("Loading vsock module")
err = util.LoadModule("vsock")
if err != nil {
return fmt.Errorf("Unable to load the vsock kernel module: %w", err)
}
// Wait for vsock device to appear.
for i := 0; i < 5; i++ {
if !shared.PathExists("/dev/vsock") {
time.Sleep(1 * time.Second)
}
}
// Mount shares from host.
c.mountHostShares()
d := newDaemon(c.global.flagLogDebug, c.global.flagLogVerbose)
// Start the server.
err = startHTTPServer(d, c.global.flagLogDebug)
if err != nil {
return fmt.Errorf("Failed to start HTTP server: %w", err)
}
// Check context ID periodically, and restart the HTTP server if needed.
go func() {
for range time.Tick(30 * time.Second) {
cid, err := vsock.ContextID()
if err != nil {
continue
}
if d.localCID == cid {
continue
}
// Restart server
servers["http"].Close()
err = startHTTPServer(d, c.global.flagLogDebug)
if err != nil {
errChan <- err
}
// Update context ID.
d.localCID = cid
}
}()
// Check whether we should start the devlxd server in the early setup. This way, /dev/lxd/sock
// will be available for any systemd services starting after the lxd-agent.
if shared.PathExists("agent.conf") {
f, err := os.Open("agent.conf")
if err != nil {
return err
}
err = setConnectionInfo(d, f)
if err != nil {
_ = f.Close()
return err
}
_ = f.Close()
if d.devlxdEnabled {
err = startDevlxdServer(d)
if err != nil {
return err
}
}
}
// Create a cancellation context.
ctx, cancelFunc := context.WithCancel(context.Background())
// Start status notifier in background.
cancelStatusNotifier := c.startStatusNotifier(ctx, d.chConnected)
// Done with early setup, tell systemd to continue boot.
// Allows a service that needs a file that's generated by the agent to be able to declare After=lxd-agent
// and know the file will have been created by the time the service is started.
if os.Getenv("NOTIFY_SOCKET") != "" {
_, err := shared.RunCommand("systemd-notify", "READY=1")
if err != nil {
cancelStatusNotifier() // Ensure STOPPED status is written to QEMU status ringbuffer.
cancelFunc()
return fmt.Errorf("Failed to notify systemd of readiness: %w", err)
}
}
// Cancel context when SIGTEM is received.
chSignal := make(chan os.Signal, 1)
signal.Notify(chSignal, unix.SIGTERM)
exitStatus := 0
select {
case <-chSignal:
case err := <-errChan:
fmt.Fprintln(os.Stderr, err)
exitStatus = 1
}
cancelStatusNotifier() // Ensure STOPPED status is written to QEMU status ringbuffer.
cancelFunc()
os.Exit(exitStatus)
return nil
}
// startStatusNotifier sends status of agent to vserial ring buffer every 10s or when context is done.
// Returns a function that can be used to update the running status to STOPPED in the ring buffer.
func (c *cmdAgent) startStatusNotifier(ctx context.Context, chConnected <-chan struct{}) context.CancelFunc {
// Write initial started status.
_ = c.writeStatus("STARTED")
wg := sync.WaitGroup{}
exitCtx, exit := context.WithCancel(ctx) // Allows manual synchronous cancellation via cancel function.
cancel := func() {
exit() // Signal for the go routine to end.
wg.Wait() // Wait for the go routine to actually finish.
}
wg.Add(1)
go func() {
defer wg.Done() // Signal to cancel function that we are done.
ticker := time.NewTicker(time.Duration(time.Second) * 5)
defer ticker.Stop()
for {
select {
case <-chConnected:
_ = c.writeStatus("CONNECTED") // Indicate we were able to connect to LXD.
case <-ticker.C:
_ = c.writeStatus("STARTED") // Re-populate status periodically in case LXD restarts.
case <-exitCtx.Done():
_ = c.writeStatus("STOPPED") // Indicate we are stopping to LXD and exit go routine.
return
}
}
}()
return cancel
}
// writeStatus writes a status code to the vserial ring buffer used to detect agent status on host.
func (c *cmdAgent) writeStatus(status string) error {
if shared.PathExists("/dev/virtio-ports/org.linuxcontainers.lxd") {
vSerial, err := os.OpenFile("/dev/virtio-ports/org.linuxcontainers.lxd", os.O_RDWR, 0600)
if err != nil {
return err
}
defer vSerial.Close()
_, err = vSerial.Write([]byte(fmt.Sprintf("%s\n", status)))
if err != nil {
return err
}
}
return nil
}
// mountHostShares reads the agent-mounts.json file from config share and mounts the shares requested.
func (c *cmdAgent) mountHostShares() {
agentMountsFile := "./agent-mounts.json"
if !shared.PathExists(agentMountsFile) {
return
}
b, err := os.ReadFile(agentMountsFile)
if err != nil {
logger.Errorf("Failed to load agent mounts file %q: %v", agentMountsFile, err)
}
var agentMounts []instancetype.VMAgentMount
err = json.Unmarshal(b, &agentMounts)
if err != nil {
logger.Errorf("Failed to parse agent mounts file %q: %v", agentMountsFile, err)
return
}
for _, mount := range agentMounts {
// Convert relative mounts to absolute from / otherwise dir creation fails or mount fails.
if !strings.HasPrefix(mount.Target, "/") {
mount.Target = fmt.Sprintf("/%s", mount.Target)
}
if !shared.PathExists(mount.Target) {
err := os.MkdirAll(mount.Target, 0755)
if err != nil {
logger.Errorf("Failed to create mount target %q", mount.Target)
continue // Don't try to mount if mount point can't be created.
}
}
if mount.FSType == "9p" {
// Before mounting with 9p, try virtio-fs and use 9p as the fallback.
args := []string{"-t", "virtiofs", mount.Source, mount.Target}
for _, opt := range mount.Options {
// Ignore the transport and msize mount option as they are specific to 9p.
if strings.HasPrefix(opt, "trans=") || strings.HasPrefix(opt, "msize=") {
continue
}
args = append(args, "-o", opt)
}
_, err = shared.RunCommand("mount", args...)
if err == nil {
logger.Infof("Mounted %q (Type: %q, Options: %v) to %q", mount.Source, "virtiofs", mount.Options, mount.Target)
continue
}
}
args := []string{"-t", mount.FSType, mount.Source, mount.Target}
for _, opt := range mount.Options {
args = append(args, "-o", opt)
}
_, err = shared.RunCommand("mount", args...)
if err != nil {
logger.Errorf("Failed mount %q (Type: %q, Options: %v) to %q: %v", mount.Source, mount.FSType, mount.Options, mount.Target, err)
continue
}
logger.Infof("Mounted %q (Type: %q, Options: %v) to %q", mount.Source, mount.FSType, mount.Options, mount.Target)
}
}