-
Notifications
You must be signed in to change notification settings - Fork 28
/
stream.go
338 lines (290 loc) · 8.87 KB
/
stream.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
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
// Copyright (c) 2022 Target Brands, Inc. All rights reserved.
//
// Use of this source code is governed by the LICENSE file in this repository.
package api
import (
"bufio"
"bytes"
"fmt"
"net/http"
"time"
"github.com/go-vela/server/router/middleware/org"
"github.com/go-vela/server/router/middleware/user"
"github.com/go-vela/server/database"
"github.com/go-vela/server/router/middleware/build"
"github.com/go-vela/server/router/middleware/repo"
"github.com/go-vela/server/router/middleware/service"
"github.com/go-vela/server/router/middleware/step"
"github.com/go-vela/server/util"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
const logUpdateInterval = 1 * time.Second
// swagger:operation POST /api/v1/repos/{org}/{repo}/builds/{build}/service/{service}/stream stream PostServiceStream
//
// Stream the logs for a service
//
// ---
// produces:
// - application/json
// parameters:
// - in: path
// name: org
// description: Name of the org
// required: true
// type: string
// - in: path
// name: repo
// description: Name of the repo
// required: true
// type: string
// - in: path
// name: build
// description: Build number
// required: true
// type: integer
// - in: path
// name: service
// description: Service number
// required: true
// type: integer
// - in: body
// name: body
// description: Payload containing logs
// required: true
// schema:
// type: string
// security:
// - ApiKeyAuth: []
// responses:
// '204':
// description: Successfully received logs
// '400':
// description: Unable to stream the logs
// schema:
// "$ref": "#/definitions/Error"
// '404':
// description: Unable to stream the logs
// schema:
// "$ref": "#/definitions/Error"
// '500':
// description: Unable to stream the logs
// schema:
// "$ref": "#/definitions/Error"
// PostServiceStream represents the API handler that
// streams service logs to the database.
//
//nolint:dupl // separate service/step functions for consistency with API
func PostServiceStream(c *gin.Context) {
// capture middleware values
b := build.Retrieve(c)
o := org.Retrieve(c)
r := repo.Retrieve(c)
s := service.Retrieve(c)
u := user.Retrieve(c)
entry := fmt.Sprintf("%s/%d", r.GetFullName(), b.GetNumber())
// update engine logger with API metadata
//
// https://pkg.go.dev/github.com/sirupsen/logrus?tab=doc#Entry.WithFields
logger := logrus.WithFields(logrus.Fields{
"build": b.GetNumber(),
"org": o,
"repo": r.GetName(),
"service": s.GetNumber(),
"user": u.GetName(),
})
logger.Infof("streaming logs for service %s/%d", entry, s.GetNumber())
// create new buffer for uploading logs
logs := new(bytes.Buffer)
// create new channel for processing logs
done := make(chan bool)
// defer closing channel to stop processing logs
defer close(done)
// send API call to capture the service logs
_log, err := database.FromContext(c).GetServiceLog(s.GetID())
if err != nil {
retErr := fmt.Errorf("unable to get logs for service %s/%d: %w", entry, s.GetNumber(), err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
go func() {
logger.Debugf("polling request body buffer for service %s/%d", entry, s.GetNumber())
// spawn "infinite" loop that will upload logs
// from the buffer until the channel is closed
for {
// sleep before attempting to upload logs
time.Sleep(logUpdateInterval)
// create a non-blocking select to check if the channel is closed
select {
// after repo timeout of idle (no response) end the stream
//
// this is a safety mechanism
case <-time.After(time.Duration(r.GetTimeout()) * time.Minute):
logger.Tracef("repo timeout of %d exceeded", r.GetTimeout())
return
// channel is closed
case <-done:
logger.Trace("channel closed for polling container logs")
// return out of the go routine
return
// channel is not closed
default:
// get the current size of log data
currBytesSize := len(_log.GetData())
// update the existing log with the new bytes if there is new data to add
if len(logs.Bytes()) > currBytesSize {
// https://pkg.go.dev/github.com/go-vela/types/library?tab=doc#Log.SetData
_log.SetData(logs.Bytes())
// update the log in the database
err = database.FromContext(c).UpdateLog(_log)
if err != nil {
retErr := fmt.Errorf("unable to update logs for service %s/%d: %w", entry, s.GetNumber(), err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
}
}
}
}()
logger.Debugf("scanning request body for service %s/%d", entry, s.GetNumber())
scanner := bufio.NewScanner(c.Request.Body)
for scanner.Scan() {
// write all the logs from the scanner
logs.Write(append(scanner.Bytes(), []byte("\n")...))
}
c.JSON(http.StatusNoContent, nil)
}
// swagger:operation POST /api/v1/repos/{org}/{repo}/builds/{build}/steps/{step}/stream stream PostStepStream
//
// Stream the logs for a step
//
// ---
// produces:
// - application/json
// parameters:
// - in: path
// name: org
// description: Name of the org
// required: true
// type: string
// - in: path
// name: repo
// description: Name of the repo
// required: true
// type: string
// - in: path
// name: build
// description: Build number
// required: true
// type: integer
// - in: path
// name: step
// description: Step number
// required: true
// type: integer
// - in: body
// name: body
// description: Payload containing logs
// required: true
// schema:
// type: string
// security:
// - ApiKeyAuth: []
// responses:
// '204':
// description: Successfully received logs
// '400':
// description: Unable to stream the logs
// schema:
// "$ref": "#/definitions/Error"
// '404':
// description: Unable to stream the logs
// schema:
// "$ref": "#/definitions/Error"
// '500':
// description: Unable to stream the logs
// schema:
// "$ref": "#/definitions/Error"
// PostStepStream represents the API handler that
// streams service logs to the database.
//
//nolint:dupl // separate service/step functions for consistency with API
func PostStepStream(c *gin.Context) {
// capture middleware values
b := build.Retrieve(c)
o := org.Retrieve(c)
r := repo.Retrieve(c)
s := step.Retrieve(c)
u := user.Retrieve(c)
entry := fmt.Sprintf("%s/%d", r.GetFullName(), b.GetNumber())
// update engine logger with API metadata
//
// https://pkg.go.dev/github.com/sirupsen/logrus?tab=doc#Entry.WithFields
logger := logrus.WithFields(logrus.Fields{
"build": b.GetNumber(),
"org": o,
"repo": r.GetName(),
"step": s.GetNumber(),
"user": u.GetName(),
})
logger.Infof("streaming logs for step %s/%d", entry, s.GetNumber())
// create new buffer for uploading logs
logs := new(bytes.Buffer)
// create new channel for processing logs
done := make(chan bool)
// defer closing channel to stop processing logs
defer close(done)
// send API call to capture the step logs
_log, err := database.FromContext(c).GetStepLog(s.GetID())
if err != nil {
retErr := fmt.Errorf("unable to get logs for step %s/%d: %w", entry, s.GetNumber(), err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
go func() {
logger.Debugf("polling request body buffer for step %s/%d", entry, s.GetNumber())
// spawn "infinite" loop that will upload logs
// from the buffer until the channel is closed
for {
// sleep before attempting to upload logs
time.Sleep(logUpdateInterval)
// create a non-blocking select to check if the channel is closed
select {
// after repo timeout of idle (no response) end the stream
//
// this is a safety mechanism
case <-time.After(time.Duration(r.GetTimeout()) * time.Minute):
logger.Tracef("repo timeout of %d exceeded", r.GetTimeout())
return
// channel is closed
case <-done:
logger.Trace("channel closed for polling container logs")
// return out of the go routine
return
// channel is not closed
default:
// get the current size of log data
currBytesSize := len(_log.GetData())
// update the existing log with the new bytes if there is new data to add
if len(logs.Bytes()) > currBytesSize {
// https://pkg.go.dev/github.com/go-vela/types/library?tab=doc#Log.SetData
_log.SetData(logs.Bytes())
// update the log in the database
err = database.FromContext(c).UpdateLog(_log)
if err != nil {
retErr := fmt.Errorf("unable to update logs for step %s/%d: %w", entry, s.GetNumber(), err)
util.HandleError(c, http.StatusInternalServerError, retErr)
return
}
}
}
}
}()
logger.Debugf("scanning request body for step %s/%d", entry, s.GetNumber())
scanner := bufio.NewScanner(c.Request.Body)
for scanner.Scan() {
// write all the logs from the scanner
logs.Write(append(scanner.Bytes(), []byte("\n")...))
}
c.JSON(http.StatusNoContent, nil)
}