config.go 8.35 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package config

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"regexp"
	"time"
)

type (
Lukas Burgey's avatar
Lukas Burgey committed
15
	// A ServiceID locally identifies a provided Service.
Lukas Burgey's avatar
Lukas Burgey committed
16
17
18
19
20
21
22
23
24
25
26
	ServiceID string

	// Service for which we do deployments
	Service struct {
		Name        string `json:"name"`
		Command     string `json:"command"`
		Description string `json:"description"`
	}

	// RabbitMQConfig is used for the amqp source
	RabbitMQConfig struct {
Lukas Burgey's avatar
Lukas Burgey committed
27
28
		Exchanges []string `json:"exchanges"`
		Vhost     string   `json:"vhost"`
Lukas Burgey's avatar
Lukas Burgey committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
	}

	fetchedConfig struct {
		RabbitMQConfig RabbitMQConfig `json:"rabbitmq_config"`
		Site           string         `json:"site"`
	}

	// 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
		Sequential bool `json:"sequential_execution"`
		Scripts    bool `json:"scripts"`
		Backend    bool `json:"backend"`
	}

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

Lukas Burgey's avatar
Lukas Burgey committed
49
		// The Username of this client, registered at the backend.
Lukas Burgey's avatar
Lukas Burgey committed
50
		Username string `json:"username"`
Lukas Burgey's avatar
Lukas Burgey committed
51
52

		// The Password of this client, registered at the backend.
Lukas Burgey's avatar
Lukas Burgey committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
		Password string `json:"password"`

		// Services maps an (arbitrary) service identifier to service structs
		// the service identifiers are referenced in GroupToServiceIDs and EntitlementToServiceIDs
		Services map[ServiceID]Service

		// 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
		GroupToServiceIDs map[string][]ServiceID `json:"group_to_service_ids"`

		// 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
		EntitlementToServiceIDs map[string][]ServiceID `json:"entitlement_to_service_ids"`

		// FetchIntervalString gets parsed by time.ParseDuration
		FetchIntervalString string `json:"fetch_interval"`
Lukas Burgey's avatar
Lukas Burgey committed
73

Lukas Burgey's avatar
Lukas Burgey committed
74
75
76
		// ReconnectTimeout gets parsed by time.ParseDuration
		ReconnectTimeoutString string `json:"reconnect_timeout"`

Lukas Burgey's avatar
Lukas Burgey committed
77
78
		// After the duration of FetchInterval the client will fetch updates using the REST
		// interface.
Lukas Burgey's avatar
Lukas Burgey committed
79
		FetchInterval time.Duration
Lukas Burgey's avatar
Lukas Burgey committed
80
81
82
83

		// We reconnect to RabbitMQ after ReconnectTimeout.
		ReconnectTimeout time.Duration

Lukas Burgey's avatar
Lukas Burgey committed
84
85
		RabbitMQConfig RabbitMQConfig

Lukas Burgey's avatar
Lukas Burgey committed
86
87
88
89
		// The Site is the name of the site of this client. It is fetched from the backend.
		Site string

		// Debug flags control the log levels of the client.
Lukas Burgey's avatar
Lukas Burgey committed
90
91
92
93
94
95
96
97
98
99
100
101
102
		Debug DebugConfig `json:"debug"`
	}

	// strippedConfig is sent to the backend on startup
	strippedConfig struct {
		Services                map[ServiceID]Service  `json:"services"`
		GroupToServiceIDs       map[string][]ServiceID `json:"group_to_service_ids"`
		EntitlementToServiceIDs map[string][]ServiceID `json:"entitlement_to_service_ids"`
	}
)

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

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
222
223
		conf.ReconnectTimeout = defaultReconnectTimeout
		log.Printf("[Conf] Using default reconnect_timeout of %v", conf.ReconnectTimeout)
Lukas Burgey's avatar
Lukas Burgey committed
224
	} else {
Lukas Burgey's avatar
Lukas Burgey committed
225
		conf.ReconnectTimeout, err = time.ParseDuration(conf.ReconnectTimeoutString)
Lukas Burgey's avatar
Lukas Burgey committed
226
227
228
229
		if err != nil {
			log.Printf("[Conf] Error parsing reconnect timeout: %s", err)
			err = nil

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

	// 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
func ReadConfig(configFile string) (conf *Config, err error) {
	log.Printf("[Conf] Reading config file %s", configFile)

	configBytes, err := ioutil.ReadFile(configFile)
	if err != nil {
		return
	}

	conf = new(Config)
	err = json.Unmarshal(configBytes, conf)
	if err != nil {
		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
}