-
Notifications
You must be signed in to change notification settings - Fork 9
/
client.go
219 lines (187 loc) · 5.75 KB
/
client.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
// Copyright 2022 Namespace Labs Inc; 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.
package orchestration
import (
"context"
"errors"
"fmt"
"io"
"net"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/spf13/viper"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/types/known/timestamppb"
"namespacelabs.dev/foundation/internal/compute"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/console/common"
"namespacelabs.dev/foundation/internal/fnapi"
awsprovider "namespacelabs.dev/foundation/internal/providers/aws"
"namespacelabs.dev/foundation/internal/runtime"
"namespacelabs.dev/foundation/orchestration/proto"
"namespacelabs.dev/foundation/schema"
"namespacelabs.dev/foundation/schema/orchestration"
"namespacelabs.dev/foundation/std/cfg"
"namespacelabs.dev/foundation/std/tasks"
"namespacelabs.dev/foundation/std/tasks/protolog"
awsconf "namespacelabs.dev/foundation/universe/aws/configuration"
)
const (
connTimeout = time.Minute // TODO reduce - we've seen slow connections in CI
)
type RemoteOrchestrator struct {
cluster runtime.ClusterNamespace
server runtime.Deployable
endpoint *schema.Endpoint
}
func (c *RemoteOrchestrator) Connect(ctx context.Context) (*grpc.ClientConn, error) {
orch := compute.On(ctx)
sink := tasks.SinkFrom(ctx)
return grpc.DialContext(ctx, "orchestrator",
grpc.WithBlock(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
patchedContext := compute.AttachOrch(tasks.WithSink(ctx, sink), orch)
return c.cluster.DialServer(patchedContext, c.server, c.endpoint.Port.ContainerPort)
}),
)
}
func getAwsConf(ctx context.Context, env cfg.Context) (*awsconf.Configuration, error) {
sesh, err := awsprovider.ConfiguredSession(ctx, env.Configuration())
if err != nil {
return nil, err
}
if sesh == nil {
return nil, nil
}
// Attach short term AWS credentials if configured for the current env.
cfg := sesh.Config()
creds, err := cfg.Credentials.Retrieve(ctx)
if err != nil {
return nil, err
}
if creds.CanExpire {
if creds.Expired() {
return nil, fmt.Errorf("aws credentials expired")
}
return &awsconf.Configuration{
Region: cfg.Region,
Static: &awsconf.Credentials{
AccessKeyId: creds.AccessKeyID,
Expiration: timestamppb.New(creds.Expires),
SecretAccessKey: creds.SecretAccessKey,
SessionToken: creds.SessionToken,
},
}, nil
}
// TODO do we need to configure MFA here?
result, err := sts.NewFromConfig(cfg).GetSessionToken(ctx, &sts.GetSessionTokenInput{})
if err != nil {
return nil, err
}
return &awsconf.Configuration{
Region: cfg.Region,
Static: &awsconf.Credentials{
AccessKeyId: aws.ToString(result.Credentials.AccessKeyId),
Expiration: timestamppb.New(aws.ToTime(result.Credentials.Expiration)),
SecretAccessKey: aws.ToString(result.Credentials.SecretAccessKey),
SessionToken: aws.ToString(result.Credentials.SessionToken),
},
}, nil
}
func getUserAuth(ctx context.Context) (*fnapi.UserAuth, error) {
auth, err := fnapi.LoadUser()
if err != nil {
if errors.Is(err, fnapi.ErrRelogin) {
// Don't require login yet. The orchestrator will fail with the appropriate error if required.
return nil, nil
}
return nil, err
}
res, err := fnapi.GetSessionToken(ctx, string(auth.Opaque), time.Hour)
if err != nil {
return nil, err
}
auth.Opaque = []byte(res.Token)
return auth, nil
}
func CallDeploy(ctx context.Context, env cfg.Context, conn *grpc.ClientConn, plan *schema.DeployPlan) (string, error) {
req := &proto.DeployRequest{
Plan: plan,
}
var err error
if req.Aws, err = getAwsConf(ctx, env); err != nil {
return "", err
}
if req.Auth, err = getUserAuth(ctx); err != nil {
return "", err
}
ctx, cancel := context.WithTimeout(ctx, connTimeout)
defer cancel()
resp, err := proto.NewOrchestrationServiceClient(conn).Deploy(ctx, req)
if err != nil {
return "", err
}
return resp.Id, nil
}
func WireDeploymentStatus(ctx context.Context, conn *grpc.ClientConn, id string, ch chan *orchestration.Event) error {
if ch != nil {
defer close(ch)
}
maxLogLevel := viper.GetInt32("console_log_level")
req := &proto.DeploymentStatusRequest{
Id: id,
LogLevel: maxLogLevel,
}
stream, err := proto.NewOrchestrationServiceClient(conn).DeploymentStatus(ctx, req)
if err != nil {
return err
}
for {
in, err := stream.Recv()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
if ch != nil && in.Event != nil {
ch <- in.Event
}
if in.Log != nil {
forwardsLogs(ctx, maxLogLevel, in.Log)
}
}
}
func forwardsLogs(ctx context.Context, maxLogLevel int32, log *protolog.Log) {
if l := log.Lines; l != nil {
for _, line := range l.Lines {
outputType := common.CatOutputType(l.Cat)
if outputType == common.CatOutputDebug {
// Call console.NamedDebug to respect DebugToConsole
fmt.Fprintln(console.NamedDebug(ctx, l.Name), string(line))
} else {
fmt.Fprintln(console.TypedOutput(ctx, l.Name, outputType), string(line))
}
}
}
if log.Task != nil && log.LogLevel <= maxLogLevel {
sink := tasks.SinkFrom(ctx)
ra := tasks.ActionFromProto(ctx, "orchestrator", log.Task)
switch log.Purpose {
case protolog.Log_PURPOSE_WAITING:
sink.Waiting(ra)
case protolog.Log_PURPOSE_STARTED:
sink.Started(ra)
case protolog.Log_PURPOSE_DONE:
sink.Done(ra)
case protolog.Log_PURPOSE_INSTANT:
sink.Instant(&ra.Data)
default:
fmt.Fprintf(console.Warnings(ctx), "unknown orchestrator log purpose %s", log.Purpose)
}
}
}