-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogs.go
115 lines (96 loc) · 2.17 KB
/
logs.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
package ecsceed
import (
"context"
"fmt"
"strconv"
"strings"
"time"
)
type LogsOption struct {
AdditionalParams Params
ContainerName string
StartTime string
Tail bool
}
var units = []string{"m", "h", "d"}
func parseStartTime(startTime string) (time.Time, error) {
var unit string
for _, u := range units {
if strings.HasSuffix(startTime, u) {
unit = u
break
}
}
if unit != "" {
now := time.Now()
nums := strings.TrimSuffix(startTime, unit)
num, err := strconv.Atoi(nums)
if err != nil {
return time.Time{}, err
}
switch unit {
case "m":
return now.Add(time.Minute * time.Duration(-num)), nil
case "h":
return now.Add(time.Hour * time.Duration(-num)), nil
case "d":
return now.Add(time.Hour * time.Duration(-num*24)), nil
}
}
return time.Time{}, fmt.Errorf("not implement a startTime format yet")
}
func (a *App) Logs(ctx context.Context, name string, opt LogsOption) error {
var startTime time.Time
if opt.StartTime != "" {
t, err := parseStartTime(opt.StartTime)
if err != nil {
return err
}
startTime = t
} else {
startTime = time.Now()
}
a.Log("base service", LogTarget(name))
err := a.ResolveConfigStack(opt.AdditionalParams)
if err != nil {
return err
}
_, ok := a.def.nameToSrv[name]
if !ok {
return fmt.Errorf("service %s is undefined", name)
}
fullname := a.resolveFullName(name)
srv, err := a.DescribeService(ctx, &fullname)
if err != nil {
return err
}
tdArn := srv.TaskDefinition
td, err := a.DescribeTaskDefinition(ctx, *tdArn)
if err != nil {
return err
}
container := containerOf(td, &opt.ContainerName)
a.Log("container", LogTarget(*container.Name))
tasks, err := a.ListServiceTasks(ctx, *srv.ServiceName)
if err != nil {
return err
}
for _, task := range tasks {
logGroup, logStream := a.GetLogInfo(task, container)
nl := strings.Split(logStream, "/")
prefix := fmt.Sprintf("[%s] ", nl[len(nl)-1])
if opt.Tail {
go a.WatchLogs(ctx, logGroup, logStream, startTime, prefix)
} else {
a.ShowLogs(ctx, logGroup, logStream, startTime, prefix)
}
}
if opt.Tail {
select {
case <-ctx.Done():
return ctx.Err()
}
} else {
return nil
}
}