-
Notifications
You must be signed in to change notification settings - Fork 9
/
agent_client.go
193 lines (179 loc) · 5.37 KB
/
agent_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
package kubejob
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"github.com/goccy/kubejob/agent"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
corev1 "k8s.io/api/core/v1"
)
type AgentClient struct {
serverPod *corev1.Pod
workingDir string
client agent.AgentClient
addr string
}
func NewAgentClient(agentServerPod *corev1.Pod, listenPort uint16, workingDir, signedToken string) (*AgentClient, error) {
ipAddr := agentServerPod.Status.PodIP
addr := fmt.Sprintf("%s:%d", ipAddr, listenPort)
conn, err := grpc.Dial(addr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithDefaultCallOptions(grpc.WaitForReady(true)),
grpc.WithUnaryInterceptor(agentAuthUnaryInterceptor(signedToken)),
grpc.WithStreamInterceptor(agentAuthStreamInterceptor(signedToken)),
)
if err != nil {
return nil, fmt.Errorf("job: failed to dial grpc: %w", err)
}
client := agent.NewAgentClient(conn)
return &AgentClient{
serverPod: agentServerPod,
workingDir: workingDir,
client: client,
addr: addr,
}, nil
}
type AgentExecResult struct {
Output string
Success bool
ExitCode int32
ErrorMessage string
ElapsedTimeSec int64
}
func (c *AgentClient) Exec(ctx context.Context, command []string, env []corev1.EnvVar) (*AgentExecResult, error) {
agentEnv := make([]*agent.Env, 0, len(env))
for _, e := range env {
agentEnv = append(agentEnv, &agent.Env{
Name: e.Name,
Value: e.Value,
})
}
res, err := c.client.Exec(ctx, &agent.ExecRequest{
Command: command,
Env: agentEnv,
WorkingDir: c.workingDir,
})
if err != nil {
return nil, err
}
return &AgentExecResult{
Output: res.Output,
Success: res.Success,
ExitCode: res.ExitCode,
ErrorMessage: res.ErrorMessage,
ElapsedTimeSec: res.ElapsedTimeSec,
}, nil
}
func (c *AgentClient) CopyFrom(ctx context.Context, srcPath, dstPath string) error {
finfo, err := os.Stat(dstPath)
archivedFilePath := fmt.Sprintf("%s.tar", dstPath)
if err == nil && finfo.IsDir() {
// if dstPath is directory, copy specified src into it.
archivedFilePath = filepath.Join(dstPath, fmt.Sprintf("%s.tar", filepath.Base(dstPath)))
}
defer os.Remove(archivedFilePath) // ignore error
if err := c.copyFrom(ctx, srcPath, archivedFilePath); err != nil {
return err
}
if err := extractArchivedFile(archivedFilePath, dstPath); err != nil {
return fmt.Errorf("failed to extract file %s: %w", archivedFilePath, err)
}
return nil
}
func (c *AgentClient) copyFrom(ctx context.Context, srcPath, dstPath string) error {
stream, err := c.client.CopyFrom(ctx, &agent.CopyFromRequest{
Path: srcPath,
})
if err != nil {
return fmt.Errorf("job: failed to create grpc stream to copy from pod: %w", err)
}
if err := os.MkdirAll(filepath.Dir(dstPath), 0o755); err != nil {
return fmt.Errorf("job: failed to create directory %s: %w", filepath.Dir(dstPath), err)
}
f, err := os.Create(dstPath)
if err != nil {
return fmt.Errorf("job: failed to create file %s to copy: %w", dstPath, err)
}
defer f.Close()
for {
copyFromResponse, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("job: failed to grpc stream copy: %w", err)
}
if _, err := f.Write(copyFromResponse.Data); err != nil {
return fmt.Errorf("job: failed to write data: %w", err)
}
}
return nil
}
func (c *AgentClient) CopyTo(ctx context.Context, srcPath, dstPath string) error {
stream, err := c.client.CopyTo(ctx)
if err != nil {
return fmt.Errorf("job: failed to create grpc stream to copy to pod: %w", err)
}
buf := make([]byte, defaultStreamFileChunkSize)
if _, err := os.Stat(srcPath); err != nil {
return fmt.Errorf("job: failed to get status of file %s: %w", srcPath, err)
}
dir, err := os.MkdirTemp("", "kubejob_archive")
if err != nil {
return fmt.Errorf("job: failed to create temporary directory for archivePath: %w", err)
}
defer os.RemoveAll(dir)
archivedFilePath, err := archivePath(dir, srcPath)
if err != nil {
return err
}
f, err := os.Open(archivedFilePath)
if err != nil {
return fmt.Errorf("job: failed to open archived file %s: %w", archivedFilePath, err)
}
defer f.Close()
finfo, err := f.Stat()
if err != nil {
return fmt.Errorf("job: failed to get file info of %s: %w", archivedFilePath, err)
}
if err := stream.Send(&agent.CopyToRequest{
Path: dstPath,
}); err != nil {
return fmt.Errorf("job: failed to send dst path with grpc stream: %w", err)
}
for {
n, err := f.Read(buf)
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("job: failed to read file %s: %w", archivedFilePath, err)
}
if err := stream.Send(&agent.CopyToRequest{
Data: buf[:n],
}); err != nil {
return fmt.Errorf("job: failed to send file data with grpc stream: %w", err)
}
}
if err := stream.CloseSend(); err != nil {
return fmt.Errorf("job: failed to close grpc stream: %w", err)
}
resp, err := stream.Recv()
if err != nil {
return fmt.Errorf("job: failed to recv data with grpc stream: %w", err)
}
if resp.CopiedLength != finfo.Size() {
return fmt.Errorf("job: mismatch copied length. expected size %d but got copied size %d", finfo.Size(), resp.CopiedLength)
}
return nil
}
func (c *AgentClient) Stop(ctx context.Context) error {
_, err := c.client.Finish(ctx, &agent.FinishRequest{})
if err != nil {
return fmt.Errorf("job: failed to finish agent: %w", err)
}
return nil
}