-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinuxkit.go
More file actions
463 lines (391 loc) · 10.8 KB
/
linuxkit.go
File metadata and controls
463 lines (391 loc) · 10.8 KB
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
package container
import (
"bufio"
"context"
"fmt"
goio "io"
"os"
"os/exec"
"syscall"
"time"
"dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
)
// LinuxKitManager implements the Manager interface for LinuxKit VMs.
type LinuxKitManager struct {
state *State
hypervisor Hypervisor
medium io.Medium
}
// NewLinuxKitManager creates a new LinuxKit manager with auto-detected hypervisor.
func NewLinuxKitManager(m io.Medium) (*LinuxKitManager, error) {
statePath, err := DefaultStatePath()
if err != nil {
return nil, coreerr.E("NewLinuxKitManager", "failed to determine state path", err)
}
state, err := LoadState(statePath)
if err != nil {
return nil, coreerr.E("NewLinuxKitManager", "failed to load state", err)
}
hypervisor, err := DetectHypervisor()
if err != nil {
return nil, err
}
return &LinuxKitManager{
state: state,
hypervisor: hypervisor,
medium: m,
}, nil
}
// NewLinuxKitManagerWithHypervisor creates a manager with a specific hypervisor.
func NewLinuxKitManagerWithHypervisor(m io.Medium, state *State, hypervisor Hypervisor) *LinuxKitManager {
return &LinuxKitManager{
state: state,
hypervisor: hypervisor,
medium: m,
}
}
// Run starts a new LinuxKit VM from the given image.
func (m *LinuxKitManager) Run(ctx context.Context, image string, opts RunOptions) (*Container, error) {
// Validate image exists
if !m.medium.IsFile(image) {
return nil, coreerr.E("LinuxKitManager.Run", "image not found: "+image, nil)
}
// Detect image format
format := DetectImageFormat(image)
if format == FormatUnknown {
return nil, coreerr.E("LinuxKitManager.Run", "unsupported image format: "+image, nil)
}
// Generate container ID
id, err := GenerateID()
if err != nil {
return nil, coreerr.E("LinuxKitManager.Run", "failed to generate container ID", err)
}
// Apply defaults
if opts.Memory <= 0 {
opts.Memory = 1024
}
if opts.CPUs <= 0 {
opts.CPUs = 1
}
if opts.SSHPort <= 0 {
opts.SSHPort = 2222
}
// Use name or generate from ID
name := opts.Name
if name == "" {
name = id[:8]
}
// Ensure logs directory exists
if err := EnsureLogsDir(); err != nil {
return nil, coreerr.E("LinuxKitManager.Run", "failed to create logs directory", err)
}
// Get log file path
logPath, err := LogPath(id)
if err != nil {
return nil, coreerr.E("LinuxKitManager.Run", "failed to determine log path", err)
}
// Build hypervisor options
hvOpts := &HypervisorOptions{
Memory: opts.Memory,
CPUs: opts.CPUs,
LogFile: logPath,
SSHPort: opts.SSHPort,
Ports: opts.Ports,
Volumes: opts.Volumes,
Detach: opts.Detach,
}
// Build the command
cmd, err := m.hypervisor.BuildCommand(ctx, image, hvOpts)
if err != nil {
return nil, coreerr.E("LinuxKitManager.Run", "failed to build hypervisor command", err)
}
// Create log file
logFile, err := os.Create(logPath)
if err != nil {
return nil, coreerr.E("LinuxKitManager.Run", "failed to create log file", err)
}
// Create container record
container := &Container{
ID: id,
Name: name,
Image: image,
Status: StatusRunning,
StartedAt: time.Now(),
Ports: opts.Ports,
Memory: opts.Memory,
CPUs: opts.CPUs,
}
if opts.Detach {
// Run in background
cmd.Stdout = logFile
cmd.Stderr = logFile
// Start the process
if err := cmd.Start(); err != nil {
_ = logFile.Close()
return nil, coreerr.E("LinuxKitManager.Run", "failed to start VM", err)
}
container.PID = cmd.Process.Pid
// Save state
if err := m.state.Add(container); err != nil {
// Try to kill the process we just started
_ = cmd.Process.Kill()
_ = logFile.Close()
return nil, coreerr.E("LinuxKitManager.Run", "failed to save state", err)
}
// Close log file handle (process has its own)
_ = logFile.Close()
// Start a goroutine to wait for process exit and update state
go m.waitForExit(container.ID, cmd)
return container, nil
}
// Run in foreground
// Tee output to both log file and stdout
stdout, err := cmd.StdoutPipe()
if err != nil {
_ = logFile.Close()
return nil, coreerr.E("LinuxKitManager.Run", "failed to get stdout pipe", err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
_ = logFile.Close()
return nil, coreerr.E("LinuxKitManager.Run", "failed to get stderr pipe", err)
}
if err := cmd.Start(); err != nil {
_ = logFile.Close()
return nil, coreerr.E("LinuxKitManager.Run", "failed to start VM", err)
}
container.PID = cmd.Process.Pid
// Save state before waiting
if err := m.state.Add(container); err != nil {
_ = cmd.Process.Kill()
_ = logFile.Close()
return nil, coreerr.E("LinuxKitManager.Run", "failed to save state", err)
}
// Copy output to both log and stdout
go func() {
mw := goio.MultiWriter(logFile, os.Stdout)
_, _ = goio.Copy(mw, stdout)
}()
go func() {
mw := goio.MultiWriter(logFile, os.Stderr)
_, _ = goio.Copy(mw, stderr)
}()
// Wait for the process to complete
if err := cmd.Wait(); err != nil {
container.Status = StatusError
} else {
container.Status = StatusStopped
}
_ = logFile.Close()
if err := m.state.Update(container); err != nil {
return container, coreerr.E("LinuxKitManager.Run", "update container state", err)
}
return container, nil
}
// waitForExit monitors a detached process and updates state when it exits.
func (m *LinuxKitManager) waitForExit(id string, cmd *exec.Cmd) {
err := cmd.Wait()
container, ok := m.state.Get(id)
if ok {
if err != nil {
container.Status = StatusError
} else {
container.Status = StatusStopped
}
_ = m.state.Update(container)
}
}
// Stop stops a running container by sending SIGTERM.
func (m *LinuxKitManager) Stop(ctx context.Context, id string) error {
if err := ctx.Err(); err != nil {
return err
}
container, ok := m.state.Get(id)
if !ok {
return coreerr.E("LinuxKitManager.Stop", "container not found: "+id, nil)
}
if container.Status != StatusRunning {
return coreerr.E("LinuxKitManager.Stop", "container is not running: "+id, nil)
}
// Find the process
process, err := os.FindProcess(container.PID)
if err != nil {
// Process doesn't exist, update state
container.Status = StatusStopped
_ = m.state.Update(container)
return nil
}
// Send SIGTERM
if err := process.Signal(syscall.SIGTERM); err != nil {
// Process might already be gone
container.Status = StatusStopped
_ = m.state.Update(container)
return nil
}
// Honour already-cancelled contexts before waiting
if err := ctx.Err(); err != nil {
_ = process.Signal(syscall.SIGKILL)
return err
}
// Wait for graceful shutdown with timeout
done := make(chan struct{})
go func() {
_, _ = process.Wait()
close(done)
}()
select {
case <-done:
// Process exited gracefully
case <-time.After(10 * time.Second):
// Force kill
_ = process.Signal(syscall.SIGKILL)
<-done
case <-ctx.Done():
// Context cancelled
_ = process.Signal(syscall.SIGKILL)
return ctx.Err()
}
container.Status = StatusStopped
return m.state.Update(container)
}
// List returns all known containers, verifying process state.
func (m *LinuxKitManager) List(ctx context.Context) ([]*Container, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
containers := m.state.All()
// Verify each running container's process is still alive
for _, c := range containers {
if c.Status == StatusRunning {
if !isProcessRunning(c.PID) {
c.Status = StatusStopped
_ = m.state.Update(c)
}
}
}
return containers, nil
}
// isProcessRunning checks if a process with the given PID is still running.
func isProcessRunning(pid int) bool {
process, err := os.FindProcess(pid)
if err != nil {
return false
}
// On Unix, FindProcess always succeeds, so we need to send signal 0 to check
err = process.Signal(syscall.Signal(0))
return err == nil
}
// Logs returns a reader for the container's log output.
func (m *LinuxKitManager) Logs(ctx context.Context, id string, follow bool) (goio.ReadCloser, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
_, ok := m.state.Get(id)
if !ok {
return nil, coreerr.E("LinuxKitManager.Logs", "container not found: "+id, nil)
}
logPath, err := LogPath(id)
if err != nil {
return nil, coreerr.E("LinuxKitManager.Logs", "failed to determine log path", err)
}
if !m.medium.IsFile(logPath) {
return nil, coreerr.E("LinuxKitManager.Logs", "no logs available for container: "+id, nil)
}
if !follow {
// Simple case: just open and return the file
return m.medium.Open(logPath)
}
// Follow mode: create a reader that tails the file
return newFollowReader(ctx, m.medium, logPath)
}
// followReader implements goio.ReadCloser for following log files.
type followReader struct {
file goio.ReadCloser
ctx context.Context
cancel context.CancelFunc
reader *bufio.Reader
medium io.Medium
path string
}
func newFollowReader(ctx context.Context, m io.Medium, path string) (*followReader, error) {
file, err := m.Open(path)
if err != nil {
return nil, err
}
// Note: We don't seek here because Medium.Open doesn't guarantee Seekability.
ctx, cancel := context.WithCancel(ctx)
return &followReader{
file: file,
ctx: ctx,
cancel: cancel,
reader: bufio.NewReader(file),
medium: m,
path: path,
}, nil
}
func (f *followReader) Read(p []byte) (int, error) {
for {
select {
case <-f.ctx.Done():
return 0, goio.EOF
default:
}
n, err := f.reader.Read(p)
if n > 0 {
return n, nil
}
if err != nil && err != goio.EOF {
return 0, err
}
// No data available, wait a bit and try again
select {
case <-f.ctx.Done():
return 0, goio.EOF
case <-time.After(100 * time.Millisecond):
// Reset reader to pick up new data
f.reader.Reset(f.file)
}
}
}
func (f *followReader) Close() error {
f.cancel()
return f.file.Close()
}
// Exec executes a command inside the container via SSH.
func (m *LinuxKitManager) Exec(ctx context.Context, id string, cmd []string) error {
if err := ctx.Err(); err != nil {
return err
}
container, ok := m.state.Get(id)
if !ok {
return coreerr.E("LinuxKitManager.Exec", "container not found: "+id, nil)
}
if container.Status != StatusRunning {
return coreerr.E("LinuxKitManager.Exec", "container is not running: "+id, nil)
}
// Default SSH port
sshPort := 2222
// Build SSH command
sshArgs := []string{
"-p", fmt.Sprintf("%d", sshPort),
"-o", "StrictHostKeyChecking=yes",
"-o", "UserKnownHostsFile=~/.core/known_hosts",
"-o", "LogLevel=ERROR",
"root@localhost",
}
sshArgs = append(sshArgs, cmd...)
sshCmd := exec.CommandContext(ctx, "ssh", sshArgs...)
sshCmd.Stdin = os.Stdin
sshCmd.Stdout = os.Stdout
sshCmd.Stderr = os.Stderr
return sshCmd.Run()
}
// State returns the manager's state (for testing).
func (m *LinuxKitManager) State() *State {
return m.state
}
// Hypervisor returns the manager's hypervisor (for testing).
func (m *LinuxKitManager) Hypervisor() Hypervisor {
return m.hypervisor
}