-
Notifications
You must be signed in to change notification settings - Fork 378
/
serverless.go
1474 lines (1321 loc) · 48.5 KB
/
serverless.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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2018 The Doctl Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package do
import (
"context"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/apache/openwhisk-client-go/whisk"
"github.com/digitalocean/doctl"
"github.com/digitalocean/doctl/pkg/extract"
"github.com/digitalocean/godo"
"github.com/pkg/browser"
"gopkg.in/yaml.v3"
)
// ServerlessCredentials models what is stored in credentials.json for use by the plugin and nim.
// It is also the type returned by the GetServerlessNamespace function.
type ServerlessCredentials struct {
APIHost string `json:"currentHost"`
Namespace string `json:"currentNamespace"`
Label string `json:"label"`
Credentials map[string]map[string]ServerlessCredential `json:"credentials"`
}
// ServerlessCredential is the type of an individual entry in ServerlessCredentials
type ServerlessCredential struct {
Auth string `json:"api_key"`
}
// OutputNamespace is the type of the "namespace" member of the response to /api/v2/functions/sandbox
// and /api/v2/functions/namespaces APIs. Only relevant fields unmarshalled
type OutputNamespace struct {
Namespace string `json:"namespace"`
APIHost string `json:"api_host"`
UUID string `json:"uuid"`
Key string `json:"key"`
Label string `json:"label"`
Region string `json:"Region"`
}
// FunctionParameter is the type of a parameter in the response body of action.get. We do our
// own JSON unmarshaling of these because the go OpenWhisk client doesn't include the "init" and
// "encryption" members, of which at least "init" is needed.
type FunctionParameter struct {
Key string `json:"key"`
Value string `json:"value"`
Init bool `json:"init"`
Encryption string `json:"encryption"`
}
// FunctionParameterReparse is a partial remapping of whisk.Action so that the parameters
// are declared as FunctionParameter rather than whisk.KeyValue.
type FunctionParameterReparse struct {
Parameters []FunctionParameter `json:"parameters"`
}
// NamespaceResponse is the type of the response body for /api/v2/functions/sandbox (POST) and
// /api/v2/functions/namespaces/<nsName> (GET)
type NamespaceResponse struct {
Namespace OutputNamespace `json:"namespace"`
}
// NamespaceListResponse is the type of the response body for /api/v2/functions/namespaces (GET)
type NamespaceListResponse struct {
Namespaces []OutputNamespace `json:"namespaces"`
}
// newNamespaceRequest is the type of the POST body for requesting a new namespace
type newNamespaceRequest struct {
Namespace inputNamespace `json:"namespace"`
}
// inputNamespace is the reduced representation of a namespace used when requesting a new one
type inputNamespace struct {
Label string `json:"label"`
Region string `json:"Region"`
}
// ServerlessRuntime is the type of a runtime entry returned by the API host controller
// of the serverless cluster.
// Only relevant fields unmarshalled
type ServerlessRuntime struct {
Default bool `json:"default"`
Deprecated bool `json:"deprecated"`
Kind string `json:"kind"`
}
// ServerlessHostInfo is the type of the host information return from the API host controller
// of the serverless cluster.
// Only relevant fields unmarshaled.
type ServerlessHostInfo struct {
Runtimes map[string][]ServerlessRuntime `json:"runtimes"`
}
// ServerlessProject ...
type ServerlessProject struct {
ProjectPath string `json:"project_path"`
ConfigPath string `json:"config"`
Packages string `json:"packages"`
Env string `json:"env"`
Strays []string `json:"strays"`
}
// ServerlessSpec describes a project.yml spec
// reference: https://docs.nimbella.com/configuration/
type ServerlessSpec struct {
Parameters map[string]interface{} `json:"parameters,omitempty"`
Environment map[string]interface{} `json:"environment,omitempty"`
Packages []*ServerlessPackage `json:"packages,omitempty"`
}
// ServerlessPackage ...
type ServerlessPackage struct {
Name string `json:"name,omitempty"`
Shared bool `json:"shared,omitempty"`
Environment map[string]interface{} `json:"environment,omitempty"`
Parameters map[string]interface{} `json:"parameters,omitempty"`
Annotations map[string]interface{} `json:"annotations,omitempty"`
Functions []*ServerlessFunction `json:"functions,omitempty"`
}
// ServerlessFunction ...
type ServerlessFunction struct {
Name string `json:"name,omitempty"`
Binary bool `json:"binary,omitempty"`
Main string `json:"main,omitempty"`
Runtime string `json:"runtime,omitempty"`
// `web` can be either true or "raw". We use interface{} to support both types. If we start consuming the value we
// should probably define a custom type with proper validation.
Web interface{} `json:"web,omitempty"`
WebSecure interface{} `json:"webSecure,omitempty" yaml:"webSecure"`
Parameters map[string]interface{} `json:"parameters,omitempty"`
Environment map[string]interface{} `json:"environment,omitempty"`
Annotations map[string]interface{} `json:"annotations,omitempty"`
Limits map[string]int `json:"limits,omitempty"`
}
// ProjectMetadata describes the nim project:get-metadata output structure.
type ProjectMetadata struct {
ServerlessSpec
UnresolvedVariables []string `json:"unresolvedVariables,omitempty"`
}
// ServerlessTriggerListResponse is the form returned by the list triggers API
type ServerlessTriggerListResponse struct {
Triggers []ServerlessTrigger `json:"Triggers,omitempty"`
}
// ServerlessTriggerGetResponse is the form returned by the get trigger API
type ServerlessTriggerGetResponse struct {
Trigger ServerlessTrigger `json:"Trigger,omitempty"`
}
type UpdateTriggerRequest struct {
IsEnabled bool `json:"is_enabled"`
ScheduledDetails *TriggerScheduledDetails `json:"scheduled_details,omitempty"`
}
// ServerlessTrigger is the form used in list and get responses by the triggers API
type ServerlessTrigger struct {
Namespace string `json:"namespace,omitempty"`
Function string `json:"function,omitempty"`
Type string `json:"type,omitempty"`
Name string `json:"name,omitempty"`
IsEnabled bool `json:"is_enabled"`
CreatedAt time.Time `json:"created_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
ScheduledDetails *TriggerScheduledDetails `json:"scheduled_details,omitempty"`
ScheduledRuns *TriggerScheduledRuns `json:"scheduled_runs,omitempty"`
}
type TriggerScheduledDetails struct {
Cron string `json:"cron,omitempty"`
Body map[string]interface{} `json:"body,omitempty"`
}
type TriggerScheduledRuns struct {
LastRunAt *time.Time `json:"last_run_at,omitempty"`
NextRunAt *time.Time `json:"next_run_at,omitempty"`
}
// ServerlessService is an interface for interacting with the sandbox plugin,
// with the namespaces service, and with the serverless cluster controller.
type ServerlessService interface {
Cmd(string, []string) (*exec.Cmd, error)
Exec(*exec.Cmd) (ServerlessOutput, error)
Stream(*exec.Cmd) error
GetServerlessNamespace(context.Context) (ServerlessCredentials, error)
ListNamespaces(context.Context) (NamespaceListResponse, error)
GetNamespace(context.Context, string) (ServerlessCredentials, error)
GetNamespaceFromCluster(string, string) (string, error)
CreateNamespace(context.Context, string, string) (ServerlessCredentials, error)
DeleteNamespace(context.Context, string) error
CleanNamespace() error
ListTriggers(context.Context, string) ([]ServerlessTrigger, error)
GetTrigger(context.Context, string) (ServerlessTrigger, error)
UpdateTrigger(context.Context, string, *UpdateTriggerRequest) (ServerlessTrigger, error)
DeleteTrigger(context.Context, string) error
WriteCredentials(ServerlessCredentials) error
ReadCredentials() (ServerlessCredentials, error)
GetHostInfo(string) (ServerlessHostInfo, error)
CheckServerlessStatus() error
InstallServerless(string, bool) error
ListPackages() ([]whisk.Package, error)
DeletePackage(string, bool) error
GetFunction(string, bool) (whisk.Action, []FunctionParameter, error)
ListFunctions(string, int, int) ([]whisk.Action, error)
DeleteFunction(string, bool) error
InvokeFunction(string, interface{}, bool, bool) (interface{}, error)
InvokeFunctionViaWeb(string, interface{}) error
ListActivations(whisk.ActivationListOptions) ([]whisk.Activation, error)
GetActivationCount(whisk.ActivationCountOptions) (whisk.ActivationCount, error)
GetActivation(string) (whisk.Activation, error)
GetActivationLogs(string) (whisk.Activation, error)
GetActivationResult(string) (whisk.Response, error)
GetConnectedAPIHost() (string, error)
ReadProject(*ServerlessProject, []string) (ServerlessOutput, error)
WriteProject(ServerlessProject) (string, error)
SetEffectiveCredentials(auth string, apihost string)
CredentialsPath() string
}
type serverlessService struct {
serverlessJs string
serverlessDir string
credsDir string
node string
userAgent string
accessToken string
client *godo.Client
owClient *whisk.Client
owConfig *whisk.Config
}
const (
// Minimum required version of the functions deployer plugin code.
minServerlessVersion = "5.0.18"
// The version of nodejs to download alongsize the plugin download.
nodeVersion = "v16.13.0"
// credsDir is the directory under the sandbox where all credentials are stored.
// It in turn has a subdirectory for each access token employed (formed as a prefix of the token).
credsDir = "creds"
// CredentialsFile is the name of the file where the sandbox plugin stores OpenWhisk credentials.
CredentialsFile = "credentials.json"
)
const (
/*
The following are forbidden configurations for a serverless project.
Validation ensures these are the configurations are not set in the project.yml
Some of these configs can exist at multiple levels (i.e. Namespace, package, and action)
*/
// ForbiddenConfigShared ...
ForbiddenConfigShared = "shared"
// ForbiddenConfigWebSecure ...
ForbiddenConfigWebSecure = "webSecure"
// ForbiddenConfigSequence ...
ForbiddenConfigSequence = "sequence"
// ForbiddenConfigProvideAPIKeyAnnotation ...
ForbiddenConfigProvideAPIKeyAnnotation = "provideAPIKeyAnnotation"
// ForbiddenConfigRequireWhiskAuthAnnotation ...
ForbiddenConfigRequireWhiskAuthAnnotation = "provideWhiskAuthAnnotation"
/*
These are values for forbidden annotations. Not all annotations are forbidden
*/
// ForbiddenAnnotationProvideAPIKey ...
ForbiddenAnnotationProvideAPIKey = "provide-api-key"
// ForbiddenAnnotationRequireWhiskAuth ...
ForbiddenAnnotationRequireWhiskAuth = "require-whisk-auth"
)
var _ ServerlessService = &serverlessService{}
var (
// ErrServerlessNotInstalled is the error returned to users when the sandbox is not installed.
ErrServerlessNotInstalled = errors.New("serverless support is not installed (use `doctl serverless install`)")
// ErrServerlessNeedsUpgrade is the error returned to users when the sandbox is at too low a version
ErrServerlessNeedsUpgrade = errors.New("serverless support needs to be upgraded (use `doctl serverless upgrade`)")
// ErrServerlessNotConnected is the error returned to users when the sandbox is not connected to a namespace
ErrServerlessNotConnected = errors.New("serverless support is installed but not connected to a functions namespace (use `doctl serverless connect`)")
)
// ServerlessOutput contains the output returned from calls to the sandbox plugin.
type ServerlessOutput struct {
Table []map[string]interface{} `json:"table,omitempty"`
Captured []string `json:"captured,omitempty"`
Formatted []string `json:"formatted,omitempty"`
Entity interface{} `json:"entity,omitempty"`
Error string `json:"error,omitempty"`
}
// NewServerlessService returns a configured ServerlessService.
func NewServerlessService(client *godo.Client, usualServerlessDir string, accessToken string) ServerlessService {
nodeBin := "node"
if runtime.GOOS == "windows" {
nodeBin = "node.exe"
}
// The following is needed to support snap installation. For snap, the installation directory
// is relocated to a snap-managed area. That area is not user-writable, so, the credsDir location
// is always computed relative to the normal installation area (usualServerlessDir).
serverlessDir := os.Getenv("OVERRIDE_SANDBOX_DIR")
if serverlessDir == "" {
serverlessDir = usualServerlessDir
}
credsToken := HashAccessToken(accessToken)
return &serverlessService{
serverlessJs: filepath.Join(serverlessDir, "sandbox.js"),
serverlessDir: serverlessDir,
credsDir: GetCredentialDirectory(credsToken, usualServerlessDir),
node: filepath.Join(serverlessDir, nodeBin),
userAgent: fmt.Sprintf("doctl/%s serverless/%s", doctl.DoitVersion.String(), minServerlessVersion),
client: client,
owClient: nil,
accessToken: accessToken,
}
}
// HashAccessToken converts a DO access token string into a shorter but suitably random string
// via hashing. This is used to form part of the path for storing OpenWhisk credentials
func HashAccessToken(token string) string {
hasher := sha1.New()
hasher.Write([]byte(token))
sha := hasher.Sum(nil)
return hex.EncodeToString(sha[:4])
}
// InitWhisk is an on-demand initializer for the OpenWhisk client, called when that client
// is needed.
func initWhisk(s *serverlessService) error {
if s.owClient != nil {
return nil
}
var config *whisk.Config
if s.owConfig != nil {
config = s.owConfig
} else {
err := s.CheckServerlessStatus()
if err != nil {
return err
}
creds, err := s.ReadCredentials()
if err != nil {
return err
}
credential := creds.Credentials[creds.APIHost][creds.Namespace]
config = &whisk.Config{Host: creds.APIHost, AuthToken: credential.Auth}
}
client, err := whisk.NewClient(http.DefaultClient, config)
if err != nil {
return err
}
s.owClient = client
return nil
}
// SetEffectiveCredentials is used in low-level scenarios when we want to bypass normal credentialing.
// For example, doing things to serverless clusters that are not yet in full production.
func (s *serverlessService) SetEffectiveCredentials(auth string, apihost string) {
s.owConfig = &whisk.Config{Host: apihost, AuthToken: auth}
s.owClient = nil // ensure fresh initialization next time
}
func (s *serverlessService) CheckServerlessStatus() error {
_, err := os.Stat(s.serverlessDir)
if os.IsNotExist(err) {
return ErrServerlessNotInstalled
}
if !serverlessUptodate(s.serverlessDir) {
return ErrServerlessNeedsUpgrade
}
if !isServerlessConnected(s.credsDir) {
return ErrServerlessNotConnected
}
return nil
}
// InstallServerless is the common subroutine for both serverless install and serverless upgrade
func (s *serverlessService) InstallServerless(leafCredsDir string, upgrading bool) error {
serverlessDir := s.serverlessDir
// Make a temporary directory for use during the install.
// Note: we don't let this be allocated in the system temporaries area because
// that might be on a separate file system, meaning that the final install step
// will require an additional copy rather than a simple rename.
os.Mkdir(filepath.Dir(serverlessDir), 0700) // in case using config dir and it doesn't exist yet
tmp, err := ioutil.TempDir(filepath.Dir(serverlessDir), "sbx-install")
if err != nil {
return err
}
// Download the nodejs tarball for this os and architecture
fmt.Print("Downloading...")
goos := runtime.GOOS
arch := runtime.GOARCH
nodeBin := "node"
if arch == "amd64" {
arch = "x64"
}
if arch == "386" {
if goos == "linux" {
return errors.New("serverless support is not available for 32-bit linux")
}
arch = "x86"
}
if goos == "windows" {
goos = "win"
nodeBin = "node.exe"
}
var (
nodeURL string
nodeFileName string
nodeDir string
)
// Download nodejs only if necessary
if !upgrading || !canReuseNode(serverlessDir, nodeBin) {
nodeDir = fmt.Sprintf("node-%s-%s-%s", nodeVersion, goos, arch)
nodeURL = fmt.Sprintf("https://nodejs.org/dist/%s/%s.tar.gz", nodeVersion, nodeDir)
nodeFileName = filepath.Join(tmp, "node-install.tar.gz")
if goos == "win" {
nodeURL = fmt.Sprintf("https://nodejs.org/dist/%s/%s.zip", nodeVersion, nodeDir)
nodeFileName = filepath.Join(tmp, "node-install.zip")
}
err = download(nodeURL, nodeFileName)
if err != nil {
return err
}
}
// Download the fat tarball with the nim CLI, deployer, and sandbox bridge
// TODO do these need to be arch-specific? Currently assuming not.
URL := fmt.Sprintf("https://do-serverless-tools.nyc3.digitaloceanspaces.com/doctl-sandbox-%s.tar.gz",
GetMinServerlessVersion())
sandboxFileName := filepath.Join(tmp, "doctl-sandbox.tar.gz")
err = download(URL, sandboxFileName)
if err != nil {
return err
}
// Exec the Extract utility at least once to unpack the fat tarball and possibly a second time if
// node was downloaded. If node was not downloaded, just move the existing binary into place.
fmt.Print("Unpacking...")
err = extract.Extract(sandboxFileName, tmp)
if err != nil {
return err
}
if nodeFileName != "" {
err = extract.Extract(nodeFileName, tmp)
if err != nil {
return err
}
}
// Move artifacts to final location
fmt.Print("Installing...")
srcPath := filepath.Join(tmp, "sandbox")
if upgrading {
// Preserve credentials by moving them from target (which will be replaced) to source.
err = PreserveCreds(leafCredsDir, srcPath, serverlessDir)
if err != nil {
return err
}
// Preserve existing node if necessary
if nodeFileName == "" {
// Node was not downloaded
err = moveExistingNode(serverlessDir, srcPath, nodeBin)
if err != nil {
return err
}
}
} else {
// Make new empty credentials directory
emptyCreds := filepath.Join(srcPath, credsDir)
err = os.MkdirAll(emptyCreds, 0700)
if err != nil {
return nil
}
// Create the sandbox directory if necessary.
err := os.MkdirAll(serverlessDir, 0755)
if err != nil {
return err
}
}
// Remove former serverlessDir before moving in the new one
err = os.RemoveAll(serverlessDir)
if err != nil {
return err
}
err = os.Rename(srcPath, serverlessDir)
if err != nil {
return err
}
if nodeFileName != "" {
if goos == "win" {
srcPath = filepath.Join(tmp, nodeDir, nodeBin)
} else {
// Additional nesting in non-windows case
srcPath = filepath.Join(tmp, nodeDir, "bin", nodeBin)
}
destPath := filepath.Join(serverlessDir, nodeBin)
err = os.Rename(srcPath, destPath)
if err != nil {
return err
}
}
// Clean up temp directory
fmt.Print("Cleaning up...")
os.RemoveAll(tmp) // Best effort, ignore error
fmt.Println("\nDone")
return nil
}
// Cmd builds an *exec.Cmd for calling into the sandbox plugin.
func (s *serverlessService) Cmd(command string, args []string) (*exec.Cmd, error) {
args = append([]string{s.serverlessJs, command}, args...)
cmd := exec.Command(s.node, args...)
cmd.Env = append(os.Environ(), "NIMBELLA_DIR="+s.credsDir, "NIM_USER_AGENT="+s.userAgent, "DO_API_KEY="+s.accessToken)
// If DEBUG is specified, we need to open up stderr for that stream. The stdout stream
// will continue to work for returning structured results.
if os.Getenv("DEBUG") != "" {
cmd.Stderr = os.Stderr
}
return cmd, nil
}
// Exec executes an *exec.Cmd and captures its output in a ServerlessOutput.
func (s *serverlessService) Exec(cmd *exec.Cmd) (ServerlessOutput, error) {
output, err := cmd.Output()
if err != nil {
// Ignore "errors" that are just non-zero exit. The
// serverless uses this as a secondary indicator but the output
// is still trustworthy (and includes error information inline)
if _, ok := err.(*exec.ExitError); !ok {
// Real error of some sort
return ServerlessOutput{}, err
}
}
var result ServerlessOutput
err = json.Unmarshal(output, &result)
if err != nil {
return ServerlessOutput{}, err
}
// Result is sound JSON but also has an error field, meaning that something did
// go wrong. In this case we return the actual output but also the distinguished
// error return. Most callers will process only the error, which is fine. Sometimes,
// however, there is other information that can be useful as part of the error report.
if len(result.Error) > 0 {
return result, errors.New(result.Error)
}
// Result is both sound and error free
return result, nil
}
// Stream is like Exec but assumes that output will not be captured and can be streamed.
func (s *serverlessService) Stream(cmd *exec.Cmd) error {
return cmd.Run()
}
// GetServerlessNamespace returns the credentials of the one serverless namespace assigned to
// the invoking doctl context.
func (s *serverlessService) GetServerlessNamespace(ctx context.Context) (ServerlessCredentials, error) {
path := "v2/functions/sandbox"
req, err := s.client.NewRequest(ctx, http.MethodPost, path, nil)
if err != nil {
return ServerlessCredentials{}, err
}
return executeNamespaceRequest(ctx, s, req)
}
// executeNamespaceRequest executes a valid http.Request object where the request is expected
// to return a NamespaceResponse. The response is converted to ServerlessCredentials. The request
// may represent the (new) 'namespaces/<name>' GET API, the (legacy) 'sandbox' POST API, or
// a namespace creation.
// The legacy API will continue to be used by some users until feature-flipper protection is removed
// from the new one.
func executeNamespaceRequest(ctx context.Context, s *serverlessService, req *http.Request) (ServerlessCredentials, error) {
decoded := new(NamespaceResponse)
_, err := s.client.Do(ctx, req, decoded)
if err != nil {
return ServerlessCredentials{}, err
}
host := assignAPIHost(decoded.Namespace.APIHost, decoded.Namespace.Namespace)
credential := ServerlessCredential{Auth: decoded.Namespace.UUID + ":" + decoded.Namespace.Key}
namespace := decoded.Namespace.Namespace
ans := ServerlessCredentials{
APIHost: host,
Namespace: namespace,
Label: decoded.Namespace.Label,
Credentials: map[string]map[string]ServerlessCredential{host: {namespace: credential}},
}
return ans, nil
}
// ListNamespaces obtains the full list of namespaces that belong to the requesting account
func (s *serverlessService) ListNamespaces(ctx context.Context) (NamespaceListResponse, error) {
path := "v2/functions/namespaces"
req, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)
if err != nil {
return NamespaceListResponse{}, err
}
decoded := new(NamespaceListResponse)
_, err = s.client.Do(ctx, req, decoded)
if err != nil {
return NamespaceListResponse{}, err
}
return removeAppNamespaces(*decoded), nil
}
// removeAppNamespaces modifies a NamespaceListResponse to exclude namespaces prefixed by ap-.
// Those are supposed to be managed by App Platform and should not be available to doctl serverless
// for connection or modification of any kind. This is intended to be temporary because the filtering
// really should be done within the API.
func removeAppNamespaces(input NamespaceListResponse) NamespaceListResponse {
newList := []OutputNamespace{}
for _, ns := range input.Namespaces {
if strings.HasPrefix(ns.Namespace, "ap-") {
continue
}
newList = append(newList, ns)
}
return NamespaceListResponse{Namespaces: newList}
}
// GetNamespace obtains the credentials of a specific namespace, given its name
func (s *serverlessService) GetNamespace(ctx context.Context, name string) (ServerlessCredentials, error) {
path := "v2/functions/namespaces/" + name
req, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)
if err != nil {
return ServerlessCredentials{}, err
}
return executeNamespaceRequest(ctx, s, req)
}
// GetNamespaceFromCluster obtains the namespace that uniquely owns a valid combination of API host and "auth"
// (uuid:key). This can be used to connect to clusters not known to the portal (e.g. dev clusters) or simply
// to check that credentials are valid.
func (s *serverlessService) GetNamespaceFromCluster(APIhost string, auth string) (string, error) {
// We do not use the shared client in serverlessService for this because it uses the stored
// credentials, not the passed ones.
config := whisk.Config{Host: APIhost, AuthToken: auth}
client, err := whisk.NewClient(http.DefaultClient, &config)
if err != nil {
return "", err
}
ns, _, err := client.Namespaces.List()
if err != nil {
return "", err
}
if len(ns) != 1 {
return "", fmt.Errorf("unexpected response when validating apihost and auth")
}
return ns[0].Name, nil
}
// CreateNamespace creates a new namespace and returns its credentials, given a label and region
func (s *serverlessService) CreateNamespace(ctx context.Context, label string, region string) (ServerlessCredentials, error) {
reqBody := newNamespaceRequest{Namespace: inputNamespace{Label: label, Region: region}}
path := "v2/functions/namespaces"
req, err := s.client.NewRequest(ctx, http.MethodPost, path, reqBody)
if err != nil {
return ServerlessCredentials{}, err
}
return executeNamespaceRequest(ctx, s, req)
}
// DeleteNamespace deletes a namespace by name
func (s *serverlessService) DeleteNamespace(ctx context.Context, name string) error {
path := "v2/functions/namespaces/" + name
req, err := s.client.NewRequest(ctx, http.MethodDelete, path, nil)
if err != nil {
return err
}
_, err = s.client.Do(ctx, req, nil)
return err
}
func (s *serverlessService) CleanNamespace() error {
// Deletes all triggers
ctx := context.TODO()
triggers, err := s.ListTriggers(ctx, "")
// Intentionally ignore errors when listing triggers, the trigger API is behind a
// feature flag and may will return an error for users not enabled.
if err == nil {
for _, trig := range triggers {
err = s.DeleteTrigger(ctx, trig.Name)
if err != nil {
return err
}
}
}
// Deletes all functions
fns, err := s.ListFunctions("", 0, 200)
if err != nil {
return err
}
for _, fn := range fns {
name := fn.Name
pkg := strings.Split(fn.Namespace, "/")
if len(pkg) == 2 {
name = pkg[1] + "/" + fn.Name
}
// All triggers for the namespace are deleted above so we don't need to remove the trigger for each individual function.
err := s.DeleteFunction(name, false)
if err != nil {
return err
}
}
// Now delete all packages. Since the functions are presumably gone, the packages can be deleted non-recursively.
pkgs, err := s.ListPackages()
if err != nil {
return err
}
for _, pkg := range pkgs {
err := s.DeletePackage(pkg.Name, false)
if err != nil {
return err
}
}
return nil
}
// GetHostInfo returns the HostInfo structure of the provided API host
func (s *serverlessService) GetHostInfo(APIHost string) (ServerlessHostInfo, error) {
endpoint := APIHost + "/api/v1"
resp, err := http.Get(endpoint)
if err != nil {
return ServerlessHostInfo{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
var result ServerlessHostInfo
err = json.Unmarshal(body, &result)
return result, err
}
// GetFunction returns the metadata and optionally the code of a deployer function
func (s *serverlessService) GetFunction(name string, fetchCode bool) (whisk.Action, []FunctionParameter, error) {
err := initWhisk(s)
if err != nil {
return whisk.Action{}, []FunctionParameter{}, err
}
action, resp, err := s.owClient.Actions.Get(name, fetchCode)
if err != nil {
return whisk.Action{}, []FunctionParameter{}, err
}
var parameters []FunctionParameter
if resp != nil {
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err == nil {
reparse := FunctionParameterReparse{}
err = json.Unmarshal(body, &reparse)
if err != nil {
return whisk.Action{}, []FunctionParameter{}, err
}
parameters = reparse.Parameters
}
}
return *action, parameters, nil
}
// ListFunctions lists the functions of the connected namespace
func (s *serverlessService) ListFunctions(pkg string, skip int, limit int) ([]whisk.Action, error) {
err := initWhisk(s)
if err != nil {
return []whisk.Action{}, err
}
if limit == 0 {
limit = 30
}
options := &whisk.ActionListOptions{
Skip: skip,
Limit: limit,
}
list, _, err := s.owClient.Actions.List(pkg, options)
return list, err
}
// DeleteFunction removes a function from the namespace
func (s *serverlessService) DeleteFunction(name string, deleteTriggers bool) error {
err := initWhisk(s)
if err != nil {
return err
}
if deleteTriggers {
ctx := context.TODO()
triggers, err := s.ListTriggers(ctx, name)
// Intentionally ignore errors when listing triggers, the trigger API is behind a
// feature flag and may will return an error for users not enabled.
if err == nil {
for _, trig := range triggers {
err = s.DeleteTrigger(ctx, trig.Name)
if err != nil {
return err
}
}
}
}
_, e := s.owClient.Actions.Delete(name)
return e
}
// ListPackages lists the packages of the namespace
func (s *serverlessService) ListPackages() ([]whisk.Package, error) {
err := initWhisk(s)
if err != nil {
return []whisk.Package{}, err
}
options := whisk.PackageListOptions{Limit: 200} // 200 is the max and we are also treating it as a safe-enough value here
list, _, err := s.owClient.Packages.List(&options)
return list, err
}
// DeletePackage removes a package from the namespace.
// If recursive is set to true, it will remove all functions in the package.
func (s *serverlessService) DeletePackage(name string, recursive bool) error {
err := initWhisk(s)
if err != nil {
return err
}
if recursive {
pkg, _, err := s.owClient.Packages.Get(name)
if err != nil {
return err
}
for _, fn := range pkg.Actions {
funcName := name + "/" + fn.Name
err = s.DeleteFunction(funcName, true)
if err != nil {
return err
}
}
}
_, err = s.owClient.Packages.Delete(name)
return err
}
// InvokeFunction invokes a function via POST with authentication
func (s *serverlessService) InvokeFunction(name string, params interface{}, blocking bool, result bool) (interface{}, error) {
var empty map[string]interface{}
err := initWhisk(s)
if err != nil {
return empty, err
}
resp, _, err := s.owClient.Actions.Invoke(name, params, blocking, result)
return resp, err
}
// InvokeFunctionViaWeb invokes a function via GET using its web URL (or error if not a web function)
func (s *serverlessService) InvokeFunctionViaWeb(name string, params interface{}) error {
// Get the function so we can use its metadata in formulating the request
theFunction, _, err := s.GetFunction(name, false)
if err != nil {
return err
}
// Check that it's a web function
isWeb := false
for _, annot := range theFunction.Annotations {
if annot.Key == "web-export" {
isWeb = true
break
}
}
if !isWeb {
return fmt.Errorf("'%s' is not a web function", name)
}
// Formulate the invocation URL
host, err := s.GetConnectedAPIHost()
if err != nil {
return err
}
nsParts := strings.Split(theFunction.Namespace, "/")
namespace := nsParts[0]
pkg := "default"
if len(nsParts) > 1 {
pkg = nsParts[1]
}
theURL := fmt.Sprintf("%s/api/v1/web/%s/%s/%s", host, namespace, pkg, theFunction.Name)
// Add params, if any
if params != nil {
encoded := url.Values{}
for key, val := range params.(map[string]interface{}) {
stringVal, ok := val.(string)
if !ok {
return fmt.Errorf("the value of '%s' is not a string; web invocation is not possible", key)
}
encoded.Add(key, stringVal)
}
theURL += "?" + encoded.Encode()
}
return browser.OpenURL(theURL)
}
// ListActivations drives the OpenWhisk API for listing activations
func (s *serverlessService) ListActivations(options whisk.ActivationListOptions) ([]whisk.Activation, error) {
empty := []whisk.Activation{}
err := initWhisk(s)
if err != nil {
return empty, err
}
resp, _, err := s.owClient.Activations.List(&options)
return resp, err
}
// GetActivationCount drives the OpenWhisk API for getting the total number of activations in namespace
func (s *serverlessService) GetActivationCount(options whisk.ActivationCountOptions) (whisk.ActivationCount, error) {
err := initWhisk(s)
empty := whisk.ActivationCount{}
if err != nil {
return empty, err
}
resp, _, err := s.owClient.Activations.Count(&options)
if err != nil {
return empty, err
}
return *resp, err
}
// GetActivation drives the OpenWhisk API getting an activation
func (s *serverlessService) GetActivation(id string) (whisk.Activation, error) {
empty := whisk.Activation{}
err := initWhisk(s)
if err != nil {
return empty, err
}
resp, _, err := s.owClient.Activations.Get(id)
if err != nil {
return empty, err
}
return *resp, err
}
// GetActivationLogs drives the OpenWhisk API getting the logs of an activation
func (s *serverlessService) GetActivationLogs(id string) (whisk.Activation, error) {
empty := whisk.Activation{}
err := initWhisk(s)
if err != nil {
return empty, err