-
Notifications
You must be signed in to change notification settings - Fork 156
/
containerd.go
311 lines (269 loc) · 9.37 KB
/
containerd.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
// Copyright (c) 2017-2020 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package hypervisor
import (
"fmt"
"github.com/lf-edge/eve/pkg/pillar/containerd"
"github.com/lf-edge/eve/pkg/pillar/types"
"github.com/opencontainers/runtime-spec/specs-go"
"os"
"path/filepath"
"time"
uuid "github.com/satori/go.uuid"
"github.com/sirupsen/logrus"
)
const (
vifsDir string = "/run/tasks/vifs"
//ContainerdHypervisorName is a name of containerd hypervisor
ContainerdHypervisorName = "containerd"
)
type ctrdContext struct {
domCounter int
PCI map[string]bool
ctrdClient *containerd.Client
}
func initContainerd() (*ctrdContext, error) {
ctrdClient, err := containerd.NewContainerdClient(false)
if err != nil {
return nil, err
}
return &ctrdContext{
domCounter: 0,
PCI: map[string]bool{},
ctrdClient: ctrdClient,
}, nil
}
func newContainerd() Hypervisor {
if ret, err := initContainerd(); err != nil {
logrus.Fatalf("couldn't initialize containerd (this should not happen): %v. Exiting.", err)
return nil // it really never returns on account of above
} else {
return ret
}
}
// CountMemOverhead - returns the memory overhead for a domain.
// This implementation is used for Xen as well
func (ctx ctrdContext) CountMemOverhead(domainName string, domainUUID uuid.UUID, domainRAMMemory int64, vmmMaxMem int64,
domainMaxCpus int64, domainVCpus int64, domainIoAdapterList []types.IoAdapter, aa *types.AssignableAdapters,
globalConfig *types.ConfigItemValueMap) (uint64, error) {
// Does containerd have any overhead?
return 0, nil
}
func (ctx ctrdContext) GetCapabilities() (*types.Capabilities, error) {
//we are here because of no /dev/xen or /dev/kvm exists
return &types.Capabilities{
HWAssistedVirtualization: false,
IOVirtualization: false,
CPUPinning: false,
UseVHost: false,
}, nil
}
func (ctx ctrdContext) Name() string {
return ContainerdHypervisorName
}
func (ctx ctrdContext) Task(status *types.DomainStatus) types.Task {
return ctx
}
func (ctx ctrdContext) setupSpec(status *types.DomainStatus, config *types.DomainConfig, volume string) (containerd.OCISpec, error) {
spec, err := ctx.ctrdClient.NewOciSpec(status.DomainName, config.Service)
if err != nil {
return nil, err
}
if err := spec.UpdateFromVolume(volume); err != nil {
return nil, err
}
spec.UpdateFromDomain(config, status)
spec.UpdateMounts(status.DiskStatusList)
spec.UpdateVifList(config.VifList)
spec.UpdateEnvVar(status.EnvVariables)
return spec, nil
}
func (ctx ctrdContext) Setup(status types.DomainStatus, config types.DomainConfig,
aa *types.AssignableAdapters, globalConfig *types.ConfigItemValueMap, file *os.File) error {
if status.OCIConfigDir == "" {
return logError("failed to run domain %s: not based on an OCI image", status.DomainName)
}
spec, err := ctx.setupSpec(&status, &config, status.OCIConfigDir)
if err != nil {
return logError("setting up OCI spec for domain %s failed %v", status.DomainName, err)
}
// we use patched version of dhcpcd with /etc/resolv.conf.new
vifsTaskResolv := filepath.Join(vifsDir, status.DomainName, "etc", "resolv.conf.new")
err = os.MkdirAll(filepath.Dir(vifsTaskResolv), 0755)
if err != nil {
return logError("Failed to create directory for vifs task %s with err: %s",
filepath.Dir(vifsTaskResolv), err)
}
f, err := os.OpenFile(vifsTaskResolv, os.O_WRONLY|os.O_CREATE|os.O_SYNC, 0755)
if err != nil {
return logError("Failed creating empty resolv.conf.new file %s with err: %s", vifsTaskResolv, err)
}
defer f.Close()
spec.Get().Mounts = append(spec.Get().Mounts, specs.Mount{
Type: "bind",
Source: vifsTaskResolv,
Destination: "/etc/resolv.conf",
Options: []string{"rbind", "ro"}})
if err := spec.CreateContainer(true); err != nil {
return logError("Failed to create container for task %s from %v: %v", status.DomainName, config, err)
}
return nil
}
func (ctx ctrdContext) Create(domainName string, cfgFilename string, config *types.DomainConfig) (int, error) {
// if we are here we may need to get rid of the wedged, stale task just in case
// we are ignoring error here since it is cheaper to always call this as opposed
// to figure out if there's a wedged task (IOW, error could simply mean there was
// nothing to kill)
ctrdCtx, done := ctx.ctrdClient.CtrNewUserServicesCtx()
defer done()
_ = ctx.ctrdClient.CtrStopContainer(ctrdCtx, domainName, true)
return ctx.ctrdClient.CtrCreateTask(ctrdCtx, domainName)
}
func (ctx ctrdContext) Start(domainName string) error {
ctrdCtx, done := ctx.ctrdClient.CtrNewUserServicesCtx()
defer done()
err := ctx.ctrdClient.CtrStartTask(ctrdCtx, domainName)
if err != nil {
return err
}
// now lets wait for task to reach a steady state or for >10sec to elapse
for i := 0; i < 10; i++ {
_, _, status, err := ctx.ctrdClient.CtrContainerInfo(ctrdCtx, domainName)
if err == nil && (status == "running" || status == "stopped" || status == "paused") {
return nil
}
time.Sleep(time.Second)
}
return fmt.Errorf("task %s couldn't reach a steady state in time", domainName)
}
func (ctx ctrdContext) Stop(domainName string, force bool) error {
ctrdCtx, done := ctx.ctrdClient.CtrNewUserServicesCtx()
defer done()
return ctx.ctrdClient.CtrStopContainer(ctrdCtx, domainName, force)
}
func (ctx ctrdContext) Delete(domainName string) error {
ctrdCtx, done := ctx.ctrdClient.CtrNewUserServicesCtx()
defer done()
if err := ctx.ctrdClient.CtrDeleteContainer(ctrdCtx, domainName); err != nil {
return err
}
vifsTaskDir := filepath.Join(vifsDir, domainName)
if err := os.RemoveAll(vifsTaskDir); err != nil {
return logError("cannot clear vifs task dir %s: %v", vifsTaskDir, err)
}
return nil
}
// Cleanup deletes stale containers if exists
func (ctx ctrdContext) Cleanup(domainName string) error {
ctrdCtx, done := ctx.ctrdClient.CtrNewUserServicesCtx()
defer done()
container, _ := ctx.ctrdClient.CtrLoadContainer(ctrdCtx, domainName)
if container == nil {
return nil
}
return ctx.Delete(domainName)
}
func (ctx ctrdContext) Annotations(domainName string) (map[string]string, error) {
ctrdCtx, done := ctx.ctrdClient.CtrNewUserServicesCtx()
defer done()
return ctx.ctrdClient.CtrGetAnnotations(ctrdCtx, domainName)
}
func (ctx ctrdContext) Info(domainName string) (int, types.SwState, error) {
ctrdCtx, done := ctx.ctrdClient.CtrNewUserServicesCtx()
defer done()
effectiveDomainID, exit, status, err := ctx.ctrdClient.CtrContainerInfo(ctrdCtx, domainName)
if err != nil {
return 0, types.UNKNOWN, logError("containerd looking up domain %s resulted in %v", domainName, err)
}
if status == "stopped" && exit != 0 {
return 0, types.BROKEN, logError("task broke with exit status %d", exit)
}
stateMap := map[string]types.SwState{
"created": types.INSTALLED,
"running": types.RUNNING,
"pausing": types.PAUSING,
"paused": types.PAUSED,
"stopped": types.HALTED,
}
if effectiveDomainState, matched := stateMap[status]; !matched {
err := fmt.Errorf("task %s happens to be in an unexpected state %s",
domainName, status)
logrus.Error(err)
return effectiveDomainID, types.BROKEN, err
} else {
return effectiveDomainID, effectiveDomainState, nil
}
}
func (ctx ctrdContext) PCIReserve(long string) error {
if ctx.PCI[long] {
return fmt.Errorf("PCI %s is already reserved", long)
} else {
ctx.PCI[long] = true
return nil
}
}
func (ctx ctrdContext) PCIRelease(long string) error {
if !ctx.PCI[long] {
return fmt.Errorf("PCI %s is not reserved", long)
} else {
ctx.PCI[long] = false
return nil
}
}
func (ctx ctrdContext) PCISameController(id1 string, id2 string) bool {
return types.PCISameController(id1, id2)
}
func (ctx ctrdContext) GetHostCPUMem() (types.HostMemory, error) {
return selfDomCPUMem()
}
const nanoSecToSec uint64 = 1000000000
func (ctx ctrdContext) GetDomsCPUMem() (map[string]types.DomainMetric, error) {
res := map[string]types.DomainMetric{}
ctrdCtx, done := ctx.ctrdClient.CtrNewUserServicesCtx()
defer done()
ids, err := ctx.ctrdClient.CtrListTaskIds(ctrdCtx)
if err != nil {
return nil, err
}
for _, id := range ids {
var usedMem, maxUsedMem, availMem, totalMem uint32
var usedMemPerc float64
var cpuTotal uint64
if metric, err := ctx.ctrdClient.CtrGetContainerMetrics(ctrdCtx, id); err == nil {
if metric.Memory == nil || metric.Memory.Usage == nil {
logrus.Errorf("GetDomsCPUMem nil returned in metric.Memory: %v", metric)
} else {
usedMem = uint32(roundFromBytesToMbytes(metric.Memory.Usage.Usage))
maxUsedMem = uint32(roundFromBytesToMbytes(metric.Memory.Usage.Max))
totalMem = uint32(roundFromBytesToMbytes(metric.Memory.HierarchicalMemoryLimit))
availMem = 0
if totalMem > usedMem {
availMem = totalMem - usedMem
}
if totalMem != 0 {
usedMemPerc = float64(100 * float32(usedMem) / float32(totalMem))
} else {
usedMemPerc = 0
}
}
if metric.CPU == nil || metric.CPU.Usage == nil {
logrus.Errorf("GetDomsCPUMem nil returned in metric.CPU: %v", metric)
} else {
cpuTotal = metric.CPU.Usage.Total
}
} else {
logrus.Errorf("GetDomsCPUMem failed with error %v", err)
}
res[id] = types.DomainMetric{
UUIDandVersion: types.UUIDandVersion{},
CPUTotalNs: cpuTotal, // Caller will scale
CPUScaled: 1,
AllocatedMB: totalMem,
UsedMemory: usedMem,
MaxUsedMemory: maxUsedMem,
AvailableMemory: availMem,
UsedMemoryPercent: usedMemPerc,
}
}
return res, nil
}