-
Notifications
You must be signed in to change notification settings - Fork 9
/
agent.go
348 lines (324 loc) · 9.86 KB
/
agent.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
package kubejob
import (
"archive/tar"
"context"
"crypto/rand"
"crypto/rsa"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/lestrrat-go/jwx/v2/jwt"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
corev1 "k8s.io/api/core/v1"
)
const (
defaultAgentAllocationStartPort = uint16(5000)
maxPortNum = uint16(9000)
rsaBitSize = 2048
agentJWTIssuer = "kubejob"
agentPublicKeyPEMName = "AGENT_PUBLIC_KEY_PEM"
)
type AgentConfig struct {
containerNameToInstalledPathMap map[string]string
allocationStartPort uint16
lastAllocatedPort uint16
excludePortMap map[uint16]struct{}
portMapMu sync.RWMutex
privateKey *rsa.PrivateKey
publicKeyPEM string
timeout *time.Duration
}
func NewAgentConfig(containerNameToInstalledPathMap map[string]string) (*AgentConfig, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, rsaBitSize)
if err != nil {
return nil, fmt.Errorf("job: failed to generate rsa key: %w", err)
}
publicKeyPEM, err := jwk.EncodePEM(&privateKey.PublicKey)
if err != nil {
return nil, fmt.Errorf("job: failed to encode public key: %w", err)
}
return &AgentConfig{
containerNameToInstalledPathMap: containerNameToInstalledPathMap,
allocationStartPort: defaultAgentAllocationStartPort,
excludePortMap: map[uint16]struct{}{},
privateKey: privateKey,
publicKeyPEM: string(publicKeyPEM),
}, nil
}
func (c *AgentConfig) Enabled(containerName string) bool {
path, exists := c.containerNameToInstalledPathMap[containerName]
return exists && path != ""
}
func (c *AgentConfig) SetTimeout(timeout time.Duration) {
c.timeout = &timeout
}
func (c *AgentConfig) Timeout() string {
if c.timeout == nil {
return ""
}
return c.timeout.String()
}
func (c *AgentConfig) InstalledPath(containerName string) string {
return c.containerNameToInstalledPathMap[containerName]
}
func (c *AgentConfig) IssueJWT() ([]byte, error) {
token, err := jwt.NewBuilder().
Issuer(agentJWTIssuer).
IssuedAt(time.Now()).
Build()
if err != nil {
return nil, fmt.Errorf("job: failed to create jwt token: %w", err)
}
signed, err := jwt.Sign(token, jwt.WithKey(jwa.RS256, c.privateKey))
if err != nil {
return nil, fmt.Errorf("job: failed to sign token: %w", err)
}
return signed, nil
}
func (c *AgentConfig) PublicKeyEnv() corev1.EnvVar {
return corev1.EnvVar{
Name: agentPublicKeyPEMName,
Value: c.publicKeyPEM,
}
}
func (c *AgentConfig) SetAllocationStartPort(port uint16) {
c.allocationStartPort = port
}
func (c *AgentConfig) SetExcludePorts(ports ...uint16) {
c.portMapMu.Lock()
defer c.portMapMu.Unlock()
for _, port := range ports {
c.excludePortMap[port] = struct{}{}
}
}
func (c *AgentConfig) NewAllocatedPort() (uint16, error) {
if c.lastAllocatedPort == 0 {
c.lastAllocatedPort = c.allocationStartPort
return c.allocationStartPort, nil
}
newPort, err := c.lookupNewPort(c.lastAllocatedPort + 1)
if err != nil {
return 0, err
}
c.lastAllocatedPort = newPort
return newPort, nil
}
func (c *AgentConfig) lookupNewPort(base uint16) (uint16, error) {
c.portMapMu.RLock()
defer c.portMapMu.RUnlock()
for i := base; i < maxPortNum; i++ {
if _, exists := c.excludePortMap[i]; exists {
continue
}
return i, nil
}
return 0, fmt.Errorf("failed to find new port number")
}
func authorizeAgentJWT(signed []byte) (jwt.Token, error) {
publicKey := os.Getenv(agentPublicKeyPEMName)
if publicKey == "" {
return nil, fmt.Errorf("failed to get public key to authorize token")
}
pubkey, _, err := jwk.DecodePEM([]byte(publicKey))
if err != nil {
return nil, fmt.Errorf("failed to decode public key: %w", err)
}
token, err := jwt.Parse(signed, jwt.WithKey(jwa.RS256, pubkey))
if err != nil {
return nil, fmt.Errorf("failed to verify token: %w", err)
}
if token.Issuer() != agentJWTIssuer {
return nil, fmt.Errorf("unknown issuer %s", token.Issuer())
}
return token, nil
}
func agentAuthUnaryInterceptor(signedToken string) grpc.UnaryClientInterceptor {
return func(ctx context.Context,
method string,
req, reply interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption,
) error {
md := metadata.Pairs("Authorization", fmt.Sprintf("Bearer %s", signedToken))
ctx = metadata.NewOutgoingContext(ctx, md)
return invoker(ctx, method, req, reply, cc, opts...)
}
}
func agentAuthStreamInterceptor(signedToken string) grpc.StreamClientInterceptor {
return func(
ctx context.Context,
desc *grpc.StreamDesc,
cc *grpc.ClientConn,
method string,
streamer grpc.Streamer,
opts ...grpc.CallOption,
) (grpc.ClientStream, error) {
md := metadata.Pairs("Authorization", fmt.Sprintf("Bearer %s", signedToken))
ctx = metadata.NewOutgoingContext(ctx, md)
return streamer(ctx, desc, cc, method, opts...)
}
}
func archivePath(baseDir string, targetPath string) (string, error) {
archivedFilePath := filepath.Join(baseDir, fmt.Sprintf("%s.tar", filepath.Base(targetPath)))
dst, err := os.Create(archivedFilePath)
if err != nil {
return "", fmt.Errorf("failed to create archive file %s: %w", archivedFilePath, err)
}
defer dst.Close()
tw := tar.NewWriter(dst)
defer tw.Close()
finfo, err := os.Stat(targetPath)
if err != nil {
return "", fmt.Errorf("failed to get file info of src path %s: %w", targetPath, err)
}
if !finfo.IsDir() {
// file copy
if err := tw.WriteHeader(&tar.Header{
Name: filepath.Base(targetPath),
Mode: int64(finfo.Mode()),
ModTime: finfo.ModTime(),
Size: finfo.Size(),
}); err != nil {
return "", fmt.Errorf("failed to write archive header to create archive file: %w", err)
}
f, err := os.Open(targetPath)
if err != nil {
return "", fmt.Errorf("failed to open local file to create archive file: %w", err)
}
defer f.Close()
if _, err := io.Copy(tw, f); err != nil {
return "", fmt.Errorf("failed to copy local file to archive file: %w", err)
}
return archivedFilePath, nil
}
pathToDir := filepath.Dir(targetPath)
if err := filepath.Walk(targetPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("failed to create archive file: %w", err)
}
if info.IsDir() {
return nil
}
name := path[len(pathToDir)+1:]
switch {
case info.Mode()&os.ModeSymlink == os.ModeSymlink:
linkName, err := os.Readlink(path)
if err != nil {
return fmt.Errorf("failed to read symlink file: %s: %w", path, err)
}
hdr, err := tar.FileInfoHeader(info, linkName)
if err != nil {
return fmt.Errorf("failed to get header from symlink file name: %s: %w", linkName, err)
}
hdr.Name = name
if !strings.HasPrefix(linkName, pathToDir) {
log.Printf(
"WARN: %s symlink refer to %s, but it is not under the %s directory, so it couldn't copy to archive file",
path, linkName, targetPath,
)
return nil
}
relPath, err := filepath.Rel(filepath.Dir(path), linkName)
if err != nil {
return fmt.Errorf("failed to get relative path from %s to %s: %w", path, linkName, err)
}
if relPath != "" && relPath[0] != '.' {
relPath = "./" + relPath
}
hdr.Linkname = relPath
if err := tw.WriteHeader(hdr); err != nil {
return fmt.Errorf("failed to write symlink header: %w", err)
}
default:
if err := tw.WriteHeader(&tar.Header{
Name: name,
Mode: int64(info.Mode()),
ModTime: info.ModTime(),
Size: info.Size(),
}); err != nil {
return fmt.Errorf("failed to write archive header to create archive file: %w", err)
}
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("failed to open local file to create archive file: %w", err)
}
defer f.Close()
if _, err := io.Copy(tw, f); err != nil {
return fmt.Errorf("failed to copy local file to archive file: %w", err)
}
}
return nil
}); err != nil {
return "", err
}
return archivedFilePath, nil
}
func extractArchivedFile(filePath string, dstPath string) error {
baseDir := filepath.Dir(dstPath)
f, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("failed to open %s: %w", filePath, err)
}
defer f.Close()
tr := tar.NewReader(f)
for {
header, err := tr.Next()
if err != nil {
if err == io.EOF {
break
}
return fmt.Errorf("failed to read archived file %s: %w", filePath, err)
}
if filepath.Join(baseDir, header.Name) == dstPath {
// specified file copy
if err := createFile(dstPath, dstPath, header, tr); err != nil {
return err
}
return nil
}
path := filepath.Join(dstPath, header.Name)
if header.FileInfo().IsDir() {
if err := os.MkdirAll(path, 0o755); err != nil {
return fmt.Errorf("failed to create directory %s: %w", path, err)
}
} else {
if err := createFile(dstPath, path, header, tr); err != nil {
return err
}
}
}
return nil
}
func createFile(dstPath, outPath string, hdr *tar.Header, tr *tar.Reader) error {
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
return fmt.Errorf("failed to create directory %s: %w", filepath.Dir(outPath), err)
}
if hdr.FileInfo().Mode()&os.ModeSymlink == os.ModeSymlink {
referFile := filepath.Join(dstPath, filepath.Dir(hdr.Name), hdr.Linkname)
if err := os.Symlink(referFile, outPath); err != nil {
return fmt.Errorf("failed to create symlink file to %s: %s", outPath, err)
}
} else {
f, err := os.Create(outPath)
if err != nil {
return fmt.Errorf("failed to create file %s: %w", outPath, err)
}
defer f.Close()
if err := f.Chmod(os.FileMode(hdr.Mode)); err != nil {
return fmt.Errorf("failed to apply chmod %d", hdr.Mode)
}
if _, err := io.Copy(f, tr); err != nil {
return fmt.Errorf("failed to copy from archived file to local file: %w", err)
}
}
return nil
}