forked from AliyunContainerService/pouch
/
snapshotter_key.go
64 lines (52 loc) · 2.04 KB
/
snapshotter_key.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
package ctrd
import (
"context"
"fmt"
"google.golang.org/grpc/metadata"
)
const (
// TypeLabelKey is the key of label type=image in Snapshotter metadata Info.Labels, with which indicates the snapshot for image.
TypeLabelKey = "type"
// ImageType is the label value
ImageType = "image"
// SnapshotLabelContextKey is the key which is stored in context to transfer to containerd snapshotter
SnapshotLabelContextKey = "containerd.io.snapshot.labels"
)
type snapshotterKey struct{}
// GetSnapshotter get snapshotter from context
func GetSnapshotter(ctx context.Context) string {
snapshotter, _ := ctx.Value(snapshotterKey{}).(string)
return snapshotter
}
// WithSnapshotter set snapshotter key for context
func WithSnapshotter(ctx context.Context, snapshotter string) context.Context {
return context.WithValue(ctx, snapshotterKey{}, snapshotter)
}
// CleanSnapshotter cleans snapshotter key for context
func CleanSnapshotter(ctx context.Context) context.Context {
if v, ok := ctx.Value(snapshotterKey{}).(string); ok && v != "" {
return context.WithValue(ctx, snapshotterKey{}, "")
}
return ctx
}
// WithImageUnpack adds SnapshotLabelContextKey in context before creation of image snapshot.
// it should be called when image snapshot is on creation, such as pullImage, loadImage and commitImage.
func WithImageUnpack(ctx context.Context) context.Context {
value := fmt.Sprintf("%s=%s", TypeLabelKey, ImageType)
// store on the grpc headers so it gets picked up by any clients that
// are using this.
return withGRPCImageUnpackHeader(ctx, SnapshotLabelContextKey, value)
}
func withGRPCImageUnpackHeader(ctx context.Context, key string, value string) context.Context {
// also store on the grpc headers so it gets picked up by any clients
// that are using this.
txheader := metadata.Pairs(key, value)
md, ok := metadata.FromOutgoingContext(ctx) // merge with outgoing context.
if !ok {
md = txheader
} else {
// order ensures the latest is first in this list.
md = metadata.Join(txheader, md)
}
return metadata.NewOutgoingContext(ctx, md)
}