config.go 9.71 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
2
3
4
5
6
package config

import (
	"bytes"
	"encoding/json"
	"fmt"
7
	"io"
Lukas Burgey's avatar
Lukas Burgey committed
8
9
10
11
	"io/ioutil"
	"log"
	"net/http"
	"regexp"
12
	"strings"
Lukas Burgey's avatar
Lukas Burgey committed
13
	"time"
14
15

	"gopkg.in/yaml.v2"
Lukas Burgey's avatar
Lukas Burgey committed
16
17
18
)

type (
Lukas Burgey's avatar
Lukas Burgey committed
19
	// A ServiceID locally identifies a provided Service.
Lukas Burgey's avatar
Lukas Burgey committed
20
21
22
23
	ServiceID string

	// Service for which we do deployments
	Service struct {
24
25
26
27
28
29
30
		// Name is the name of the service. It is presented to users.
		Name string `json:"name" yaml:"name"`

		// Command is a shell command to invoke the adapter
		Command string `json:"command" yaml:"command"`

		// Description describes the service. It is presented to users
31
		Description string `json:"description" yaml:"description"`
32
33
34
35
36

		// ContactEmail is an email
		ContactEmail string `json:"contact_email" yaml:"contact_email"`
		// ContactDescription describes the person contable using ContactEmail
		ContactDescription string `json:"contact_description" yaml:"contact_description"`
Lukas Burgey's avatar
Lukas Burgey committed
37
38
39
40
	}

	// RabbitMQConfig is used for the amqp source
	RabbitMQConfig struct {
41
42
		Exchanges []string `json:"exchanges" yaml:"exchanges"`
		Vhost     string   `json:"vhost" yaml:"vhost"`
Lukas Burgey's avatar
Lukas Burgey committed
43
44
45
	}

	fetchedConfig struct {
46
47
		RabbitMQConfig RabbitMQConfig `json:"rabbitmq_config" yaml:"rabbitmq_config"`
		Site           string         `json:"site" yaml:"site"`
Lukas Burgey's avatar
Lukas Burgey committed
48
49
50
51
52
	}

	// The DebugConfig sets the debuging levels for components of the client.
	DebugConfig struct {
		// Sequential causes the execution of only one deployment at a time for debugging purposes
53
54
55
		Sequential bool `json:"sequential_execution" yaml:"sequential_execution"`
		Scripts    bool `json:"scripts" yaml:"scripts"`
		Backend    bool `json:"backend" yaml:"backend"`
Lukas Burgey's avatar
Lukas Burgey committed
56
57
58
59
	}

	// Config is the structure of our config file
	Config struct {
Lukas Burgey's avatar
Lukas Burgey committed
60
		// The Hostname of the feudal backends host
61
		Hostname string `json:"feudal_backend_host" yaml:"feudal_backend_host"`
Lukas Burgey's avatar
Lukas Burgey committed
62

Lukas Burgey's avatar
Lukas Burgey committed
63
		// The Username of this client, registered at the backend.
64
		Username string `json:"username" yaml:"username"`
Lukas Burgey's avatar
Lukas Burgey committed
65
66

		// The Password of this client, registered at the backend.
67
		Password string `json:"password" yaml:"password"`
Lukas Burgey's avatar
Lukas Burgey committed
68
69
70

		// Services maps an (arbitrary) service identifier to service structs
		// the service identifiers are referenced in GroupToServiceIDs and EntitlementToServiceIDs
71
		Services map[ServiceID]Service `json:"services" yaml:"services"`
Lukas Burgey's avatar
Lukas Burgey committed
72
73
74
75
76

		// GroupToServiceIDs determines which services are provided for users of the
		// group
		// maps a group name to service identifiers of the services
		// services are declared in Config.Services
77
		GroupToServiceIDs map[string][]ServiceID `json:"group_to_service_ids" yaml:"group_to_service_ids"`
Lukas Burgey's avatar
Lukas Burgey committed
78
79
80
81
82

		// EntitlementToServiceIDs determines which services are provided for users of the
		// entitlement
		// maps an entitlement to service identifiers of the services
		// services are declared in Config.Services
83
		EntitlementToServiceIDs map[string][]ServiceID `json:"entitlement_to_service_ids" yaml:"entitlement_to_service_ids"`
Lukas Burgey's avatar
Lukas Burgey committed
84
85

		// FetchIntervalString gets parsed by time.ParseDuration
86
		FetchIntervalString string `json:"fetch_interval,omitempty" yaml:"fetch_interval,omitempty"`
Lukas Burgey's avatar
Lukas Burgey committed
87

Lukas Burgey's avatar
Lukas Burgey committed
88
		// ReconnectTimeout gets parsed by time.ParseDuration
89
		ReconnectTimeoutString string `json:"reconnect_timeout,omitempty" yaml:"reconnect_timeout,omitempty"`
Lukas Burgey's avatar
Lukas Burgey committed
90
91

		// Debug flags control the log levels of the client.
92
		Debug DebugConfig `json:"debug,omitempty" yaml:"debug,omitempty"`
Lukas Burgey's avatar
Lukas Burgey committed
93

Lukas Burgey's avatar
Lukas Burgey committed
94
95
		// After the duration of FetchInterval the client will fetch updates using the REST
		// interface.
96
		FetchInterval time.Duration `json:"-" yaml:"-"`
Lukas Burgey's avatar
Lukas Burgey committed
97
98

		// We reconnect to RabbitMQ after ReconnectTimeout.
99
		ReconnectTimeout time.Duration `json:"-" yaml:"-"`
Lukas Burgey's avatar
Lukas Burgey committed
100

101
		RabbitMQConfig RabbitMQConfig `json:"-" yaml:"-"`
Lukas Burgey's avatar
Lukas Burgey committed
102

Lukas Burgey's avatar
Lukas Burgey committed
103
		// The Site is the name of the site of this client. It is fetched from the backend.
104
		Site string `json:"-" yaml:"-"`
Lukas Burgey's avatar
Lukas Burgey committed
105
106
107
108
	}

	// strippedConfig is sent to the backend on startup
	strippedConfig struct {
109
110
111
		Services                map[ServiceID]Service  `json:"services" yaml:"services"`
		GroupToServiceIDs       map[string][]ServiceID `json:"group_to_service_ids" yaml:"group_to_service_ids"`
		EntitlementToServiceIDs map[string][]ServiceID `json:"entitlement_to_service_ids" yaml:"entitlement_to_service_ids"`
Lukas Burgey's avatar
Lukas Burgey committed
112
113
114
115
116
	}
)

const (
	defaultFetchInterval    = 30 * time.Minute
Lukas Burgey's avatar
Lukas Burgey committed
117
	defaultReconnectTimeout = 30 * time.Second
Lukas Burgey's avatar
Lukas Burgey committed
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
)

func (s Service) String() string {
	return s.Name
}

// GetServices resolves service ids into services
func (conf *Config) GetServices(sids []ServiceID) (services []Service, err error) {
	var ok bool
	services = make([]Service, len(sids))

	for i, sid := range sids {
		if services[i], ok = conf.Services[sid]; !ok {
			services = nil
			err = fmt.Errorf("Service with service ID '%s' does no exist", sid)
			return
		}
	}
	return
}

// Sync sends our config to the backend to inform it about changes
func (conf *Config) Sync() (err error) {

	if conf.Debug.Backend {
		log.Printf("[Conf] Synchronising configuration with %v", conf.Hostname)
	}

	var (
		strippedConfigBytes []byte
		req                 *http.Request
		resp                *http.Response
		fetchedConfig       fetchedConfig
	)

	// we inform the backend which services we provide
	strippedConfigBytes, err = json.Marshal(strippedConfig{
		Services:                conf.Services,
		GroupToServiceIDs:       conf.GroupToServiceIDs,
		EntitlementToServiceIDs: conf.EntitlementToServiceIDs,
	})
	if err != nil {
		err = fmt.Errorf("Error syncing config: %s", err)
		return
	}

	// update the services tracked by the backend
	req, err = http.NewRequest(
		"PUT",
		"https://"+conf.Hostname+"/backend/clientapi/config",
		bytes.NewReader(strippedConfigBytes),
	)
	if err != nil {
		err = fmt.Errorf("Error requesting remote config: %s", err)
		return
	}

	req.SetBasicAuth(conf.Username, conf.Password)
	req.Header.Set("Content-Type", "application/json")
	resp, err = (&http.Client{}).Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		err = fmt.Errorf("Error reading remote config: %s", err)
		return
	}
	if resp.StatusCode != 200 {
		err = fmt.Errorf("Error with remote config request: Response was %v", resp.Status)
		return
	}

	err = json.Unmarshal(body, &fetchedConfig)
	if err != nil {
		err = fmt.Errorf("Error parsing remote configuration: %s %s", err, body)
		return
	}

	conf.RabbitMQConfig = fetchedConfig.RabbitMQConfig
	conf.Site = fetchedConfig.Site

	log.Printf("[Conf] Synchronised configuration with %v", conf.Hostname)

	return
}

func (conf *Config) validateConfig() (err error) {

	// check the config values
	if conf.Hostname == "" {
		return fmt.Errorf("No 'hostname' in config")
	}
	if conf.Username == "" {
		return fmt.Errorf("No 'username' in config")
	}
	if conf.Password == "" {
		return fmt.Errorf("No 'password' in config")
	}

	// try to parse duration, otherwise use default
	if conf.FetchIntervalString == "" {
		conf.FetchInterval = defaultFetchInterval
		log.Printf("[Conf] Using default fetch_interval of %v", conf.FetchInterval)
	} else {
		conf.FetchInterval, err = time.ParseDuration(conf.FetchIntervalString)
		if err != nil {
			log.Printf("[Conf] Error parsing fetch interval: %s", err)
			err = nil

			conf.FetchInterval = defaultFetchInterval
			log.Printf("[Conf] Using default fetch_interval of %v", conf.FetchInterval)
		}
	}

	if conf.ReconnectTimeoutString == "" {
Lukas Burgey's avatar
Lukas Burgey committed
236
237
		conf.ReconnectTimeout = defaultReconnectTimeout
		log.Printf("[Conf] Using default reconnect_timeout of %v", conf.ReconnectTimeout)
Lukas Burgey's avatar
Lukas Burgey committed
238
	} else {
Lukas Burgey's avatar
Lukas Burgey committed
239
		conf.ReconnectTimeout, err = time.ParseDuration(conf.ReconnectTimeoutString)
Lukas Burgey's avatar
Lukas Burgey committed
240
241
242
243
		if err != nil {
			log.Printf("[Conf] Error parsing reconnect timeout: %s", err)
			err = nil

Lukas Burgey's avatar
Lukas Burgey committed
244
245
			conf.ReconnectTimeout = defaultReconnectTimeout
			log.Printf("[Conf] Using default reconnect_timeout of %v", conf.ReconnectTimeout)
Lukas Burgey's avatar
Lukas Burgey committed
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
		}
	}

	// check that the services names are unique
	var exists bool
	serviceNames := make(map[string]struct{}, len(conf.Services))
	for _, service := range conf.Services {
		if _, exists = serviceNames[service.Name]; !exists {
			serviceNames[service.Name] = struct{}{}
		} else {
			return fmt.Errorf("Service name is ambiguous: %s", service.Name)
		}
	}

	// check if referenced service ids exist
	for _, sids := range conf.GroupToServiceIDs {
		for _, sid := range sids {
			if _, exists = conf.Services[sid]; !exists {
				return fmt.Errorf("GroupToServiceIDs: service ID '%s' does not exist", sid)
			}
		}
	}
	for _, sids := range conf.EntitlementToServiceIDs {
		for _, sid := range sids {
			if _, exists = conf.Services[sid]; !exists {
				return fmt.Errorf("EntitlementToServiceIDs: service ID '%s' does not exist", sid)
			}
		}
	}
	return
}

// ReadConfig reads a config file and validates it
279
func ReadConfig(r io.Reader, fileName string) (conf *Config, err error) {
280
	configBytes, err := ioutil.ReadAll(r)
Lukas Burgey's avatar
Lukas Burgey committed
281
282
283
284
285
	if err != nil {
		return
	}

	conf = new(Config)
286

287
	if strings.HasSuffix(fileName, ".yaml") {
288
289
290
291
292
		err = yaml.Unmarshal(configBytes, conf)
		if err != nil {
			err = fmt.Errorf("Error decoding yaml: %s", err)
			return
		}
293
	} else if strings.HasSuffix(fileName, ".json") {
294
295
296
297
298
299
300
		err = json.Unmarshal(configBytes, conf)
		if err != nil {
			err = fmt.Errorf("Error decoding json: %s", err)
			return
		}
	} else {
		err = fmt.Errorf("Incompatible config format, supported are: YAML or JSON")
Lukas Burgey's avatar
Lukas Burgey committed
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
		return
	}

	err = conf.validateConfig()
	if err != nil {
		err = fmt.Errorf("Error validating config:\n\t%s", err)
		return
	}

	// strip the group authority from entitlement names
	nameExtractor := regexp.MustCompile("^(.*?)#")
	for entName, entServices := range conf.EntitlementToServiceIDs {
		match := nameExtractor.FindStringSubmatch(entName)
		if len(match) == 2 {
			delete(conf.EntitlementToServiceIDs, entName)
			conf.EntitlementToServiceIDs[match[1]] = entServices
		}
	}

	log.Printf("[Conf] Services:     %s", conf.Services)
	log.Printf("[Conf] Groups:       %s", conf.GroupToServiceIDs)
	log.Printf("[Conf] Entitlements: %s", conf.EntitlementToServiceIDs)

	return
}