-
Notifications
You must be signed in to change notification settings - Fork 40
/
agent.go
286 lines (240 loc) · 7.33 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
// The codebase is inherited from kata-containers with the modifications.
package v2
import (
"context"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"sync"
"time"
"github.com/BurntSushi/toml"
shimconfig "github.com/confidential-containers/enclave-cc/src/shim/config"
agentClient "github.com/confidential-containers/enclave-cc/src/shim/runtime/v2/rune/agent/client"
grpc "github.com/confidential-containers/enclave-cc/src/shim/runtime/v2/rune/agent/grpc"
"github.com/confidential-containers/enclave-cc/src/shim/runtime/v2/rune/constants"
"github.com/confidential-containers/enclave-cc/src/shim/runtime/v2/rune/image"
types "github.com/containerd/containerd/api/types"
"github.com/containerd/containerd/mount"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/containerd/pkg/process"
"github.com/containerd/containerd/runtime/v2/runc"
taskAPI "github.com/containerd/containerd/runtime/v2/task"
"github.com/containerd/continuity/fs"
runcC "github.com/containerd/go-runc"
"github.com/gogo/protobuf/proto"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
grpcStatus "google.golang.org/grpc/status"
)
const (
configFilename = "config.json"
defaultDirPerm = 0700
defaultFilePerms = 0600
agentIDFile = "agent-id"
grpcPullImageRequest = "grpc.PullImageRequest"
)
var (
defaultRequestTimeout = 60 * time.Second
errAgent = errors.New("Agent error")
)
type agent struct {
// ID of the container
ID string
// Bundle path
Bundle string
// lock protects the client pointer
sync.Mutex
reqHandlers map[string]reqFunc
URL string
dialTimout uint32
dead bool
client *agentClient.AgentClient
}
func (c *agent) Logger() *logrus.Entry {
return logrus.WithField("source", "agent_enclave_container")
}
func (c *agent) connect() error {
if c.dead {
return fmt.Errorf("%w: Dead agent", errAgent)
}
// lockless quick pass
if c.client != nil {
return nil
}
// This is for the first connection only, to prevent race
c.Lock()
defer c.Unlock()
if c.client != nil {
return nil
}
c.Logger().WithField("url", c.URL).Info("New client")
client, err := agentClient.NewAgentClient(c.URL, c.dialTimout)
if err != nil {
c.dead = true
return err
}
c.client = client
c.installReqFunc()
return nil
}
func (c *agent) disconnect() error {
c.Lock()
defer c.Unlock()
if c.client == nil {
return nil
}
if err := c.client.Close(); err != nil && grpcStatus.Convert(err).Code() != codes.Canceled {
return err
}
c.client = nil
c.reqHandlers = nil
return nil
}
type reqFunc func(context.Context, interface{}) (interface{}, error)
func (c *agent) installReqFunc() {
c.reqHandlers = make(map[string]reqFunc)
c.reqHandlers[grpcPullImageRequest] = func(ctx context.Context, req interface{}) (interface{}, error) {
return c.client.ImageServiceClient.PullImage(ctx, req.(*grpc.PullImageRequest))
}
}
func (c *agent) sendReq(spanCtx context.Context, request interface{}) (interface{}, error) {
if err := c.connect(); err != nil {
return nil, err
}
defer c.disconnect()
msgName := proto.MessageName(request.(proto.Message))
c.Lock()
if c.reqHandlers == nil {
c.Unlock()
return nil, fmt.Errorf("%w: Client has already disconnected", errAgent)
}
handler := c.reqHandlers[msgName]
if msgName == "" || handler == nil {
c.Unlock()
return nil, fmt.Errorf("%w: Invalid request type", errAgent)
}
c.Unlock()
message := request.(proto.Message)
ctx, cancel := context.WithTimeout(spanCtx, defaultRequestTimeout)
if cancel != nil {
defer cancel()
}
c.Logger().WithField("name", msgName).WithField("req", message.String()).Trace("sending request")
return handler(ctx, request)
}
func (c *agent) PullImage(ctx context.Context, req *image.PullImageReq) (*image.PullImageResp, error) {
cid, err := getContainerID(req.Image)
if err != nil {
return nil, err
}
// Create dir for store unionfs image (based on sefs)
for _, dir := range []string{"upper", "lower"} {
if err := os.MkdirAll(filepath.Join(c.Bundle, "rootfs", "images", cid, "sefs", dir), defaultDirPerm); err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Join(c.Bundle, "rootfs", "images", cid, "keys", "sefs", dir), defaultDirPerm); err != nil {
return nil, err
}
}
r := &grpc.PullImageRequest{
Image: req.Image,
ContainerId: cid,
}
resp, err := c.sendReq(ctx, r)
if err != nil {
c.Logger().WithError(err).Error("agent enclave container pull image")
return nil, err
}
response := resp.(*grpc.PullImageResponse)
return &image.PullImageResp{
ImageRef: response.ImageRef,
}, nil
}
// The function creates agent enclave container based on a pre-installed OCI bundle
func createAgentContainer(ctx context.Context, s *service, r *taskAPI.CreateTaskRequest) (*runc.Container, error) {
dir := filepath.Join(agentContainerRootDir, r.ID)
upperDir := path.Join(dir, "upper")
workDir := path.Join(dir, "work")
destDir := path.Join(dir, "merged")
for _, dir := range []string{upperDir, workDir, destDir} {
if err := os.MkdirAll(dir, defaultDirPerm); err != nil {
return nil, err
}
}
var options []string
// Set index=off when mount overlayfs
options = append(options, "index=off")
options = append(options,
fmt.Sprintf("lowerdir=%s", filepath.Join(agentContainerPath, "rootfs")),
fmt.Sprintf("workdir=%s", filepath.Join(workDir)),
fmt.Sprintf("upperdir=%s", filepath.Join(upperDir)),
)
r.Rootfs = append(r.Rootfs, &types.Mount{
Type: "overlay",
Source: "overlay",
Options: options,
})
r.Bundle = destDir
fs.CopyFile(filepath.Join(r.Bundle, configFilename), filepath.Join(agentContainerPath, configFilename))
// Create Stdout and Stderr file for agent enclave container
r.Stdout = filepath.Join(agentContainerRootDir, r.ID, "stdout")
r.Stderr = filepath.Join(agentContainerRootDir, r.ID, "stderr")
for _, file := range []string{r.Stdout, r.Stderr} {
f, err := os.Create(file)
if err != nil {
return nil, err
}
defer f.Close()
}
agentContainer, err := runc.NewContainer(ctx, s.platform, r)
if err != nil {
return nil, err
}
return agentContainer, nil
}
// Cleanup the agent enclave container resource
func cleanupAgentContainer(ctx context.Context, id string) error {
var cfg shimconfig.Config
if _, err := toml.DecodeFile(constants.ConfigurationPath, &cfg); err != nil {
return err
}
rootdir := cfg.Containerd.AgentContainerRootDir
path := filepath.Join(rootdir, id, "merged")
ns, err := namespaces.NamespaceRequired(ctx)
if err != nil {
return err
}
runtime, err := runc.ReadRuntime(path)
if err != nil {
return err
}
opts, err := runc.ReadOptions(path)
if err != nil {
return err
}
root := process.RuncRoot
if opts != nil && opts.Root != "" {
root = opts.Root
}
logrus.WithFields(logrus.Fields{
"root": root,
"path": path,
"ns": ns,
"runtime": runtime,
}).Debug("agent enclave Container Cleanup()")
r := process.NewRunc(root, path, ns, runtime, "", false)
if err := r.Delete(ctx, id, &runcC.DeleteOpts{
Force: true,
}); err != nil {
logrus.WithError(err).Warn("failed to remove agent enclave container")
}
if err := mount.UnmountAll(filepath.Join(path, "rootfs"), 0); err != nil {
logrus.WithError(err).Warn("failed to cleanup rootfs mount")
}
if err := os.RemoveAll(filepath.Join(rootdir, id)); err != nil {
logrus.WithError(err).Warn("failed to remove agent enclave container path")
}
return nil
}