-
Notifications
You must be signed in to change notification settings - Fork 5
/
zun.go
545 lines (485 loc) · 15.5 KB
/
zun.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
package openstack
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack"
"github.com/gophercloud/gophercloud/openstack/container/v1/capsules"
"github.com/gophercloud/gophercloud/pagination"
"github.com/virtual-kubelet/node-cli/manager"
"github.com/virtual-kubelet/virtual-kubelet/node/api"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
// ZunProvider implements the virtual-kubelet provider interface and communicates with OpenStack's Zun APIs.
type ZunProvider struct {
ZunClient *gophercloud.ServiceClient
resourceManager *manager.ResourceManager
region string
nodeName string
operatingSystem string
cpu string
memory string
pods string
daemonEndpointPort int32
}
// NewZunProvider creates a new ZunProvider.
func NewZunProvider(config string, rm *manager.ResourceManager, nodeName string, operatingSystem string, daemonEndpointPort int32) (*ZunProvider, error) {
var p ZunProvider
var err error
p.resourceManager = rm
AuthOptions, err := openstack.AuthOptionsFromEnv()
if err != nil {
return nil, fmt.Errorf("Unable to get the Auth options from environment variables: %s", err)
}
Provider, err := openstack.AuthenticatedClient(AuthOptions)
if err != nil {
return nil, fmt.Errorf("Unable to get provider: %s", err)
}
p.ZunClient, err = openstack.NewContainerV1(Provider, gophercloud.EndpointOpts{
Region: os.Getenv("OS_REGION_NAME"),
})
if err != nil {
return nil, fmt.Errorf("Unable to get zun client")
}
p.ZunClient.Microversion = "1.32"
// Set sane defaults for Capacity in case config is not supplied
p.cpu = "20"
p.memory = "100Gi"
p.pods = "20"
p.operatingSystem = operatingSystem
p.nodeName = nodeName
p.daemonEndpointPort = daemonEndpointPort
return &p, err
}
// GetPod returns a pod by name that is running inside Zun
// returns nil if a pod by that name is not found.
func (p *ZunProvider) GetPod(ctx context.Context, namespace, name string) (*v1.Pod, error) {
capsule, err := capsules.Get(p.ZunClient, fmt.Sprintf("%s-%s", namespace, name)).ExtractV132()
if err != nil {
return nil, err
}
if capsule.MetaLabels["NodeName"] != p.nodeName {
return nil, nil
}
return capsuleToPod(capsule)
}
// GetPods returns a list of all pods known to be running within Zun.
func (p *ZunProvider) GetPods(ctx context.Context) ([]*v1.Pod, error) {
pager := capsules.List(p.ZunClient, nil)
pages := 0
err := pager.EachPage(func(page pagination.Page) (bool, error) {
pages++
return true, nil
})
if err != nil {
return nil, err
}
pods := make([]*v1.Pod, 0, pages)
err = pager.EachPage(func(page pagination.Page) (bool, error) {
CapsuleList, err := capsules.ExtractCapsulesV132(page)
if err != nil {
return false, err
}
for _, m := range CapsuleList {
c := m
if m.MetaLabels["NodeName"] != p.nodeName {
continue
}
p, err := capsuleToPod(&c)
if err != nil {
log.Println(err)
continue
}
pods = append(pods, p)
}
return true, nil
})
if err != nil {
return nil, err
}
return pods, nil
}
// CreatePod accepts a Pod definition and creates
// an Zun deployment
func (p *ZunProvider) CreatePod(ctx context.Context, pod *v1.Pod) error {
var capsuleTemplate CapsuleTemplate
capsuleTemplate.Kind = "capsule"
podUID := string(pod.UID)
podCreationTimestamp := pod.CreationTimestamp.String()
var metadata Metadata
metadata.Labels = map[string]string{
"PodName": pod.Name,
"ClusterName": pod.ClusterName,
"NodeName": pod.Spec.NodeName,
"Namespace": pod.Namespace,
"UID": podUID,
"CreationTimestamp": podCreationTimestamp,
}
metadata.Name = pod.Namespace + "-" + pod.Name
capsuleTemplate.Metadata = metadata
// get containers
containers, err := p.getContainers(ctx, pod)
if err != nil {
return err
}
capsuleTemplate.Spec.Containers = containers
data, err := json.MarshalIndent(capsuleTemplate, "", " ")
if err != nil {
return err
}
template := new(capsules.Template)
template.Bin = []byte(data)
createOpts := capsules.CreateOpts{
TemplateOpts: template,
}
_, err = capsules.Create(p.ZunClient, createOpts).ExtractV132()
if err != nil {
return err
}
return err
}
func (p *ZunProvider) getContainers(ctx context.Context, pod *v1.Pod) ([]Container, error) {
containers := make([]Container, 0, len(pod.Spec.Containers))
for _, container := range pod.Spec.Containers {
c := Container{
// Name: container.Name,
Image: container.Image,
Command: append(container.Command, container.Args...),
WorkingDir: container.WorkingDir,
ImagePullPolicy: string(container.ImagePullPolicy),
}
// Container ENV need to sync with K8s in Zun and gophercloud. Will change them.
// From map[string]string to []map[string]string
c.Env = map[string]string{}
for _, e := range container.Env {
c.Env[e.Name] = e.Value
}
if container.Resources.Limits != nil {
cpuLimit := float64(1)
if _, ok := container.Resources.Limits[v1.ResourceCPU]; ok {
cpuLimit = float64(container.Resources.Limits.Cpu().MilliValue()) / 1000.00
}
memoryLimit := 0.5
if _, ok := container.Resources.Limits[v1.ResourceMemory]; ok {
memoryLimit = float64(container.Resources.Limits.Memory().Value()) / 1000000000.00
}
c.Resources.Limits["cpu"] = cpuLimit
c.Resources.Limits["memory"] = memoryLimit * 1024
}
//TODO: Add Sync with Resource requirement
//TODO: Add port Sync
//TODO: Add volume support
containers = append(containers, c)
}
return containers, nil
}
// RunInContainer executes a command in a container in the pod, copying data
// between in/out/err and the container's stdin/stdout/stderr.
func (p *ZunProvider) RunInContainer(ctx context.Context, namespace, name, container string, cmd []string, attach api.AttachIO) error {
log.Printf("receive ExecInContainer %q\n", container)
return nil
}
// ConfigureNode enables a provider to configure the node object that
// will be used for Kubernetes.
func (p *ZunProvider) ConfigureNode(ctx context.Context, node *v1.Node) {
node.Status.Capacity = p.capacity()
node.Status.Allocatable = p.capacity()
node.Status.Conditions = p.nodeConditions()
node.Status.Addresses = p.nodeAddresses()
node.Status.DaemonEndpoints = p.nodeDaemonEndpoints()
node.Status.NodeInfo.OperatingSystem = p.operatingSystem
}
// GetPodStatus returns the status of a pod by name that is running inside Zun
// returns nil if a pod by that name is not found.
func (p *ZunProvider) GetPodStatus(ctx context.Context, namespace, name string) (*v1.PodStatus, error) {
pod, err := p.GetPod(ctx, namespace, name)
if err != nil {
return nil, err
}
if pod == nil {
return nil, nil
}
return &pod.Status, nil
}
func (p *ZunProvider) GetContainerLogs(ctx context.Context, namespace, podName, containerName string, opts api.ContainerLogOpts) (io.ReadCloser, error) {
return ioutil.NopCloser(strings.NewReader("not support in Zun Provider")), nil
}
// nodeConditions returns a list of conditions (Ready, OutOfDisk, etc), for updates to the node status
// within Kubernetes.
func (p *ZunProvider) nodeConditions() []v1.NodeCondition {
// TODO: Make these dynamic and augment with custom Zun specific conditions of interest
return []v1.NodeCondition{
{
Type: "Ready",
Status: v1.ConditionTrue,
LastHeartbeatTime: metav1.Now(),
LastTransitionTime: metav1.Now(),
Reason: "KubeletReady",
Message: "kubelet is ready.",
},
{
Type: "OutOfDisk",
Status: v1.ConditionFalse,
LastHeartbeatTime: metav1.Now(),
LastTransitionTime: metav1.Now(),
Reason: "KubeletHasSufficientDisk",
Message: "kubelet has sufficient disk space available",
},
{
Type: "MemoryPressure",
Status: v1.ConditionFalse,
LastHeartbeatTime: metav1.Now(),
LastTransitionTime: metav1.Now(),
Reason: "KubeletHasSufficientMemory",
Message: "kubelet has sufficient memory available",
},
{
Type: "DiskPressure",
Status: v1.ConditionFalse,
LastHeartbeatTime: metav1.Now(),
LastTransitionTime: metav1.Now(),
Reason: "KubeletHasNoDiskPressure",
Message: "kubelet has no disk pressure",
},
{
Type: "NetworkUnavailable",
Status: v1.ConditionFalse,
LastHeartbeatTime: metav1.Now(),
LastTransitionTime: metav1.Now(),
Reason: "RouteCreated",
Message: "RouteController created a route",
},
}
}
// nodeAddresses returns a list of addresses for the node status
// within Kubernetes.
func (p *ZunProvider) nodeAddresses() []v1.NodeAddress {
return nil
}
// nodeDaemonEndpoints returns NodeDaemonEndpoints for the node status
// within Kubernetes.
func (p *ZunProvider) nodeDaemonEndpoints() v1.NodeDaemonEndpoints {
return v1.NodeDaemonEndpoints{
KubeletEndpoint: v1.DaemonEndpoint{
Port: p.daemonEndpointPort,
},
}
}
func capsuleToPod(capsule *capsules.CapsuleV132) (*v1.Pod, error) {
var podCreationTimestamp metav1.Time
var containerStartTime metav1.Time
podCreationTimestamp = metav1.NewTime(capsule.CreatedAt)
if len(capsule.Containers) > 0 {
containerStartTime = metav1.NewTime(capsule.Containers[0].StartedAt)
}
containerStartTime = metav1.NewTime(time.Time{})
// Deal with container inside capsule
containers := make([]v1.Container, 0, len(capsule.Containers))
containerStatuses := make([]v1.ContainerStatus, 0, len(capsule.Containers))
for _, c := range capsule.Containers {
containerMemoryMB := 0
if c.Memory != "" {
containerMemory, err := strconv.Atoi(c.Memory)
if err != nil {
log.Println(err)
}
containerMemoryMB = containerMemory
}
container := v1.Container{
Name: c.Name,
Image: c.Image,
Command: c.Command,
Resources: v1.ResourceRequirements{
Limits: v1.ResourceList{
v1.ResourceCPU: resource.MustParse(fmt.Sprintf("%g", float64(c.CPU))),
v1.ResourceMemory: resource.MustParse(fmt.Sprintf("%dM", containerMemoryMB)),
},
Requests: v1.ResourceList{
v1.ResourceCPU: resource.MustParse(fmt.Sprintf("%g", float64(c.CPU*1024/100))),
v1.ResourceMemory: resource.MustParse(fmt.Sprintf("%dM", containerMemoryMB)),
},
},
}
containers = append(containers, container)
containerStatus := v1.ContainerStatus{
Name: c.Name,
State: zunContainerStausToContainerStatus(&c),
LastTerminationState: zunContainerStausToContainerStatus(&c),
Ready: zunStatusToPodPhase(c.Status) == v1.PodRunning,
RestartCount: int32(0),
Image: c.Image,
ImageID: "",
ContainerID: c.UUID,
}
// Add to containerStatuses
containerStatuses = append(containerStatuses, containerStatus)
}
ip := ""
if capsule.Addresses != nil {
for _, v := range capsule.Addresses {
for _, addr := range v {
if addr.Version == float64(4) {
ip = addr.Addr
}
}
}
}
p := v1.Pod{
TypeMeta: metav1.TypeMeta{
Kind: "Pod",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: capsule.MetaLabels["PodName"],
Namespace: capsule.MetaLabels["Namespace"],
ClusterName: capsule.MetaLabels["ClusterName"],
UID: types.UID(capsule.UUID),
CreationTimestamp: podCreationTimestamp,
},
Spec: v1.PodSpec{
NodeName: capsule.MetaLabels["NodeName"],
Volumes: []v1.Volume{},
Containers: containers,
},
Status: v1.PodStatus{
Phase: zunStatusToPodPhase(capsule.Status),
Conditions: zunStatusToPodConditions(capsule.Status, podCreationTimestamp),
Message: "",
Reason: "",
HostIP: "",
PodIP: ip,
StartTime: &containerStartTime,
ContainerStatuses: containerStatuses,
},
}
return &p, nil
}
// UpdatePod is a noop, Zun currently does not support live updates of a pod.
func (p *ZunProvider) UpdatePod(ctx context.Context, pod *v1.Pod) error {
return nil
}
// DeletePod deletes the specified pod out of Zun.
func (p *ZunProvider) DeletePod(ctx context.Context, pod *v1.Pod) error {
err := capsules.Delete(p.ZunClient, fmt.Sprintf("%s-%s", pod.Namespace, pod.Name)).ExtractErr()
if err != nil {
return err
}
// wait for the capsule deletion
for i := 0; i < 300; i++ {
time.Sleep(1 * time.Second)
capsule, err := capsules.Get(p.ZunClient, fmt.Sprintf("%s-%s", pod.Namespace, pod.Name)).ExtractV132()
if _, ok := err.(gophercloud.ErrDefault404); ok {
// deletion complete
return nil
}
if err != nil {
return err
}
if capsule.Status == "Error" {
return fmt.Errorf("Capsule in ERROR state")
}
}
return fmt.Errorf("Timed out on waiting capsule deletion")
}
func zunContainerStausToContainerStatus(cs *capsules.Container) v1.ContainerState {
// Zun already container start time but not add support at gophercloud
//startTime := metav1.NewTime(time.Time(cs.StartTime))
// Zun container status:
//'Error', 'Running', 'Stopped', 'Paused', 'Unknown', 'Creating', 'Created',
//'Deleted', 'Deleting', 'Rebuilding', 'Dead', 'Restarting'
// Handle the case where the container is running.
if cs.Status == "Running" || cs.Status == "Stopped" {
return v1.ContainerState{
Running: &v1.ContainerStateRunning{
StartedAt: metav1.NewTime(time.Time(cs.StartedAt)),
},
}
}
// Handle the case where the container failed.
if cs.Status == "Error" || cs.Status == "Dead" {
return v1.ContainerState{
Terminated: &v1.ContainerStateTerminated{
ExitCode: int32(0),
Reason: cs.Status,
Message: cs.StatusDetail,
StartedAt: metav1.NewTime(time.Time(cs.StartedAt)),
FinishedAt: metav1.NewTime(time.Time(cs.UpdatedAt)),
},
}
}
// Handle the case where the container is pending.
// Which should be all other Zun states.
return v1.ContainerState{
Waiting: &v1.ContainerStateWaiting{
Reason: cs.Status,
Message: cs.StatusDetail,
},
}
}
func zunStatusToPodPhase(status string) v1.PodPhase {
switch status {
case "Running":
return v1.PodRunning
case "Stopped":
return v1.PodSucceeded
case "Error":
return v1.PodFailed
case "Dead":
return v1.PodFailed
case "Creating":
return v1.PodPending
case "Created":
return v1.PodPending
case "Restarting":
return v1.PodPending
case "Rebuilding":
return v1.PodPending
case "Paused":
return v1.PodPending
case "Deleting":
return v1.PodPending
case "Deleted":
return v1.PodPending
}
return v1.PodUnknown
}
func zunStatusToPodConditions(status string, transitiontime metav1.Time) []v1.PodCondition {
switch status {
case "Running":
return []v1.PodCondition{
v1.PodCondition{
Type: v1.PodReady,
Status: v1.ConditionTrue,
LastTransitionTime: transitiontime,
}, v1.PodCondition{
Type: v1.PodInitialized,
Status: v1.ConditionTrue,
LastTransitionTime: transitiontime,
}, v1.PodCondition{
Type: v1.PodScheduled,
Status: v1.ConditionTrue,
LastTransitionTime: transitiontime,
},
}
}
return []v1.PodCondition{}
}
// capacity returns a resource list containing the capacity limits set for Zun.
func (p *ZunProvider) capacity() v1.ResourceList {
return v1.ResourceList{
"cpu": resource.MustParse(p.cpu),
"memory": resource.MustParse(p.memory),
"pods": resource.MustParse(p.pods),
}
}