~mvo/snappy/15.04-network-config

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
/*
 * Copyright (C) 2014-2015 Canonical Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package coreconfig

import (
	"errors"
	"io/ioutil"
	"os"
	"os/exec"
	"reflect"
	"strings"
	"syscall"

	"gopkg.in/yaml.v2"
)

const (
	tzPathEnvironment string = "UBUNTU_CORE_CONFIG_TZ_FILE"
	tzPathDefault     string = "/etc/timezone"
)

const (
	autopilotTimer         string = "snappy-autopilot.timer"
	autopilotTimerEnabled  string = "enabled"
	autopilotTimerDisabled string = "disabled"
)

var (
	modprobePath string = "/etc/modprobe.d/ubuntu-core.conf"
)

// ErrInvalidUnitStatus signals that a unit is not returning a status
// of "enabled" or "disabled".
var ErrInvalidUnitStatus = errors.New("invalid unit status")

type systemConfig struct {
	Autopilot *bool   `yaml:"autopilot,omitempty"`
	Timezone  *string `yaml:"timezone,omitempty"`
	Hostname  *string `yaml:"hostname,omitempty"`
	Modprobe  *string `yaml:"modprobe,omitempty"`
}

type coreConfig struct {
	UbuntuCore *systemConfig `yaml:"ubuntu-core"`
}

type configYaml struct {
	Config coreConfig
}

func newSystemConfig() (*systemConfig, error) {
	// TODO think of a smart way not to miss a config entry
	tz, err := getTimezone()
	if err != nil {
		return nil, err
	}

	autopilot, err := getAutopilot()
	if err != nil {
		return nil, err
	}
	hostname, err := getHostname()
	if err != nil {
		return nil, err
	}
	modprobe, err := getModprobe()
	if err != nil {
		return nil, err
	}

	config := &systemConfig{
		Autopilot: &autopilot,
		Timezone:  &tz,
		Hostname:  &hostname,
		Modprobe:  &modprobe,
	}

	return config, nil
}

// for testing purposes
var yamlMarshal = yaml.Marshal

// Get is a special configuration case for the system, for which
// there is no such entry in a package.yaml to satisfy the snappy config interface.
// This implements getting the current configuration for ubuntu-core.
func Get() (rawConfig string, err error) {
	config, err := newSystemConfig()
	if err != nil {
		return "", err
	}

	out, err := yamlMarshal(&configYaml{Config: coreConfig{config}})
	if err != nil {
		return "", err
	}

	return string(out), nil
}

// Set is used to configure settings for the system, this is meant to
// be used as an interface for snappy config to satisfy the ubuntu-core
// hook.
func Set(rawConfig string) (newRawConfig string, err error) {
	oldConfig, err := newSystemConfig()
	if err != nil {
		return "", err
	}

	var configWrap configYaml
	err = yaml.Unmarshal([]byte(rawConfig), &configWrap)
	if err != nil {
		return "", err
	}
	newConfig := configWrap.Config.UbuntuCore

	rNewConfig := reflect.ValueOf(newConfig).Elem()
	rType := rNewConfig.Type()
	for i := 0; i < rNewConfig.NumField(); i++ {
		if rNewConfig.Field(i).IsNil() {
			continue
		}

		switch rType.Field(i).Name {
		case "Timezone":
			if *oldConfig.Timezone == *newConfig.Timezone {
				continue
			}

			if err := setTimezone(*newConfig.Timezone); err != nil {
				return "", err
			}
		case "Autopilot":
			if *oldConfig.Autopilot == *newConfig.Autopilot {
				continue
			}

			if err := setAutopilot(*newConfig.Autopilot); err != nil {
				return "", err
			}
		case "Hostname":
			if *oldConfig.Hostname == *newConfig.Hostname {
				continue
			}

			if err := setHostname(*newConfig.Hostname); err != nil {
				return "", err
			}
		case "Modprobe":
			if *oldConfig.Modprobe == *newConfig.Modprobe {
				continue
			}

			if err := setModprobe(*newConfig.Modprobe); err != nil {
				return "", err
			}
		}
	}

	return Get()
}

// tzFile determines which timezone file to read from
func tzFile() string {
	tzFile := os.Getenv(tzPathEnvironment)
	if tzFile == "" {
		tzFile = tzPathDefault
	}

	return tzFile
}

// getTimezone returns the current timezone the system is set to or an error
// if it can't.
var getTimezone = func() (timezone string, err error) {
	tz, err := ioutil.ReadFile(tzFile())
	if err != nil {
		return "", err
	}

	return strings.TrimSpace(string(tz)), nil
}

// setTimezone sets the specified timezone for the system, an error is returned
// if it can't.
var setTimezone = func(timezone string) error {
	return ioutil.WriteFile(tzFile(), []byte(timezone), 0644)
}

// getModprobe returns the current modprobe config
var getModprobe = func() (string, error) {
	modprobe, err := ioutil.ReadFile(modprobePath)
	if err != nil && !os.IsNotExist(err) {
		return "", err
	}

	return string(modprobe), nil
}

// setModprobe sets the specified modprobe config
var setModprobe = func(modprobe string) error {
	return ioutil.WriteFile(modprobePath, []byte(modprobe), 0644)
}

// for testing purposes
var (
	cmdAutopilotEnabled = []string{"is-enabled", autopilotTimer}
	cmdSystemctl        = "systemctl"
)

// getAutopilot returns the autopilot state
var getAutopilot = func() (state bool, err error) {
	out, err := exec.Command(cmdSystemctl, cmdAutopilotEnabled...).Output()
	if exitErr, ok := err.(*exec.ExitError); ok {
		waitStatus := exitErr.Sys().(syscall.WaitStatus)

		// when a service is disabled the exit status is 1
		if e := waitStatus.ExitStatus(); e != 1 {
			return false, err
		}
	}

	status := strings.TrimSpace(string(out))

	if status == autopilotTimerEnabled {
		return true, nil
	} else if status == autopilotTimerDisabled {
		return false, nil
	} else {
		return false, ErrInvalidUnitStatus
	}
}

// for testing purposes
var (
	cmdEnableAutopilot  = []string{"enable", autopilotTimer}
	cmdStartAutopilot   = []string{"start", autopilotTimer}
	cmdDisableAutopilot = []string{"disable", autopilotTimer}
	cmdStopAutopilot    = []string{"stop", autopilotTimer}
)

// setAutopilot enables and starts, or stops and disables autopilot
var setAutopilot = func(stateEnabled bool) error {
	if stateEnabled {
		if err := exec.Command(cmdSystemctl, cmdEnableAutopilot...).Run(); err != nil {
			return err
		}
		if err := exec.Command(cmdSystemctl, cmdStartAutopilot...).Run(); err != nil {
			return err
		}
	} else {
		if err := exec.Command(cmdSystemctl, cmdStopAutopilot...).Run(); err != nil {
			return err
		}
		if err := exec.Command(cmdSystemctl, cmdDisableAutopilot...).Run(); err != nil {
			return err
		}
	}

	return nil
}

// getHostname returns the hostname for the host
var getHostname = os.Hostname

var hostnamePath = "/etc/writable/hostname"
var syscallSethostname = syscall.Sethostname

// setHostname sets the hostname for the host
var setHostname = func(hostname string) error {
	hostnameB := []byte(hostname)

	if err := syscallSethostname(hostnameB); err != nil {
		return err
	}

	return ioutil.WriteFile(hostnamePath, hostnameB, 0644)
}