forked from loft-sh/devpod
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathproxy_client.go
More file actions
439 lines (372 loc) · 9.88 KB
/
proxy_client.go
File metadata and controls
439 lines (372 loc) · 9.88 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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package clientimplementation
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/blang/semver/v4"
"github.com/gofrs/flock"
"github.com/loft-sh/api/v4/pkg/devpod"
"github.com/skevetter/devpod/pkg/client"
"github.com/skevetter/devpod/pkg/config"
devpodlog "github.com/skevetter/devpod/pkg/log"
"github.com/skevetter/devpod/pkg/options"
platformclient "github.com/skevetter/devpod/pkg/platform/client"
"github.com/skevetter/devpod/pkg/provider"
"github.com/skevetter/log"
)
var (
DevPodDebug = "DEVPOD_DEBUG"
DevPodPlatformOptions = "DEVPOD_PLATFORM_OPTIONS"
DevPodFlagsUp = "DEVPOD_FLAGS_UP"
DevPodFlagsSsh = "DEVPOD_FLAGS_SSH"
DevPodFlagsDelete = "DEVPOD_FLAGS_DELETE"
DevPodFlagsStatus = "DEVPOD_FLAGS_STATUS"
)
func NewProxyClient(devPodConfig *config.Config, prov *provider.ProviderConfig, workspace *provider.Workspace, log log.Logger) (client.ProxyClient, error) {
return &proxyClient{
devPodConfig: devPodConfig,
config: prov,
workspace: workspace,
log: log,
}, nil
}
type proxyClient struct {
m sync.Mutex
workspaceLockOnce sync.Once
workspaceLock *flock.Flock
devPodConfig *config.Config
config *provider.ProviderConfig
workspace *provider.Workspace
log log.Logger
}
func (s *proxyClient) Lock(ctx context.Context) error {
s.initLock()
// try to lock workspace
s.log.Debugf("Acquire workspace lock...")
err := tryLock(ctx, s.workspaceLock, "workspace", s.log)
if err != nil {
return fmt.Errorf("error locking workspace %w", err)
}
s.log.Debugf("Acquired workspace lock...")
return nil
}
func (s *proxyClient) Unlock() {
s.initLock()
// try to unlock workspace
err := s.workspaceLock.Unlock()
if err != nil {
s.log.Warnf("Error unlocking workspace: %v", err)
}
}
func tryLock(ctx context.Context, lock *flock.Flock, name string, log log.Logger) error {
done := printLogMessagePeriodically(fmt.Sprintf("Trying to lock %s, seems like another process is running that blocks this %s", name, name), log)
defer close(done)
now := time.Now()
for time.Since(now) < time.Minute*5 {
locked, err := lock.TryLock()
if err != nil {
return err
} else if locked {
return nil
}
select {
case <-time.After(time.Second):
continue
case <-ctx.Done():
return ctx.Err()
}
}
return fmt.Errorf("timed out waiting to lock %s, seems like there is another process running on this machine that blocks it", name)
}
func (s *proxyClient) initLock() {
s.workspaceLockOnce.Do(func() {
s.m.Lock()
defer s.m.Unlock()
// get locks dir
workspaceLocksDir, err := provider.GetLocksDir(s.workspace.Context)
if err != nil {
panic(fmt.Errorf("get workspaces dir %w", err))
}
_ = os.MkdirAll(workspaceLocksDir, 0777)
// create workspace lock
s.workspaceLock = flock.New(filepath.Join(workspaceLocksDir, s.workspace.ID+".workspace.lock"))
})
}
func (s *proxyClient) Provider() string {
return s.config.Name
}
func (s *proxyClient) Workspace() string {
s.m.Lock()
defer s.m.Unlock()
return s.workspace.ID
}
func (s *proxyClient) WorkspaceConfig() *provider.Workspace {
s.m.Lock()
defer s.m.Unlock()
return provider.CloneWorkspace(s.workspace)
}
func (s *proxyClient) Context() string {
return s.workspace.Context
}
func (s *proxyClient) RefreshOptions(ctx context.Context, userOptionsRaw []string, reconfigure bool) error {
s.m.Lock()
defer s.m.Unlock()
userOptions, err := provider.ParseOptions(userOptionsRaw)
if err != nil {
return fmt.Errorf("parse options %w", err)
}
workspace, err := options.ResolveAndSaveOptionsProxy(ctx, s.devPodConfig, s.config, s.workspace, userOptions, s.log)
if err != nil {
return err
}
if reconfigure {
err := s.updateInstance(ctx)
if err != nil {
return err
}
}
s.workspace = workspace
return nil
}
func (s *proxyClient) Create(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
err := RunCommandWithBinaries(
ctx,
"createWorkspace",
s.config.Exec.Proxy.Create.Workspace,
s.workspace.Context,
s.workspace,
nil,
s.devPodConfig.ProviderOptions(s.config.Name),
s.config,
nil,
stdin,
stdout,
stderr,
s.log)
if err != nil {
return fmt.Errorf("create remote workspace %w", err)
}
return nil
}
func (s *proxyClient) Up(ctx context.Context, opt client.UpOptions) error {
writer, _ := devpodlog.PipeJSONStream(s.log.ErrorStreamOnly())
defer func() { _ = writer.Close() }()
opts := EncodeOptions(opt.CLIOptions, DevPodFlagsUp)
if opt.Debug {
opts["DEBUG"] = "true"
}
// check if the provider is outdated
providerOptions := s.devPodConfig.ProviderOptions(s.config.Name)
if providerOptions["LOFT_CONFIG"].Value != "" {
baseClient, err := platformclient.InitClientFromPath(ctx, providerOptions["LOFT_CONFIG"].Value)
if err != nil {
return fmt.Errorf("error initializing platform client %w", err)
}
version, err := baseClient.Version()
if err != nil {
return fmt.Errorf("error retrieving platform version %w", err)
}
// check if the version is lower than v4.3.0-devpod.alpha.19
parsedVersion, err := semver.Parse(strings.TrimPrefix(version.DevPodVersion, "v"))
if err != nil {
return fmt.Errorf("error parsing platform version %w", err)
}
// if devpod version is greater than 0.7.0 we error here
if parsedVersion.GE(semver.MustParse("0.6.99")) {
return fmt.Errorf("you are using an outdated provider version for this platform. Please disconnect and reconnect the platform to update the provider")
}
}
err := RunCommandWithBinaries(
ctx,
"up",
s.config.Exec.Proxy.Up,
s.workspace.Context,
s.workspace,
nil,
providerOptions,
s.config,
opts,
opt.Stdin,
opt.Stdout,
writer,
s.log.ErrorStreamOnly(),
)
if err != nil {
return fmt.Errorf("error running devpod up %w", err)
}
return nil
}
func (s *proxyClient) Ssh(ctx context.Context, opt client.SshOptions) error {
writer, _ := devpodlog.PipeJSONStream(s.log.ErrorStreamOnly())
defer func() { _ = writer.Close() }()
err := RunCommandWithBinaries(
ctx,
"ssh",
s.config.Exec.Proxy.Ssh,
s.workspace.Context,
s.workspace,
nil,
s.devPodConfig.ProviderOptions(s.config.Name),
s.config,
EncodeOptions(opt, DevPodFlagsSsh),
opt.Stdin,
opt.Stdout,
writer,
s.log.ErrorStreamOnly(),
)
if err != nil {
return err
}
return nil
}
func (s *proxyClient) Delete(ctx context.Context, opt client.DeleteOptions) error {
s.m.Lock()
defer s.m.Unlock()
writer, _ := devpodlog.PipeJSONStream(s.log.ErrorStreamOnly())
defer func() { _ = writer.Close() }()
var gracePeriod *time.Duration
if opt.GracePeriod != "" {
duration, err := time.ParseDuration(opt.GracePeriod)
if err == nil {
gracePeriod = &duration
}
}
// kill the command after the grace period
if gracePeriod != nil {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, *gracePeriod)
defer cancel()
}
err := RunCommandWithBinaries(
ctx,
"delete",
s.config.Exec.Proxy.Delete,
s.workspace.Context,
s.workspace,
nil,
s.devPodConfig.ProviderOptions(s.config.Name),
s.config,
EncodeOptions(opt, DevPodFlagsDelete),
nil,
writer,
writer,
s.log,
)
if err != nil {
if !opt.Force {
return fmt.Errorf("error deleting workspace %w", err)
}
s.log.Errorf("Error deleting workspace: %v", err)
}
return DeleteWorkspaceFolder(DeleteWorkspaceFolderParams{
Context: s.workspace.Context,
WorkspaceID: s.workspace.ID,
SSHConfigPath: s.workspace.SSHConfigPath,
SSHConfigIncludePath: s.workspace.SSHConfigIncludePath,
}, s.log)
}
func (s *proxyClient) Stop(ctx context.Context, opt client.StopOptions) error {
s.m.Lock()
defer s.m.Unlock()
writer, _ := devpodlog.PipeJSONStream(s.log.ErrorStreamOnly())
defer func() { _ = writer.Close() }()
err := RunCommandWithBinaries(
ctx,
"stop",
s.config.Exec.Proxy.Stop,
s.workspace.Context,
s.workspace,
nil,
s.devPodConfig.ProviderOptions(s.config.Name),
s.config,
nil,
nil,
writer,
writer,
s.log,
)
if err != nil {
return fmt.Errorf("error stopping container %w", err)
}
return nil
}
func (s *proxyClient) Status(ctx context.Context, options client.StatusOptions) (client.Status, error) {
s.m.Lock()
defer s.m.Unlock()
stdout := &bytes.Buffer{}
buf := &bytes.Buffer{}
err := RunCommandWithBinaries(
ctx,
"status",
s.config.Exec.Proxy.Status,
s.workspace.Context,
s.workspace,
nil,
s.devPodConfig.ProviderOptions(s.config.Name),
s.config,
EncodeOptions(options, DevPodFlagsStatus),
nil,
io.MultiWriter(stdout, buf),
buf,
s.log.ErrorStreamOnly(),
)
if err != nil {
return client.StatusNotFound, fmt.Errorf("error retrieving container status: %s%w", buf.String(), err)
}
devpodlog.ReadJSONStream(bytes.NewReader(buf.Bytes()), s.log.ErrorStreamOnly())
status := &client.WorkspaceStatus{}
err = json.Unmarshal(stdout.Bytes(), status)
if err != nil {
return client.StatusNotFound, fmt.Errorf("error parsing proxy command response: %s%w", stdout.String(), err)
}
// parse status
return client.ParseStatus(status.State)
}
func (s *proxyClient) updateInstance(ctx context.Context) error {
err := RunCommandWithBinaries(
ctx,
"updateWorkspace",
s.config.Exec.Proxy.Update.Workspace,
s.workspace.Context,
s.workspace,
nil,
s.devPodConfig.ProviderOptions(s.config.Name),
s.config,
nil,
os.Stdin,
os.Stdout,
os.Stderr,
s.log.ErrorStreamOnly(),
)
if err != nil {
return err
}
return nil
}
func EncodeOptions(options any, name string) map[string]string {
raw, _ := json.Marshal(options)
return map[string]string{
name: string(raw),
}
}
func DecodeOptionsFromEnv(name string, into any) (bool, error) {
raw := os.Getenv(name)
if raw == "" {
return false, nil
}
return true, json.Unmarshal([]byte(raw), into)
}
func DecodePlatformOptionsFromEnv(into *devpod.PlatformOptions) error {
raw := os.Getenv(DevPodPlatformOptions)
if raw == "" {
return nil
}
return json.Unmarshal([]byte(raw), into)
}