-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
245 lines (210 loc) · 5.55 KB
/
main.go
File metadata and controls
245 lines (210 loc) · 5.55 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
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"slices"
"strings"
"sync"
"syscall"
"github.com/fatih/color"
"github.com/moby/moby/api/types/events"
"github.com/moby/moby/client"
)
type LogState struct {
LastTime string
LastLine string
}
type Registry struct {
mu sync.Mutex
active map[string]context.CancelFunc
lastStates map[string]LogState
Client *Client
Targets []string
targetColors map[string]*color.Color
}
func NewRegistry(client *Client, targets []string) *Registry {
targetColors := make(map[string]*color.Color)
{
allColors := []*color.Color{
color.New(color.FgCyan),
color.New(color.FgBlue),
color.New(color.FgMagenta),
color.New(color.FgGreen),
color.New(color.FgRed),
color.New(color.FgYellow),
color.New(color.FgCyan).Add(color.ReverseVideo),
color.New(color.FgBlue).Add(color.ReverseVideo),
color.New(color.FgMagenta).Add(color.ReverseVideo),
color.New(color.FgGreen).Add(color.ReverseVideo),
color.New(color.FgRed).Add(color.ReverseVideo),
color.New(color.FgYellow).Add(color.ReverseVideo),
color.New(color.FgCyan).Add(color.Bold).Add(color.Underline),
color.New(color.FgBlue).Add(color.Bold).Add(color.Underline),
color.New(color.FgMagenta).Add(color.Bold).Add(color.Underline),
color.New(color.FgGreen).Add(color.Bold).Add(color.Underline),
color.New(color.FgRed).Add(color.Bold).Add(color.Underline),
color.New(color.FgYellow).Add(color.Bold).Add(color.Underline),
}
for i, v := range targets {
targetColors[v] = allColors[i%len(allColors)]
}
}
return &Registry{
active: make(map[string]context.CancelFunc),
lastStates: make(map[string]LogState),
Client: client,
Targets: targets,
targetColors: targetColors,
}
}
func main() {
targets := os.Args[1:]
if len(targets) == 0 {
log.Fatal("Please specify at least one container name to tail")
}
slices.Sort(targets)
targets = slices.Compact(targets)
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
dockerClient := NewClient()
reg := NewRegistry(dockerClient, targets)
running, err := dockerClient.ListContainers(ctx)
if err != nil {
log.Println("error listing docker containers", err)
os.Exit(1)
}
for _, c := range running {
if reg.isTarget(c.Name, c.ComposeService) {
reg.startTailing(ctx, c.ID, c.Name)
}
}
eventChan, errChan := dockerClient.Events(ctx)
for {
select {
case <-ctx.Done():
return
case err := <-errChan:
log.Printf("Event Error: %v", err)
return
case msg := <-eventChan:
reg.handleEvent(ctx, msg)
}
}
}
func (reg *Registry) handleEvent(ctx context.Context, msg events.Message) {
name := strings.TrimPrefix(msg.Actor.Attributes["name"], "/")
service := msg.Actor.Attributes["com.docker.compose.service"]
if !reg.isTarget(name, service) {
return
}
switch msg.Action {
case "start":
reg.startTailing(ctx, msg.Actor.ID, name)
case "die", "kill", "stop":
reg.stopTailing(name, name)
}
}
func (reg *Registry) startTailing(ctx context.Context, id, name string) {
reg.mu.Lock()
defer reg.mu.Unlock()
if _, exists := reg.active[name]; exists {
return
}
displayName := name
container, err := reg.Client.GetContainer(ctx, id)
if err == nil && container.ComposeProject != "" && container.ComposeService != "" {
displayName = shortenComposeName(container.ComposeProject, container.ComposeService)
}
tCtx, tCancel := context.WithCancel(ctx)
reg.active[name] = tCancel
state, hasState := reg.lastStates[name]
go func() {
defer reg.stopTailing(name, displayName)
opts := client.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Follow: true,
Timestamps: true,
}
if hasState {
opts.Since = state.LastTime
} else {
opts.Tail = "1000"
}
msgs, errs := reg.Client.ContainerLogs(tCtx, id, opts)
for {
select {
case <-tCtx.Done():
return
case err := <-errs:
if err != nil && err != context.Canceled {
fmt.Printf("[%s] Stream closed: %v\n", displayName, err)
}
return
case msg := <-msgs:
parts := strings.SplitN(msg, " ", 2)
if len(parts) < 2 {
fmt.Printf("[%s] %s", displayName, msg)
continue
}
timestamp := parts[0]
content := parts[1]
if hasState && msg == state.LastLine {
continue
}
reg.mu.Lock()
state = LogState{
LastTime: timestamp,
LastLine: msg,
}
reg.lastStates[name] = state
hasState = true
reg.mu.Unlock()
var sb strings.Builder
sb.WriteString(reg.targetColors[name].Sprint(displayName))
sb.WriteString("┃")
sb.WriteString(content)
fmt.Printf(sb.String())
}
}
}()
}
func (reg *Registry) stopTailing(name, displayName string) {
reg.mu.Lock()
defer reg.mu.Unlock()
if cancel, exists := reg.active[name]; exists {
cancel()
delete(reg.active, name)
fmt.Printf("--- Detached from %s ---\n", displayName)
}
}
func (reg *Registry) isTarget(name, service string) bool {
for _, t := range reg.Targets {
if name == t || service == t {
return true
}
}
return false
}
func shortenComposeName(project, service string) string {
parts := strings.Split(project, "-")
var projectAbbr string
for _, p := range parts {
if len(p) > 0 {
projectAbbr += string(p[0])
}
}
if len(projectAbbr) < 2 && len(project) > 1 {
lastPart := parts[len(parts)-1]
needed := 2 - len(projectAbbr)
if len(lastPart) > needed {
projectAbbr += lastPart[len(lastPart)-needed:]
} else {
return fmt.Sprintf("%s-%s", project, service)
}
}
return fmt.Sprintf("%s-%s", projectAbbr, service)
}