This repository has been archived by the owner on Mar 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathstorage.go
205 lines (180 loc) · 6.65 KB
/
storage.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
package licensing
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/licensing/model"
)
var (
licenseNamePrefix = "com.docker.license"
licenseFilename = "docker.lic"
// ErrWorkerNode returned on a swarm worker node - lookup licenses on swarm managers
ErrWorkerNode = fmt.Errorf("this node is not a swarm manager - check license status on a manager node")
// ErrUnlicensed returned when no license found
ErrUnlicensed = fmt.Errorf("no license found")
)
// WrappedDockerClient provides methods useful for installing licenses to the wrapped docker engine or cluster
type WrappedDockerClient interface {
Info(ctx context.Context) (types.Info, error)
NodeList(ctx context.Context, options types.NodeListOptions) ([]swarm.Node, error)
ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (types.ConfigCreateResponse, error)
ConfigList(ctx context.Context, options types.ConfigListOptions) ([]swarm.Config, error)
ConfigInspectWithRaw(ctx context.Context, id string) (swarm.Config, []byte, error)
}
// StoreLicense will store the license on the host filesystem and swarm (if swarm is active)
func StoreLicense(ctx context.Context, clnt WrappedDockerClient, license *model.IssuedLicense, rootDir string) error {
licenseData, err := json.Marshal(*license)
if err != nil {
return err
}
// First determine if we're in swarm-mode or a stand-alone engine
_, err = clnt.NodeList(ctx, types.NodeListOptions{})
if err != nil { // TODO - check for the specific error message
return writeLicenseToHost(ctx, clnt, licenseData, rootDir)
}
// Load this in the latest license index
latestVersion, err := getLatestNamedConfig(clnt, licenseNamePrefix)
if err != nil {
return fmt.Errorf("unable to get latest license version: %s", err)
}
spec := swarm.ConfigSpec{
Annotations: swarm.Annotations{
Name: fmt.Sprintf("%s-%d", licenseNamePrefix, latestVersion+1),
Labels: map[string]string{
"com.docker.ucp.access.label": "/",
"com.docker.ucp.collection": "swarm",
"com.docker.ucp.collection.root": "true",
"com.docker.ucp.collection.swarm": "true",
},
},
Data: licenseData,
}
_, err = clnt.ConfigCreate(context.Background(), spec)
if err != nil {
return fmt.Errorf("Failed to create license: %s", err)
}
return nil
}
func (c *client) LoadLocalLicense(ctx context.Context, clnt WrappedDockerClient) (*model.Subscription, error) {
info, err := clnt.Info(ctx)
if err != nil {
return nil, err
}
var licenseData []byte
if info.Swarm.LocalNodeState != "active" {
licenseData, err = readLicenseFromHost(ctx, info.DockerRootDir)
} else {
// Load the latest license index
var latestVersion int
// check if node is swarm manager
if !info.Swarm.ControlAvailable {
return nil, ErrWorkerNode
}
latestVersion, err = getLatestNamedConfig(clnt, licenseNamePrefix)
if err != nil {
return nil, fmt.Errorf("unable to get latest license version: %s", err)
}
if latestVersion >= 0 {
cfg, _, err := clnt.ConfigInspectWithRaw(ctx, fmt.Sprintf("%s-%d", licenseNamePrefix, latestVersion))
if err != nil {
return nil, fmt.Errorf("unable to load license from swarm config: %s", err)
}
licenseData = cfg.Spec.Data
} else {
licenseData, err = readLicenseFromHost(ctx, info.DockerRootDir)
}
}
if err != nil {
if os.IsNotExist(err) {
return nil, ErrUnlicensed
}
return nil, fmt.Errorf("Failed to create license: %s", err)
}
parsedLicense, err := c.ParseLicense(licenseData)
if err != nil {
return nil, err
}
checkResponse, err := c.VerifyLicense(ctx, *parsedLicense)
if err != nil {
return nil, err
}
return checkResponseToSubscription(checkResponse), nil
}
func checkResponseToSubscription(checkResponse *model.CheckResponse) *model.Subscription {
// Determine if the license has already expired
var state string
if checkResponse.Expiration.Before(time.Now()) {
state = "expired"
} else {
state = "active"
}
// For backward compatibility, show information about old (per node) licenses
components := checkResponse.PricingComponents
if checkResponse.MaxEngines > 0 {
components = append(components, &model.SubscriptionPricingComponent{
Name: "Nodes",
Value: checkResponse.MaxEngines,
})
}
// Translate the legacy structure into the new Subscription fields
return &model.Subscription{
ID: checkResponse.SubscriptionID,
ProductID: checkResponse.ProductID,
ProductRatePlanID: checkResponse.RatePlanID,
Expires: &checkResponse.Expiration,
State: state,
PricingComponents: components,
GraceDays: checkResponse.GraceDays,
}
}
func (c *client) SummarizeLicense(checkResponse *model.CheckResponse) *model.Subscription {
return checkResponseToSubscription(checkResponse)
}
// getLatestNamedConfig looks for versioned instances of configs with the
// given name prefix which have a `-NUM` integer version suffix. Returns the
// config with the higest version number found or nil if no such configs exist
// along with its version number.
func getLatestNamedConfig(dclient WrappedDockerClient, namePrefix string) (int, error) {
latestVersion := -1
// List any/all existing configs so that we create a newer version than
// any that already exist.
filter := filters.NewArgs()
filter.Add("name", namePrefix)
existingConfigs, err := dclient.ConfigList(context.Background(), types.ConfigListOptions{Filters: filter})
if err != nil {
return latestVersion, fmt.Errorf("unable to list existing configs: %s", err)
}
for _, existingConfig := range existingConfigs {
existingConfigName := existingConfig.Spec.Name
nameSuffix := strings.TrimPrefix(existingConfigName, namePrefix)
if nameSuffix == "" || nameSuffix[0] != '-' {
continue // No version specifier?
}
versionSuffix := nameSuffix[1:] // Trim the version separator.
existingVersion, err := strconv.Atoi(versionSuffix)
if err != nil {
continue // Unable to parse version as integer.
}
if existingVersion > latestVersion {
latestVersion = existingVersion
}
}
return latestVersion, nil
}
func writeLicenseToHost(ctx context.Context, dclient WrappedDockerClient, license []byte, rootDir string) error {
// TODO we should write the file out over the clnt instead of to the local filesystem
return ioutil.WriteFile(filepath.Join(rootDir, licenseFilename), license, 0644)
}
func readLicenseFromHost(ctx context.Context, rootDir string) ([]byte, error) {
// TODO we should read the file in over the clnt instead of to the local filesystem
return ioutil.ReadFile(filepath.Join(rootDir, licenseFilename))
}