This repository has been archived by the owner on Feb 24, 2020. It is now read-only.
/
config.go
416 lines (377 loc) · 10.7 KB
/
config.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
// Copyright 2015 The rkt Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"github.com/hashicorp/errwrap"
"github.com/rkt/rkt/common"
)
// Headerer is an interface for getting additional HTTP headers to use
// when downloading data (images, signatures).
type Headerer interface {
GetHeader() http.Header
SignRequest(r *http.Request) *http.Request
}
// BasicCredentials holds typical credentials used for authentication
// (user and password). Used for fetching docker images.
type BasicCredentials struct {
User string `json:"user"`
Password string `json:"password"`
}
// ConfigurablePaths holds various paths defined in the configuration.
type ConfigurablePaths struct {
DataDir string
Stage1ImagesDir string
}
// Stage1 holds name, version and location of a default stage1 image
// if it was specified in configuration.
type Stage1Data struct {
Name string
Version string
Location string
}
// Config is a single place where configuration for rkt frontend needs
// resides.
type Config struct {
AuthPerHost map[string]Headerer
DockerCredentialsPerRegistry map[string]BasicCredentials
Paths ConfigurablePaths
Stage1 Stage1Data
}
// MarshalJSON marshals the config for user output.
func (c *Config) MarshalJSON() ([]byte, error) {
stage0 := []interface{}{}
for host, auth := range c.AuthPerHost {
var typ string
var credentials interface{}
switch h := auth.(type) {
case *basicAuthHeaderer:
typ = "basic"
credentials = h.auth
case *oAuthBearerTokenHeaderer:
typ = "oauth"
credentials = h.auth
case *awsAuthHeaderer:
typ = "aws"
credentials = h.auth
default:
return nil, errors.New("unknown headerer type")
}
auth := struct {
RktVersion string `json:"rktVersion"`
RktKind string `json:"rktKind"`
Domains []string `json:"domains"`
Type string `json:"type"`
Credentials interface{} `json:"credentials"`
}{
RktVersion: "v1",
RktKind: "auth",
Domains: []string{host},
Type: typ,
Credentials: credentials,
}
stage0 = append(stage0, auth)
}
for registry, credentials := range c.DockerCredentialsPerRegistry {
dockerAuth := struct {
RktVersion string `json:"rktVersion"`
RktKind string `json:"rktKind"`
Registries []string `json:"registries"`
Credentials BasicCredentials `json:"credentials"`
}{
RktVersion: "v1",
RktKind: "dockerAuth",
Registries: []string{registry},
Credentials: credentials,
}
stage0 = append(stage0, dockerAuth)
}
paths := struct {
RktVersion string `json:"rktVersion"`
RktKind string `json:"rktKind"`
Data string `json:"data"`
Stage1Images string `json:"stage1-images"`
}{
RktVersion: "v1",
RktKind: "paths",
Data: c.Paths.DataDir,
Stage1Images: c.Paths.Stage1ImagesDir,
}
stage1 := struct {
RktVersion string `json:"rktVersion"`
RktKind string `json:"rktKind"`
Name string `json:"name"`
Version string `json:"version"`
Location string `json:"location"`
}{
RktVersion: "v1",
RktKind: "stage1",
Name: c.Stage1.Name,
Version: c.Stage1.Version,
Location: c.Stage1.Location,
}
stage0 = append(stage0, paths, stage1)
data := map[string]interface{}{"stage0": stage0}
return json.Marshal(data)
}
type configParser interface {
parse(config *Config, raw []byte) error
}
var (
// configSubDirs is a map saying what kinds of configuration
// (values) are acceptable in a config subdirectory (key)
configSubDirs = make(map[string][]string)
parsersForKind = make(map[string]map[string]configParser)
)
// ResolveAuthPerHost takes a map of strings to Headerer and resolves the
// Headerers to http.Headers
func ResolveAuthPerHost(authPerHost map[string]Headerer) map[string]http.Header {
hostHeaders := make(map[string]http.Header, len(authPerHost))
for k, v := range authPerHost {
hostHeaders[k] = v.GetHeader()
}
return hostHeaders
}
func addParser(kind, version string, parser configParser) {
if len(kind) == 0 {
panic("empty kind string when registering a config parser")
}
if len(version) == 0 {
panic("empty version string when registering a config parser")
}
if parser == nil {
panic("trying to register a nil parser")
}
if _, err := getParser(kind, version); err == nil {
panic(fmt.Sprintf("A parser for kind %q and version %q already exist", kind, version))
}
if _, ok := parsersForKind[kind]; !ok {
parsersForKind[kind] = make(map[string]configParser)
}
parsersForKind[kind][version] = parser
}
func registerSubDir(dir string, kinds []string) {
if len(dir) == 0 {
panic("trying to register empty config subdirectory")
}
if len(kinds) == 0 {
panic("kinds array cannot be empty when registering config subdir")
}
allKinds := toArray(toSet(append(configSubDirs[dir], kinds...)))
sort.Strings(allKinds)
configSubDirs[dir] = allKinds
}
func toSet(a []string) map[string]struct{} {
s := make(map[string]struct{})
for _, v := range a {
s[v] = struct{}{}
}
return s
}
func toArray(s map[string]struct{}) []string {
a := make([]string, 0, len(s))
for k := range s {
a = append(a, k)
}
return a
}
// GetConfig gets the Config instance with configuration taken from
// default system path (see common.DefaultSystemConfigDir) overridden
// with configuration from default local path (see
// common.DefaultLocalConfigDir).
func GetConfig() (*Config, error) {
return GetConfigFrom(common.DefaultSystemConfigDir, common.DefaultLocalConfigDir)
}
// GetConfigFrom gets the Config instance with configuration taken
// from given paths. Subsequent paths override settings from the
// previous paths.
func GetConfigFrom(dirs ...string) (*Config, error) {
cfg := newConfig()
for _, cd := range dirs {
subcfg, err := GetConfigFromDir(cd)
if err != nil {
return nil, err
}
mergeConfigs(cfg, subcfg)
}
return cfg, nil
}
// GetConfigFromDir gets the Config instance with configuration taken
// from given directory.
func GetConfigFromDir(dir string) (*Config, error) {
subcfg := newConfig()
if valid, err := validDir(dir); err != nil {
return nil, err
} else if !valid {
return subcfg, nil
}
if err := readConfigDir(subcfg, dir); err != nil {
return nil, err
}
return subcfg, nil
}
func newConfig() *Config {
return &Config{
AuthPerHost: make(map[string]Headerer),
DockerCredentialsPerRegistry: make(map[string]BasicCredentials),
Paths: ConfigurablePaths{
DataDir: "",
},
}
}
func readConfigDir(config *Config, dir string) error {
for csd, kinds := range configSubDirs {
d := filepath.Join(dir, csd)
if valid, err := validDir(d); err != nil {
return err
} else if !valid {
continue
}
configWalker := getConfigWalker(config, kinds, d)
if err := filepath.Walk(d, configWalker); err != nil {
return err
}
}
return nil
}
func validDir(path string) (bool, error) {
fi, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
if !fi.IsDir() {
return false, fmt.Errorf("expected %q to be a directory", path)
}
return true, nil
}
func getConfigWalker(config *Config, kinds []string, root string) filepath.WalkFunc {
return func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if path == root {
return nil
}
return readFile(config, info, path, kinds)
}
}
func readFile(config *Config, info os.FileInfo, path string, kinds []string) error {
if valid, err := validConfigFile(info); err != nil {
return err
} else if !valid {
return nil
}
if err := parseConfigFile(config, path, kinds); err != nil {
return err
}
return nil
}
func validConfigFile(info os.FileInfo) (bool, error) {
mode := info.Mode()
switch {
case mode.IsDir():
return false, filepath.SkipDir
case mode.IsRegular():
return filepath.Ext(info.Name()) == ".json", nil
case mode&os.ModeSymlink == os.ModeSymlink:
// TODO: support symlinks?
return false, nil
default:
return false, nil
}
}
type configHeader struct {
RktVersion string `json:"rktVersion"`
RktKind string `json:"rktKind"`
}
func parseConfigFile(config *Config, path string, kinds []string) error {
raw, err := ioutil.ReadFile(path)
if err != nil {
return err
}
var header configHeader
if err := json.Unmarshal(raw, &header); err != nil {
return err
}
if len(header.RktKind) == 0 {
return fmt.Errorf("no rktKind specified in %q", path)
}
if len(header.RktVersion) == 0 {
return fmt.Errorf("no rktVersion specified in %q", path)
}
kindOk := false
for _, kind := range kinds {
if header.RktKind == kind {
kindOk = true
break
}
}
if !kindOk {
dir := filepath.Dir(path)
base := filepath.Base(path)
kindsStr := strings.Join(kinds, `", "`)
return fmt.Errorf("the configuration directory %q expects to have configuration files of kinds %q, but %q has kind of %q", dir, kindsStr, base, header.RktKind)
}
parser, err := getParser(header.RktKind, header.RktVersion)
if err != nil {
return err
}
if err := parser.parse(config, raw); err != nil {
return errwrap.Wrap(fmt.Errorf("failed to parse %q", path), err)
}
return nil
}
func getParser(kind, version string) (configParser, error) {
parsers, ok := parsersForKind[kind]
if !ok {
return nil, fmt.Errorf("no parser available for configuration of kind %q", kind)
}
parser, ok := parsers[version]
if !ok {
return nil, fmt.Errorf("no parser available for configuration of kind %q and version %q", kind, version)
}
return parser, nil
}
func mergeConfigs(config *Config, subconfig *Config) {
for host, headerer := range subconfig.AuthPerHost {
config.AuthPerHost[host] = headerer
}
for registry, creds := range subconfig.DockerCredentialsPerRegistry {
config.DockerCredentialsPerRegistry[registry] = creds
}
if subconfig.Paths.DataDir != "" {
config.Paths.DataDir = subconfig.Paths.DataDir
}
if subconfig.Paths.Stage1ImagesDir != "" {
config.Paths.Stage1ImagesDir = subconfig.Paths.Stage1ImagesDir
}
if subconfig.Stage1.Name != "" {
config.Stage1.Name = subconfig.Stage1.Name
config.Stage1.Version = subconfig.Stage1.Version
}
if subconfig.Stage1.Location != "" {
config.Stage1.Location = subconfig.Stage1.Location
}
}