base_app.go 11 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Copyright 2018 The ksonnet 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 app

import (
19
	"net/http"
20
	"path/filepath"
bryanl's avatar
bryanl committed
21
	"sync"
22

bryanl's avatar
bryanl committed
23
	"github.com/ghodss/yaml"
24
	stringutils "github.com/ksonnet/ksonnet/pkg/util/strings"
bryanl's avatar
bryanl committed
25
	"github.com/pkg/errors"
26
	log "github.com/sirupsen/logrus"
27 28 29 30
	"github.com/spf13/afero"
)

type baseApp struct {
31 32 33 34 35 36
	root       string
	fs         afero.Fs
	httpClient *http.Client

	// LibUpdater updates ksonnet lib versions.
	libUpdater KSLibUpdater
bryanl's avatar
bryanl committed
37 38 39 40 41

	config    *Spec
	overrides *Override

	mu sync.Mutex
42 43

	load func() error
44 45
}

46
func newBaseApp(fs afero.Fs, root string, httpClient *http.Client) *baseApp {
47
	ba := &baseApp{
48 49 50 51 52 53
		fs:         fs,
		httpClient: httpClient,
		libUpdater: ksLibUpdater{
			fs:         fs,
			httpClient: httpClient,
		},
bryanl's avatar
bryanl committed
54 55 56
		root:   root,
		config: &Spec{},
		overrides: &Override{
57
			Environments: EnvironmentConfigs{},
58
			Registries:   RegistryConfigs{},
bryanl's avatar
bryanl committed
59
		},
60
	}
61 62
	ba.load = ba.doLoad
	return ba
63 64
}

bryanl's avatar
bryanl committed
65 66 67 68 69 70 71 72 73 74 75
func (ba *baseApp) CurrentEnvironment() string {
	currentPath := filepath.Join(ba.root, currentEnvName)
	data, err := afero.ReadFile(ba.fs, currentPath)
	if err != nil {
		return ""
	}

	return string(data)
}

func (ba *baseApp) SetCurrentEnvironment(name string) error {
76 77 78 79 80 81 82 83 84 85 86 87 88 89
	envs, err := ba.Environments()
	if err != nil {
		return errors.Wrap(err, "loading environments")
	}

	var envNames []string
	for _, env := range envs {
		envNames = append(envNames, env.Name)
	}

	if !stringutils.InSlice(name, envNames) {
		return errors.Errorf("environment %q does not exist", name)
	}

bryanl's avatar
bryanl committed
90 91 92 93
	currentPath := filepath.Join(ba.root, currentEnvName)
	return afero.WriteFile(ba.fs, currentPath, []byte(name), DefaultFilePermissions)
}

bryanl's avatar
bryanl committed
94 95 96 97 98 99
func (ba *baseApp) configPath() string {
	return filepath.Join(ba.root, "app.yaml")
}

func (ba *baseApp) overridePath() string {
	return filepath.Join(ba.root, "app.override.yaml")
100 101
}

bryanl's avatar
bryanl committed
102
func (ba *baseApp) save() error {
103 104
	log := log.WithField("action", "baseApp.save")

bryanl's avatar
bryanl committed
105 106 107
	ba.mu.Lock()
	defer ba.mu.Unlock()

108 109 110 111 112 113 114 115
	if ba.config == nil {
		return errors.Errorf("cannot save nil app configuration")
	}

	// Signal we have converted to new app version
	ba.config.APIVersion = DefaultAPIVersion
	log.Debugf("saving app version %v", ba.config.APIVersion)

bryanl's avatar
bryanl committed
116
	configData, err := yaml.Marshal(ba.config)
117
	if err != nil {
bryanl's avatar
bryanl committed
118 119 120 121 122
		return errors.Wrap(err, "convert application configuration to YAML")
	}

	if err = afero.WriteFile(ba.fs, ba.configPath(), configData, DefaultFilePermissions); err != nil {
		return errors.Wrapf(err, "write %s", ba.configPath())
123 124
	}

125
	if err = removeOverride(ba.fs, ba.root); err != nil {
bryanl's avatar
bryanl committed
126 127 128
		return errors.Wrap(err, "clean overrides")
	}

129 130
	if ba.overrides.IsDefined() {
		return SaveOverride(defaultYAMLEncoder, ba.fs, ba.root, ba.overrides)
bryanl's avatar
bryanl committed
131 132 133 134 135
	}

	return nil
}

136
func (ba *baseApp) doLoad() error {
bryanl's avatar
bryanl committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150
	ba.mu.Lock()
	defer ba.mu.Unlock()

	configData, err := afero.ReadFile(ba.fs, ba.configPath())
	if err != nil {
		return errors.Wrapf(err, "read %s", ba.configPath())
	}

	var config Spec
	if err = yaml.Unmarshal(configData, &config); err != nil {
		return errors.Wrapf(err, "unmarshal application YAML config")
	}

	exists, err := afero.Exists(ba.fs, ba.overridePath())
151 152 153 154
	if err != nil {
		return err
	}

bryanl's avatar
bryanl committed
155
	if len(config.Environments) == 0 {
156
		config.Environments = EnvironmentConfigs{}
bryanl's avatar
bryanl committed
157 158 159
	}

	if len(config.Registries) == 0 {
160
		config.Registries = RegistryConfigs{}
bryanl's avatar
bryanl committed
161 162 163
	}

	override := Override{
164
		Environments: EnvironmentConfigs{},
165
		Registries:   RegistryConfigs{},
bryanl's avatar
bryanl committed
166 167 168 169 170 171 172 173 174 175
	}
	if exists {
		overrideData, err := afero.ReadFile(ba.fs, ba.overridePath())
		if err != nil {
			return errors.Wrapf(err, "read %s", ba.overridePath())
		}
		if err = yaml.Unmarshal(overrideData, &override); err != nil {
			return errors.Wrapf(err, "unmarshal override YAML config")
		}

176 177
		if err = override.Validate(); err != nil {
			return errors.Wrap(err, "validating override")
bryanl's avatar
bryanl committed
178 179 180
		}

		if len(override.Environments) == 0 {
181
			override.Environments = EnvironmentConfigs{}
bryanl's avatar
bryanl committed
182 183 184
		}

		if len(override.Registries) == 0 {
185
			override.Registries = RegistryConfigs{}
bryanl's avatar
bryanl committed
186 187
		}

188 189 190 191 192 193 194 195
		for k := range override.Registries {
			override.Registries[k].isOverride = true
		}

		for k := range override.Environments {
			override.Environments[k].isOverride = true
		}

bryanl's avatar
bryanl committed
196 197 198 199 200 201 202 203
	}

	ba.overrides = &override
	ba.config = &config

	return ba.config.validate()
}

204
func (ba *baseApp) AddRegistry(newReg *RegistryConfig, isOverride bool) error {
bryanl's avatar
bryanl committed
205 206 207 208
	if err := ba.load(); err != nil {
		return errors.Wrap(err, "load configuration")
	}

209 210 211 212
	if newReg.Name == "" {
		return ErrRegistryNameInvalid
	}

bryanl's avatar
bryanl committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226
	if isOverride {
		_, exists := ba.overrides.Registries[newReg.Name]
		if exists {
			return ErrRegistryExists
		}

		newReg.isOverride = true

		ba.overrides.Registries[newReg.Name] = newReg
		return ba.save()
	}

	_, exists := ba.config.Registries[newReg.Name]
	if exists {
227 228 229
		return ErrRegistryExists
	}

bryanl's avatar
bryanl committed
230 231
	newReg.isOverride = false
	ba.config.Registries[newReg.Name] = newReg
232

bryanl's avatar
bryanl committed
233
	return ba.save()
234 235
}

236 237 238 239
// UpdateLib adds or updates a library reference.
// env is optional - if provided the reference is scoped under the environment,
// otherwise it is globally scoped.
func (ba *baseApp) UpdateLib(name string, env string, libSpec *LibraryConfig) error {
bryanl's avatar
bryanl committed
240 241
	if err := ba.load(); err != nil {
		return errors.Wrap(err, "load configuration")
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
	if ba.config == nil {
		return errors.Errorf("invalid app - configuration is nil")
	}

	if libSpec.Name != name {
		return errors.Errorf("library name mismatch: %v vs %v", libSpec.Name, name)
	}

	// TODO support app overrides

	switch env {
	case "":
		// Globally scoped
		ba.config.Libraries[name] = libSpec
	default:
		// Scoped by environment
		e, ok := ba.config.GetEnvironmentConfig(env)
		if !ok {
			return errors.Errorf("invalid environment: %v", env)
		}

		if e.Libraries == nil {
			// We may want to move this into EnvrionmentConfig unmarshaling code.
			e.Libraries = LibraryConfigs{}
		}
		e.Libraries[name] = libSpec

		if err := ba.config.UpdateEnvironmentConfig(env, e); err != nil {
			return errors.Wrapf(err, "updating environment %v", env)
		}
	}

bryanl's avatar
bryanl committed
276
	return ba.save()
277 278
}

279
// UpdateRegistry updates a registry spec and persists in app[.override].yaml
280
func (ba *baseApp) UpdateRegistry(spec *RegistryConfig) error {
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
	if err := ba.load(); err != nil {
		return errors.Wrap(err, "load configuration")
	}

	if spec.Name == "" {
		return ErrRegistryNameInvalid
	}

	// Figure out where the registry is defined (app or override)
	var ok, okOverride bool
	if ba.config != nil {
		_, ok = ba.config.Registries[spec.Name]
	}
	if ba.overrides != nil {
		_, okOverride = ba.overrides.Registries[spec.Name]
	}

	if !ok && !okOverride {
		return errors.Errorf("registry not found: %v", spec.Name)
	}

	if ok && okOverride {
		return errors.Errorf("registry %v found in both app.yaml and app.override.yaml", spec.Name)
	}

	if ok {
		ba.config.Registries[spec.Name] = spec
	} else {
		ba.overrides.Registries[spec.Name] = spec
	}

	return ba.save()
}

315 316 317 318
func (ba *baseApp) Fs() afero.Fs {
	return ba.fs
}

319 320 321 322
func (ba *baseApp) HTTPClient() *http.Client {
	return ba.httpClient
}

323 324 325 326 327
func (ba *baseApp) Root() string {
	return ba.root
}

func (ba *baseApp) EnvironmentParams(envName string) (string, error) {
bryanl's avatar
bryanl committed
328 329 330
	if envName == "" {
		return "", errors.New("environment name is blank")
	}
331 332 333
	envParamsPath := filepath.Join(ba.Root(), EnvironmentDirName, envName, "params.libsonnet")
	b, err := afero.ReadFile(ba.Fs(), envParamsPath)
	if err != nil {
bryanl's avatar
bryanl committed
334
		return "", errors.Wrapf(err, "unable to read params for environment %s", envName)
335 336 337 338
	}

	return string(b), nil
}
bryanl's avatar
bryanl committed
339 340 341 342

func (ba *baseApp) VendorPath() string {
	return filepath.Join(ba.Root(), "vendor")
}
343 344 345 346 347 348 349

// Environment returns the spec for an environment.
func (ba *baseApp) Environment(name string) (*EnvironmentConfig, error) {
	if err := ba.load(); err != nil {
		return nil, errors.Wrap(err, "load configuration")
	}

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
	e := ba.mergedEnvironment(name)
	if e == nil {
		return nil, errors.Errorf("environment %q was not found", name)
	}
	return e, nil
}

func deepCopyLibraries(src LibraryConfigs) LibraryConfigs {
	if src == nil {
		return LibraryConfigs(nil)
	}

	lc := LibraryConfigs{}
	for k, v := range src {
		c := *v
		lc[k] = &c
	}
	return lc
}

func deepCopyEnvironmentConfig(src EnvironmentConfig) *EnvironmentConfig {
	e := src

	if src.Destination != nil {
		d := *src.Destination
		e.Destination = &d
	}
	if src.Targets != nil {
		t := make([]string, len(src.Targets))
		copy(t, src.Targets)
		e.Targets = t
381
	}
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
	if src.Libraries != nil {
		e.Libraries = deepCopyLibraries(src.Libraries)
	}

	return &e
}

// mergedEnvrionment returns a fresh copy of the named environment, merged with
// optional overrides if present. Note overrides cannot override environment-scoped library
// references.
// Returns nil if the envrionment is not present and non-nil in either primary configuration
// or overrides.
func (ba *baseApp) mergedEnvironment(name string) *EnvironmentConfig {
	var hasPrimary, hasOverride bool
	var primary, override *EnvironmentConfig
397

398 399 400 401 402 403 404 405 406 407
	if ba.config != nil {
		primary, hasPrimary = ba.config.Environments[name]
		if primary == nil {
			hasPrimary = false
		}
	}
	if ba.overrides != nil {
		override, hasOverride = ba.overrides.Environments[name]
		if override == nil {
			hasOverride = false
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
	switch {
	case hasPrimary && !hasOverride:
		e := deepCopyEnvironmentConfig(*primary)
		e.isOverride = false
		return e
	case hasPrimary && hasOverride:
		combined := deepCopyEnvironmentConfig(*primary)
		combined.Name = override.Name
		combined.KubernetesVersion = override.KubernetesVersion
		combined.Path = override.Path
		if override.Destination != nil {
			d := *override.Destination
			combined.Destination = &d
		}
		if override.Targets != nil {
			t := make([]string, len(override.Targets))
			copy(t, override.Targets)
			combined.Targets = t
		}
		combined.isOverride = true
		return combined
	case hasOverride:
		e := deepCopyEnvironmentConfig(*override)
		e.isOverride = true
		return e
	default:
		return nil
	}
439 440
}

441 442
// Environments returns all environment specs, merged with any corresponding overrides.
// Note overrides cannot override environment libraries.
443 444 445 446 447
func (ba *baseApp) Environments() (EnvironmentConfigs, error) {
	if err := ba.load(); err != nil {
		return nil, errors.Wrap(err, "load configuration")
	}

448
	// Build merged list of keys
449
	environments := EnvironmentConfigs{}
450 451 452 453
	if ba.config != nil {
		for k := range ba.config.Environments {
			environments[k] = nil
		}
454
	}
455 456 457 458 459 460 461 462 463 464 465 466
	if ba.overrides != nil {
		for k := range ba.overrides.Environments {
			environments[k] = nil
		}
	}

	for k := range environments {
		e := ba.mergedEnvironment(k)
		if e == nil {
			delete(environments, k)
			continue
		}
467

468
		environments[k] = e
469 470 471 472
	}

	return environments, nil
}