-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker.go
More file actions
79 lines (68 loc) · 1.67 KB
/
Copy pathdocker.go
File metadata and controls
79 lines (68 loc) · 1.67 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
package main
import (
"context"
"errors"
"os"
"strings"
"github.com/moby/moby/api/pkg/stdcopy"
"github.com/moby/moby/client"
)
var ErrNoContainers = errors.New("no containers found")
type DockerService struct {
client *client.Client
}
func NewDockerService() (*DockerService, error) {
cli, err := client.New(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return nil, err
}
return &DockerService{client: cli}, nil
}
func (s *DockerService) GetContainers() (map[string]string, error) {
ctx := context.Background()
containers, err := s.client.ContainerList(ctx, client.ContainerListOptions{})
if err != nil {
return nil, err
}
if len(containers.Items) == 0 {
return nil, ErrNoContainers
}
containerResult := make(map[string]string)
for _, container := range containers.Items {
containerResult[container.ID] = strings.TrimPrefix(container.Names[0], "/")
}
return containerResult, nil
}
func (s *DockerService) WatchLogs(containerID, containerName string, lines string, color string) error {
loggerConfig := Config{
Output: os.Stdout,
ContainerName: containerName,
Color: color,
}
lw := NewLogWriter(loggerConfig, "stdout")
ctx := context.Background()
stdoutReader, err := s.client.ContainerLogs(ctx, containerID, client.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Follow: true,
Tail: lines,
})
if err != nil {
return err
}
defer func(logReader client.ContainerLogsResult) {
err := logReader.Close()
if err != nil {
panic(err)
}
}(stdoutReader)
_, _ = stdcopy.StdCopy(
lw,
lw,
stdoutReader,
)
return nil
}
func (s *DockerService) Close() error {
return s.client.Close()
}