This file is indexed.

/usr/share/gocode/src/github.com/ctdk/goiardi/environment/environment.go is in golang-github-ctdk-goiardi-dev 0.11.2-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
/* Environments. */

/*
 * Copyright (c) 2013-2016, Jeremy Bingham (<jeremy@goiardi.gl>)
 *
 * 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 environment provides... environments. They're like roles, but more
// so, except without run lists. They're a convenient way to share many
// attributes and cookbook version constraints among many servers.
package environment

import (
	"database/sql"
	"fmt"
	"github.com/ctdk/goiardi/config"
	"github.com/ctdk/goiardi/cookbook"
	"github.com/ctdk/goiardi/datastore"
	"github.com/ctdk/goiardi/indexer"
	"github.com/ctdk/goiardi/util"
	"net/http"
	"sort"
)

// ChefEnvironment is a collection of attributes and cookbook versions for
// organizing how nodes are deployed.
type ChefEnvironment struct {
	Name             string                 `json:"name"`
	ChefType         string                 `json:"chef_type"`
	JSONClass        string                 `json:"json_class"`
	Description      string                 `json:"description"`
	Default          map[string]interface{} `json:"default_attributes"`
	Override         map[string]interface{} `json:"override_attributes"`
	CookbookVersions map[string]string      `json:"cookbook_versions"`
}

// New creates a new environment, returning an error if the environment already
// exists or you try to create an environment named "_default".
func New(name string) (*ChefEnvironment, util.Gerror) {
	if !util.ValidateEnvName(name) {
		err := util.Errorf("Field 'name' invalid")
		err.SetStatus(http.StatusBadRequest)
		return nil, err
	}

	var found bool
	if config.UsingDB() {
		var eerr error
		found, eerr = checkForEnvironmentSQL(datastore.Dbh, name)
		if eerr != nil {
			err := util.CastErr(eerr)
			err.SetStatus(http.StatusInternalServerError)
			return nil, err
		}
	} else {
		ds := datastore.New()
		_, found = ds.Get("env", name)
	}
	if found || name == "_default" {
		err := util.Errorf("Environment already exists")
		return nil, err
	}

	env := &ChefEnvironment{
		Name:             name,
		ChefType:         "environment",
		JSONClass:        "Chef::Environment",
		Default:          map[string]interface{}{},
		Override:         map[string]interface{}{},
		CookbookVersions: map[string]string{},
	}
	return env, nil
}

// NewFromJSON creates a new environment from JSON uploaded to the server.
func NewFromJSON(jsonEnv map[string]interface{}) (*ChefEnvironment, util.Gerror) {
	env, err := New(jsonEnv["name"].(string))
	if err != nil {
		return nil, err
	}
	err = env.UpdateFromJSON(jsonEnv)
	if err != nil {
		return nil, err
	}
	return env, nil
}

// UpdateFromJSON updates an existing environment from JSON uploaded to the
// server.
func (e *ChefEnvironment) UpdateFromJSON(jsonEnv map[string]interface{}) util.Gerror {
	if e.Name != jsonEnv["name"].(string) {
		err := util.Errorf("Environment name %s and %s from JSON do not match", e.Name, jsonEnv["name"].(string))
		return err
	} else if e.Name == "_default" {
		err := util.Errorf("The '_default' environment cannot be modified.")
		err.SetStatus(http.StatusMethodNotAllowed)
		return err
	}

	/* Validations */
	validElements := []string{"name", "chef_type", "json_class", "description", "default_attributes", "override_attributes", "cookbook_versions"}
ValidElem:
	for k := range jsonEnv {
		for _, i := range validElements {
			if k == i {
				continue ValidElem
			}
		}
		err := util.Errorf("Invalid key %s in request body", k)
		return err
	}

	var verr util.Gerror

	attrs := []string{"default_attributes", "override_attributes"}
	for _, a := range attrs {
		jsonEnv[a], verr = util.ValidateAttributes(a, jsonEnv[a])
		if verr != nil {
			return verr
		}
	}

	jsonEnv["json_class"], verr = util.ValidateAsFieldString(jsonEnv["json_class"])
	if verr != nil {
		if verr.Error() == "Field 'name' nil" {
			jsonEnv["json_class"] = e.JSONClass
		} else {
			return verr
		}
	} else {
		if jsonEnv["json_class"].(string) != "Chef::Environment" {
			verr = util.Errorf("Field 'json_class' invalid")
			return verr
		}
	}

	jsonEnv["chef_type"], verr = util.ValidateAsFieldString(jsonEnv["chef_type"])
	if verr != nil {
		if verr.Error() == "Field 'name' nil" {
			jsonEnv["chef_type"] = e.ChefType
		} else {
			return verr
		}
	} else {
		if jsonEnv["chef_type"].(string) != "environment" {
			verr = util.Errorf("Field 'chef_type' invalid")
			return verr
		}
	}

	jsonEnv["cookbook_versions"], verr = util.ValidateAttributes("cookbook_versions", jsonEnv["cookbook_versions"])
	if verr != nil {
		return verr
	}
	for k, v := range jsonEnv["cookbook_versions"].(map[string]interface{}) {
		if !util.ValidateEnvName(k) || k == "" {
			merr := util.Errorf("Cookbook name %s invalid", k)
			merr.SetStatus(http.StatusBadRequest)
			return merr
		}

		if v == nil {
			verr = util.Errorf("Invalid version number")
			return verr
		}
		_, verr = util.ValidateAsConstraint(v)
		if verr != nil {
			/* try validating as a version */
			v, verr = util.ValidateAsVersion(v)
			if verr != nil {
				return verr
			}
		}
	}

	jsonEnv["description"], verr = util.ValidateAsString(jsonEnv["description"])
	if verr != nil {
		if verr.Error() == "Field 'name' missing" {
			jsonEnv["description"] = ""
		} else {
			return verr
		}
	}

	e.ChefType = jsonEnv["chef_type"].(string)
	e.JSONClass = jsonEnv["json_class"].(string)
	e.Description = jsonEnv["description"].(string)
	e.Default = jsonEnv["default_attributes"].(map[string]interface{})
	e.Override = jsonEnv["override_attributes"].(map[string]interface{})
	/* clear out, then loop over the cookbook versions */
	e.CookbookVersions = make(map[string]string, len(jsonEnv["cookbook_versions"].(map[string]interface{})))
	for c, v := range jsonEnv["cookbook_versions"].(map[string]interface{}) {
		e.CookbookVersions[c] = v.(string)
	}

	return nil
}

// Get an environment.
func Get(envName string) (*ChefEnvironment, util.Gerror) {
	if envName == "_default" {
		return defaultEnvironment(), nil
	}
	var env *ChefEnvironment
	var found bool
	if config.UsingDB() {
		var err error
		env, err = getEnvironmentSQL(envName)
		if err != nil {
			var gerr util.Gerror
			if err != sql.ErrNoRows {
				gerr = util.CastErr(err)
				gerr.SetStatus(http.StatusInternalServerError)
				return nil, gerr
			}
			found = false
		} else {
			found = true
		}
	} else {
		ds := datastore.New()
		var e interface{}
		e, found = ds.Get("env", envName)
		if e != nil {
			env = e.(*ChefEnvironment)
		}
	}
	if !found {
		err := util.Errorf("Cannot load environment %s", envName)
		err.SetStatus(http.StatusNotFound)
		return nil, err
	}

	return env, nil
}

// GetMulti gets multiple environmets from a given slice of environment names.
func GetMulti(envNames []string) ([]*ChefEnvironment, util.Gerror) {
	var envs []*ChefEnvironment
	if config.UsingDB() {
		var err error
		envs, err = getMultiSQL(envNames)
		if err != nil && err != sql.ErrNoRows {
			return nil, util.CastErr(err)
		}
	} else {
		envs = make([]*ChefEnvironment, 0, len(envNames))
		for _, e := range envNames {
			eo, _ := Get(e)
			if eo != nil {
				envs = append(envs, eo)
			}
		}
	}

	return envs, nil
}

// MakeDefaultEnvironment creates the default environment on startup.
func MakeDefaultEnvironment() {
	var de *ChefEnvironment
	if config.UsingDB() {
		// The default environment is pre-created in the db schema when
		// it's loaded. Re-indexing the default environment doesn't
		// hurt anything though, so just get the usual default env and
		// index it, not bothering with these other steps that are
		// easier to do with the in-memory mode.
		de = defaultEnvironment()
	} else {
		ds := datastore.New()
		// only create the new default environment if we don't already have one
		// saved
		if _, found := ds.Get("env", "_default"); found {
			return
		}
		de = defaultEnvironment()
		ds.Set("env", de.Name, de)
	}
	indexer.IndexObj(de)
}

func defaultEnvironment() *ChefEnvironment {
	return &ChefEnvironment{
		Name:             "_default",
		ChefType:         "environment",
		JSONClass:        "Chef::Environment",
		Description:      "The default Chef environment",
		Default:          map[string]interface{}{},
		Override:         map[string]interface{}{},
		CookbookVersions: map[string]string{},
	}
}

// Save the environment. Returns an error if you try to save the "_default"
// environment.
func (e *ChefEnvironment) Save() util.Gerror {
	if e.Name == "_default" {
		err := util.Errorf("The '_default' environment cannot be modified.")
		err.SetStatus(http.StatusMethodNotAllowed)
		return err
	}
	if config.Config.UseMySQL {
		err := e.saveEnvironmentMySQL()
		if err != nil {
			return err
		}
	} else if config.Config.UsePostgreSQL {
		err := e.saveEnvironmentPostgreSQL()
		if err != nil {
			return err
		}
	} else {
		ds := datastore.New()
		ds.Set("env", e.Name, e)
	}
	indexer.IndexObj(e)
	return nil
}

// Delete the environment, returning an error if you try to delete the
// "_default" environment.
func (e *ChefEnvironment) Delete() error {
	if e.Name == "_default" {
		err := fmt.Errorf("The '_default' environment cannot be modified.")
		return err
	}
	if config.UsingDB() {
		if err := e.deleteEnvironmentSQL(); err != nil {
			return nil
		}
	} else {
		ds := datastore.New()
		ds.Delete("env", e.Name)
	}
	indexer.DeleteItemFromCollection("environment", e.Name)
	return nil
}

// GetList gets a list of all environments on this server.
func GetList() []string {
	var envList []string
	if config.UsingDB() {
		envList = getEnvironmentList()
	} else {
		ds := datastore.New()
		envList = ds.GetList("env")
		envList = append(envList, "_default")
	}
	return envList
}

// GetName returns the environment's name.
func (e *ChefEnvironment) GetName() string {
	return e.Name
}

// URLType returns the base of an environment's URL.
func (e *ChefEnvironment) URLType() string {
	return "environments"
}

func (e *ChefEnvironment) cookbookList() []*cookbook.Cookbook {
	return cookbook.AllCookbooks()
}

// AllCookbookHash returns a hash of the cookbooks and their versions available
// to this environment.
func (e *ChefEnvironment) AllCookbookHash(numVersions interface{}) map[string]interface{} {
	cbHash := make(map[string]interface{})
	cbList := e.cookbookList()
	for _, cb := range cbList {
		if cb == nil {
			continue
		}
		cbHash[cb.Name] = cb.ConstrainedInfoHash(numVersions, e.CookbookVersions[cb.Name])
	}
	return cbHash
}

// RecipeList gets a list of recipes available to this environment.
func (e *ChefEnvironment) RecipeList() []string {
	recipeList := make(map[string]string)
	cbList := e.cookbookList()
	for _, cb := range cbList {
		if cb == nil {
			continue
		}
		cbv := cb.LatestConstrained(e.CookbookVersions[cb.Name])
		if cbv == nil {
			continue
		}
		rlist, _ := cbv.RecipeList()

		for _, recipe := range rlist {
			recipeList[recipe] = recipe
		}
	}
	sortedRecipes := make([]string, len(recipeList))
	i := 0
	for k := range recipeList {
		sortedRecipes[i] = k
		i++
	}
	sort.Strings(sortedRecipes)
	return sortedRecipes
}

/* Search indexing methods */

// DocID returns the environment's name.
func (e *ChefEnvironment) DocID() string {
	return e.Name
}

// Index returns the environment's type so the indexer knows where it should go.
func (e *ChefEnvironment) Index() string {
	return "environment"
}

// Flatten the environment so it's suitable for indexing.
func (e *ChefEnvironment) Flatten() map[string]interface{} {
	return util.FlattenObj(e)
}

// AllEnvironments returns a slice of all environments on this server.
func AllEnvironments() []*ChefEnvironment {
	var environments []*ChefEnvironment
	if config.UsingDB() {
		environments = allEnvironmentsSQL()
	} else {
		envList := GetList()
		for _, e := range envList {
			en, err := Get(e)
			if err != nil {
				continue
			}
			environments = append(environments, en)
		}
	}
	return environments
}