-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathsession.go
More file actions
368 lines (331 loc) · 9.64 KB
/
Copy pathsession.go
File metadata and controls
368 lines (331 loc) · 9.64 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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package provisionersdk
import (
"context"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/google/uuid"
"github.com/spf13/afero"
"golang.org/x/xerrors"
protobuf "google.golang.org/protobuf/proto"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/codersdk/drpcsdk"
"github.com/coder/coder/v2/provisionersdk/proto"
"github.com/coder/coder/v2/provisionersdk/tfpath"
)
// protoServer is a wrapper that translates the dRPC protocol into a Session with method calls into the Server.
type protoServer struct {
server Server
opts ServeOptions
}
func (p *protoServer) Session(stream proto.DRPCProvisioner_SessionStream) error {
sessID := uuid.New().String()
s := &Session{
Logger: p.opts.Logger.With(slog.F("session_id", sessID)),
stream: stream,
server: p.server,
}
s.Files = tfpath.Session(p.opts.WorkDirectory, sessID)
defer func() {
s.Files.Cleanup(s.Context(), s.Logger, afero.NewOsFs())
}()
req, err := stream.Recv()
if err != nil {
return xerrors.Errorf("receive config: %w", err)
}
config := req.GetConfig()
if config == nil {
return xerrors.New("first request must be Config")
}
s.Config = config
if s.Config.ProvisionerLogLevel != "" {
s.logLevel = proto.LogLevel_value[strings.ToUpper(s.Config.ProvisionerLogLevel)]
}
// Cleanup any previously left stale sessions.
err = s.Files.CleanStaleSessions(s.Context(), s.Logger, afero.NewOsFs(), time.Now())
if err != nil {
return xerrors.Errorf("unable to clean stale sessions %q: %w", s.Files, err)
}
return s.handleRequests()
}
func (s *Session) requestReader(done <-chan struct{}) <-chan *proto.Request {
ch := make(chan *proto.Request)
go func() {
defer close(ch)
for {
req, err := s.stream.Recv()
if err != nil {
if !xerrors.Is(err, io.EOF) {
s.Logger.Warn(s.Context(), "recv done on Session", slog.Error(err))
} else {
s.Logger.Info(s.Context(), "recv done on Session")
}
return
}
select {
case ch <- req:
continue
case <-done:
return
}
}
}()
return ch
}
func (s *Session) handleRequests() error {
done := make(chan struct{})
defer close(done)
requests := s.requestReader(done)
planned := false
for req := range requests {
if req.GetCancel() != nil {
s.Logger.Warn(s.Context(), "ignoring cancel before request or after complete")
continue
}
resp := &proto.Response{}
if parse := req.GetParse(); parse != nil {
if !s.initialized {
// Files must be initialized before parsing.
return xerrors.New("cannot parse before successful init")
}
r := &request[*proto.ParseRequest, *proto.ParseComplete]{
req: parse,
session: s,
serverFn: s.server.Parse,
cancels: requests,
}
complete, err := r.do()
if err != nil {
return err
}
// Handle README centrally, so that individual provisioners don't need to mess with it.
readme, err := os.ReadFile(s.Files.ReadmeFilePath())
if err == nil {
complete.Readme = readme
} else {
s.Logger.Debug(s.Context(), "failed to parse readme (missing ok)", slog.Error(err))
}
resp.Type = &proto.Response_Parse{Parse: complete}
}
if init := req.GetInit(); init != nil {
if s.initialized {
return xerrors.New("cannot init more than once per session")
}
initResp, err := s.handleInitRequest(init, requests)
if err != nil {
return err
}
resp.Type = &proto.Response_Init{Init: initResp}
}
if plan := req.GetPlan(); plan != nil {
if !s.initialized {
return xerrors.New("cannot plan before successful init")
}
planResp, err := s.handlePlanRequest(plan, requests)
if err != nil {
return err
}
if planResp.Error == "" {
planned = true
}
resp.Type = &proto.Response_Plan{Plan: planResp}
}
if apply := req.GetApply(); apply != nil {
if !planned {
return xerrors.New("cannot apply before successful plan")
}
r := &request[*proto.ApplyRequest, *proto.ApplyComplete]{
req: apply,
session: s,
serverFn: s.server.Apply,
cancels: requests,
}
complete, err := r.do()
if err != nil {
return err
}
resp.Type = &proto.Response_Apply{Apply: complete}
}
if graph := req.GetGraph(); graph != nil {
if !s.initialized {
return xerrors.New("cannot graph before successful init")
}
r := &request[*proto.GraphRequest, *proto.GraphComplete]{
req: graph,
session: s,
serverFn: s.server.Graph,
cancels: requests,
}
complete, err := r.do()
if err != nil {
return err
}
resp.Type = &proto.Response_Graph{Graph: complete}
}
err := s.stream.Send(resp)
if err != nil {
return xerrors.Errorf("send response: %w", err)
}
}
return nil
}
// fromChannel implements the `Recv` api using an underlying channel for
// downloading files.
type fromChannel struct {
requests <-chan *proto.Request
}
func (f *fromChannel) Recv() (*proto.FileUpload, error) {
next, ok := <-f.requests
if !ok {
return nil, xerrors.New("channel closed")
}
// Only file download messages are expected here.
file := next.GetFile()
if file == nil {
return nil, xerrors.Errorf("expected file upload")
}
return file, nil
}
func (s *Session) handleInitRequest(init *proto.InitRequest, requests <-chan *proto.Request) (*proto.InitComplete, error) {
req := &InitRequest{
InitRequest: init,
ModuleArchive: nil,
}
if len(init.GetInitialModuleTarHash()) > 0 {
file, err := HandleReceivingDataUpload(&fromChannel{requests: requests})
if err != nil {
return nil, err
}
data, err := file.Complete()
if err != nil {
return nil, err
}
req.ModuleArchive = data
}
r := &request[*InitRequest, *proto.InitComplete]{
req: req,
session: s,
serverFn: s.server.Init,
cancels: requests,
}
complete, err := r.do()
if err != nil {
return nil, err
}
if complete.Error != "" {
return complete, nil
}
// If the size of the complete message is too large, we need to stream the module files separately.
if protobuf.Size(&proto.Response{Type: &proto.Response_Init{Init: complete}}) > drpcsdk.MaxMessageSize {
// It is likely the modules that is pushing the message size over the limit.
// Send the modules over a stream of messages instead.
s.Logger.Info(s.Context(), "plan response too large, sending modules as stream",
slog.F("size_bytes", len(complete.ModuleFiles)),
)
dataUp, chunks, err := proto.BytesToDataUpload(proto.DataUploadType_UPLOAD_TYPE_MODULE_FILES, complete.ModuleFiles)
if err != nil {
complete.Error = fmt.Sprintf("prepare module files upload: %s", err.Error())
} else {
complete.ModuleFiles = nil // sent over the stream
complete.ModuleFilesHash = dataUp.DataHash
err := s.stream.Send(&proto.Response{Type: &proto.Response_DataUpload{DataUpload: dataUp}})
if err != nil {
complete.Error = fmt.Sprintf("send data upload: %s", err.Error())
} else {
for i, chunk := range chunks {
err := s.stream.Send(&proto.Response{Type: &proto.Response_ChunkPiece{ChunkPiece: chunk}})
if err != nil {
complete.Error = fmt.Sprintf("send data piece upload %d/%d: %s", i, dataUp.Chunks, err.Error())
break
}
}
}
}
}
s.initialized = true
return complete, nil
}
func (s *Session) handlePlanRequest(plan *proto.PlanRequest, requests <-chan *proto.Request) (*proto.PlanComplete, error) {
r := &request[*proto.PlanRequest, *proto.PlanComplete]{
req: plan,
session: s,
serverFn: s.server.Plan,
cancels: requests,
}
complete, err := r.do()
if err != nil {
return nil, err
}
return complete, nil
}
type Session struct {
Logger slog.Logger
Files tfpath.Layout
Config *proto.Config
// initialized indicates if an init was run.
// Required for plan/apply.
initialized bool
server Server
stream proto.DRPCProvisioner_SessionStream
logLevel int32
}
func (s *Session) Context() context.Context {
return s.stream.Context()
}
func (s *Session) ProvisionLog(level proto.LogLevel, output string) {
if int32(level) < s.logLevel {
return
}
err := s.stream.Send(&proto.Response{Type: &proto.Response_Log{Log: &proto.Log{
Level: level,
Output: output,
}}})
if err != nil {
s.Logger.Error(s.Context(), "failed to transmit log",
slog.F("level", level), slog.F("output", output))
}
}
type pRequest interface {
*proto.ParseRequest | *InitRequest | *proto.PlanRequest | *proto.ApplyRequest | *proto.GraphRequest
}
type pComplete interface {
*proto.ParseComplete | *proto.InitComplete | *proto.PlanComplete | *proto.ApplyComplete | *proto.GraphComplete
}
// request processes a single request call to the Server and returns its complete result, while also processing cancel
// requests from the daemon. Provisioner implementations read from canceledOrComplete to be asynchronously informed
// of cancel.
type request[R pRequest, C pComplete] struct {
req R
session *Session
cancels <-chan *proto.Request
serverFn func(*Session, R, <-chan struct{}) C
}
func (r *request[R, C]) do() (C, error) {
canceledOrComplete := make(chan struct{})
result := make(chan C)
go func() {
c := r.serverFn(r.session, r.req, canceledOrComplete)
result <- c
}()
select {
case req := <-r.cancels:
close(canceledOrComplete)
// wait for server to complete the request, even though we have canceled,
// so that we can't start a new request, and so that if the job was close
// to completion and the cancel was ignored, we return to complete.
c := <-result
// verify we got a cancel instead of another request or closed channel --- which is an error!
if req.GetCancel() != nil {
return c, nil
}
if req == nil {
return c, xerrors.New("got nil while old request still processing")
}
return c, xerrors.Errorf("got new request %T while old request still processing", req.Type)
case c := <-result:
close(canceledOrComplete)
return c, nil
}
}