-
Notifications
You must be signed in to change notification settings - Fork 18
/
rpc.go
342 lines (281 loc) · 9.74 KB
/
rpc.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
339
340
341
342
package rpc
import (
"context"
"errors"
"fmt"
"github.com/cirruslabs/cirrus-ci-agent/api"
"github.com/cirruslabs/cirrus-cli/internal/commands/logs"
"github.com/cirruslabs/cirrus-cli/internal/executor/build"
"github.com/cirruslabs/cirrus-cli/internal/executor/build/commandstatus"
"github.com/cirruslabs/cirrus-cli/internal/executor/heuristic"
"github.com/cirruslabs/echelon"
"github.com/cirruslabs/echelon/renderers"
"github.com/golang/protobuf/ptypes/empty"
"github.com/google/uuid"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"io"
"strings"
"sync"
"time"
// Registers a gzip compressor needed for streaming logs from the agent.
_ "google.golang.org/grpc/encoding/gzip"
)
var ErrRPCFailed = errors.New("RPC server failed")
type RPC struct {
// must be embedded to have forward compatible implementations
api.UnimplementedCirrusCIServiceServer
listener *heuristic.Listener
server *grpc.Server
serverWaitGroup sync.WaitGroup
serverSecret, clientSecret string
build *build.Build
logger *echelon.Logger
artifactsDir string
}
func New(build *build.Build, opts ...Option) *RPC {
r := &RPC{
server: grpc.NewServer(),
serverSecret: uuid.New().String(),
clientSecret: uuid.New().String(),
build: build,
}
// Register itself
api.RegisterCirrusCIServiceServer(r.server, r)
// Apply options
for _, opt := range opts {
opt(r)
}
// Apply default options (to cover those that weren't specified)
if r.logger == nil {
renderer := renderers.NewSimpleRenderer(io.Discard, nil)
r.logger = echelon.NewLogger(echelon.InfoLevel, renderer)
}
return r
}
func (r *RPC) ServerSecret() string {
return r.serverSecret
}
func (r *RPC) ClientSecret() string {
return r.clientSecret
}
// Start creates the listener and starts RPC server in a separate goroutine.
func (r *RPC) Start(ctx context.Context, address string) error {
listener, err := heuristic.NewListener(ctx, address)
if err != nil {
return fmt.Errorf("%w: failed to start RPC service on %s: %v", ErrRPCFailed, address, err)
}
r.listener = listener
r.serverWaitGroup.Add(1)
go func() {
if err := r.server.Serve(listener); err != nil {
if !errors.Is(err, grpc.ErrServerStopped) {
r.logger.Errorf("RPC server failed: %v", err)
}
}
r.serverWaitGroup.Done()
}()
r.logger.Debugf("gRPC server is listening at %s (%s inside of a container)",
r.DirectEndpoint(), r.ContainerEndpoint())
return nil
}
// ContainerEndpoint returns RPC server address suitable for use in agent's "-api-endpoint" flag
// when running inside of a container.
func (r *RPC) ContainerEndpoint() string {
return r.listener.ContainerEndpoint()
}
// DirectEndpoint returns RPC server address suitable for use in agent's "-api-endpoint" flag
// when running on the host.
func (r *RPC) DirectEndpoint() string {
return r.listener.DirectEndpoint()
}
// Stop gracefully stops the RPC server.
func (r *RPC) Stop() {
r.server.GracefulStop()
r.serverWaitGroup.Wait()
}
func (r *RPC) InitialCommands(
ctx context.Context,
req *api.InitialCommandsRequest,
) (*api.CommandsResponse, error) {
task, err := r.build.GetTaskFromIdentification(req.TaskIdentification, r.clientSecret)
if err != nil {
return nil, err
}
return &api.CommandsResponse{
Environment: task.Environment,
Commands: task.ProtoCommands(),
ServerToken: r.serverSecret,
TimeoutInSeconds: int64(task.Timeout.Seconds()),
FailedAtLeastOnce: task.FailedAtLeastOnce(),
}, nil
}
func (r *RPC) ReportCommandUpdates(
ctx context.Context,
req *api.ReportCommandUpdatesRequest,
) (*api.ReportCommandUpdatesResponse, error) {
task, err := r.build.GetTaskFromIdentification(req.TaskIdentification, r.clientSecret)
if err != nil {
return nil, err
}
for _, update := range req.Updates {
command := task.GetCommand(update.Name)
if command == nil {
return nil, status.Errorf(codes.FailedPrecondition, "attempt to set status for non-existent command %s",
update.Name)
}
commandLogger := r.getCommandLogger(task, command)
// Register whether the current command succeeded or failed
// so that the main loop can make the decision whether
// to proceed with the execution or not.
switch {
case update.Status == api.Status_COMPLETED:
command.SetStatus(commandstatus.Success)
commandLogger.Debugf("command %s succeeded", update.Name)
commandLogger.FinishWithType(echelon.FinishTypeSucceeded)
case update.Status == api.Status_SKIPPED:
command.SetStatus(commandstatus.Success)
commandLogger.Debugf("command %s was skipped", update.Name)
commandLogger.FinishWithType(echelon.FinishTypeSkipped)
case update.Status == api.Status_ABORTED || update.Status == api.Status_FAILED:
command.SetStatus(commandstatus.Failure)
commandLogger.Debugf("command %s failed", update.Name)
commandLogger.FinishWithType(echelon.FinishTypeFailed)
}
}
return &api.ReportCommandUpdatesResponse{}, nil
}
func (r *RPC) ReportAgentFinished(
ctx context.Context,
req *api.ReportAgentFinishedRequest,
) (*api.ReportAgentFinishedResponse, error) {
return &api.ReportAgentFinishedResponse{}, nil
}
func (r *RPC) getCommandLogger(task *build.Task, command *build.Command) *echelon.Logger {
commandLoggerScope := fmt.Sprintf("'%s'", command.ProtoCommand.Name)
command.ProtoCommand.GetScriptInstruction()
switch command.ProtoCommand.Instruction.(type) {
case *api.Command_ScriptInstruction:
commandLoggerScope += " script"
case *api.Command_BackgroundScriptInstruction:
commandLoggerScope += " background script"
case *api.Command_CacheInstruction:
commandLoggerScope += " cache"
case *api.Command_ArtifactsInstruction:
commandLoggerScope += " artifacts"
}
return r.logger.Scoped(task.UniqueDescription()).Scoped(commandLoggerScope)
}
func (r *RPC) StreamLogs(stream api.CirrusCIService_StreamLogsServer) error {
var currentTaskName string
var currentCommand string
streamLogger := r.logger
for {
logEntry, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
streamLogger.Warnf("Error while receiving logs: %v", err)
return err
}
switch x := logEntry.Value.(type) {
case *api.LogEntry_Key:
task, err := r.build.GetTaskFromIdentification(x.Key.TaskIdentification, r.clientSecret)
if err != nil {
return err
}
currentTaskName = task.Name
currentCommand = x.Key.CommandName
command := task.GetCommand(currentCommand)
if command == nil {
return status.Errorf(codes.FailedPrecondition, "attempt to stream logs for non-existent command %s",
currentCommand)
}
streamLogger = r.getCommandLogger(task, command)
streamLogger.Debugf("begin streaming logs")
case *api.LogEntry_Chunk:
if currentTaskName == "" {
return status.Error(codes.PermissionDenied, "not authenticated")
}
streamLogger.Debugf("received log chunk of %d bytes", len(x.Chunk.Data))
// Ignore the newline at the end of the chunk,
// echelon's Infof() below already adds one
log := strings.TrimSuffix(string(x.Chunk.Data), "\n")
logLines := strings.Split(log, "\n")
for _, logLine := range logLines {
streamLogger.Infof("%s", logLine)
}
}
}
if err := stream.SendAndClose(&api.UploadLogsResponse{}); err != nil {
streamLogger.Warnf("Error while closing log stream: %v", err)
return err
}
return nil
}
func (r *RPC) Heartbeat(ctx context.Context, req *api.HeartbeatRequest) (*api.HeartbeatResponse, error) {
task, err := r.build.GetTaskFromIdentification(req.TaskIdentification, r.clientSecret)
if err != nil {
return nil, err
}
r.logger.Scoped(task.UniqueDescription()).Debugf("received heartbeat")
// Update last heartbeat time
currentTime := time.Now()
task.LastHeartbeatReceivedAt.Store(¤tTime)
return &api.HeartbeatResponse{}, nil
}
func (r *RPC) ReportAgentError(ctx context.Context, req *api.ReportAgentProblemRequest) (*empty.Empty, error) {
task, err := r.build.GetTaskFromIdentification(req.TaskIdentification, r.clientSecret)
if err != nil {
return nil, err
}
r.logger.Scoped(task.UniqueDescription()).Errorf("agent error: %s", req.Message)
return &empty.Empty{}, nil
}
func (r *RPC) ReportAgentWarning(ctx context.Context, req *api.ReportAgentProblemRequest) (*empty.Empty, error) {
task, err := r.build.GetTaskFromIdentification(req.TaskIdentification, r.clientSecret)
if err != nil {
return nil, err
}
r.logger.Scoped(task.UniqueDescription()).Warnf("agent warning: %s", req.Message)
return &empty.Empty{}, nil
}
func (r *RPC) ReportAgentSignal(ctx context.Context, req *api.ReportAgentSignalRequest) (*empty.Empty, error) {
task, err := r.build.GetTaskFromIdentification(req.TaskIdentification, r.clientSecret)
if err != nil {
return nil, err
}
r.logger.Scoped(task.UniqueDescription()).Debugf("agent signal: %s", req.Signal)
return &empty.Empty{}, nil
}
func (r *RPC) ReportAnnotations(ctx context.Context, req *api.ReportAnnotationsCommandRequest) (*empty.Empty, error) {
_, err := r.build.GetTaskFromIdentification(req.TaskIdentification, r.clientSecret)
if err != nil {
return nil, err
}
ghaRenderer, ok := r.logger.Renderer().(*logs.GithubActionsLogsRenderer)
if !ok {
return &empty.Empty{}, nil
}
for _, annotation := range req.Annotations {
if annotation.FileLocation == nil {
continue
}
var mappedLevel string
switch annotation.Level {
case api.Annotation_NOTICE:
mappedLevel = "notice"
case api.Annotation_WARNING:
mappedLevel = "warning"
case api.Annotation_FAILURE:
mappedLevel = "error"
}
rawMessage := fmt.Sprintf("::%s file=%s,line=%d,endLine=%d,title=%s::%s\n", mappedLevel,
annotation.FileLocation.Path, annotation.FileLocation.StartLine, annotation.FileLocation.EndLine,
annotation.Message, annotation.RawDetails)
ghaRenderer.RenderRawMessage(rawMessage)
}
return &empty.Empty{}, nil
}