-
Notifications
You must be signed in to change notification settings - Fork 221
/
logs.go
147 lines (116 loc) · 2.5 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
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
package monitor
import (
"context"
"io"
"time"
"github.com/jpillora/backoff"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/cmdctx"
"github.com/superfly/flyctl/terminal"
)
type LogOptions struct {
W io.Writer
MaxBackoff time.Duration
AppName string
VMID string
RegionCode string
}
func WatchLogs(cc *cmdctx.CmdContext, w io.Writer, opts LogOptions) error {
ctx := cc.Command.Context()
errorCount := 0
b := &backoff.Backoff{
Min: 250 * time.Millisecond,
Max: 5 * time.Second,
Factor: 2,
Jitter: true,
}
if opts.MaxBackoff != 0 {
b.Max = opts.MaxBackoff
}
nextToken := ""
// logPresenter := presenters.LogPresenter{}
for {
entries, token, err := cc.Client.API().GetAppLogs(ctx, opts.AppName, nextToken, opts.RegionCode, opts.VMID)
if err != nil {
terminal.Debugf("error getting app logs: %v\n", err)
if api.IsNotAuthenticatedError(err) {
return err
} else if api.IsNotFoundError(err) {
return err
} else {
errorCount++
if errorCount > 10 {
return err
}
time.Sleep(b.Duration())
}
}
errorCount = 0
if len(entries) == 0 {
time.Sleep(b.Duration())
} else {
b.Reset()
// logPresenter.FPrint(w, false, entries)
if token != "" {
nextToken = token
}
}
}
}
func NewLogStream(apiClient *api.Client) *LogStream {
return &LogStream{apiClient: apiClient}
}
type LogStream struct {
apiClient *api.Client
err error
}
func (ls *LogStream) Err() error {
return ls.err
}
func (ls *LogStream) Stream(ctx context.Context, opts LogOptions) <-chan []api.LogEntry {
out := make(chan []api.LogEntry)
b := &backoff.Backoff{
Min: 250 * time.Millisecond,
Max: 5 * time.Second,
Factor: 2,
Jitter: true,
}
if opts.MaxBackoff != 0 {
b.Max = opts.MaxBackoff
}
go func() {
defer close(out)
errorCount := 0
nextToken := ""
var wait <-chan time.Time
for {
entries, token, err := ls.apiClient.GetAppLogs(ctx, opts.AppName, nextToken, opts.RegionCode, opts.VMID)
if err != nil {
errorCount++
if api.IsNotAuthenticatedError(err) || api.IsNotFoundError(err) || errorCount > 10 {
ls.err = err
return
}
wait = time.After(b.Duration())
} else {
errorCount = 0
if len(entries) == 0 {
wait = time.After(b.Duration())
} else {
b.Reset()
out <- entries
wait = time.After(0)
if token != "" {
nextToken = token
}
}
}
select {
case <-ctx.Done():
return
case <-wait:
}
}
}()
return out
}