~sergiusens/snappy/inhibitSystemCtl

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
/*
 * 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 snappy

import (
	"crypto/sha512"
	"encoding/hex"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"launchpad.net/snappy/coreconfig"
	"launchpad.net/snappy/partition"

	"github.com/mvo5/goconfigparser"
)

const (
	systemImagePartName = "ubuntu-core"

	// location of the channel config on the filesystem
	systemImageChannelConfig = "/etc/system-image/channel.ini"

	// the location for the ReloadConfig
	systemImageClientConfig = "/etc/system-image/client.ini"
)

var (
	// the system-image-cli binary
	systemImageCli = "system-image-cli"
)

// This is the root directory of the filesystem. Its only useful to
// change when writing tests
var systemImageRoot = "/"

// will replace newPartition() to return a mockPartition
var newPartition = func() (p partition.Interface) {
	return partition.New()
}

// SystemImagePart represents a "core" snap that is managed via the SystemImage
// client
type SystemImagePart struct {
	version        string
	versionDetails string
	channelName    string
	lastUpdate     time.Time

	isInstalled bool
	isActive    bool

	updateSize int64

	partition partition.Interface
}

// Type returns SnapTypeCore for this snap
func (s *SystemImagePart) Type() SnapType {
	return SnapTypeCore
}

// Name returns the name
func (s *SystemImagePart) Name() string {
	return systemImagePartName
}

// Version returns the version
func (s *SystemImagePart) Version() string {
	return s.version
}

// Description returns the description
func (s *SystemImagePart) Description() string {
	return "ubuntu-core description"
}

// Hash returns the hash
func (s *SystemImagePart) Hash() string {
	hasher := sha512.New()
	hasher.Write([]byte(s.versionDetails))
	hexdigest := hex.EncodeToString(hasher.Sum(nil))

	return hexdigest
}

// IsActive returns true if the snap is active
func (s *SystemImagePart) IsActive() bool {
	return s.isActive
}

// IsInstalled returns true if the snap is installed
func (s *SystemImagePart) IsInstalled() bool {
	return s.isInstalled
}

// InstalledSize returns the size of the installed snap
func (s *SystemImagePart) InstalledSize() int64 {
	return -1
}

// DownloadSize returns the dowload size
func (s *SystemImagePart) DownloadSize() int64 {
	return s.updateSize
}

// Date returns the last update date
func (s *SystemImagePart) Date() time.Time {
	return s.lastUpdate
}

// SetActive sets the snap active
func (s *SystemImagePart) SetActive() (err error) {
	isNextBootOther := s.partition.IsNextBootOther()
	// active and no switch scheduled -> nothing to do
	if s.IsActive() && !isNextBootOther {
		return nil
	}
	// not currently active but switch scheduled already -> nothing to do
	if !s.IsActive() && isNextBootOther {
		return nil
	}

	return s.partition.ToggleNextBoot()
}

// Install installs the snap
func (s *SystemImagePart) Install(pb ProgressMeter, flags InstallFlags) (err error) {
	if pb != nil {
		// ensure the progress finishes when we are done
		defer func() {
			pb.Finished()
		}()
	}

	// Ensure there is always a kernel + initrd to boot with, even
	// if the update does not provide new versions.
	err = s.partition.SyncBootloaderFiles()
	if err != nil {
		return err
	}

	// find out what config file to use, the other partition may be
	// empty so we need to fallback to the current one if it is
	configFile := systemImageClientConfig
	err = s.partition.RunWithOther(partition.RO, func(otherRoot string) (err error) {
		otherConfigFile := filepath.Join(systemImageRoot, otherRoot, systemImageClientConfig)
		if _, err := os.Stat(otherConfigFile); err == nil {
			configFile = otherConfigFile
		}

		return systemImageDownloadUpdate(configFile, pb)
	})
	if err != nil {
		return err
	}

	// Check that the final system state is as expected.
	if err = s.verifyUpgradeWasApplied(); err != nil {
		return err
	}

	return s.partition.ToggleNextBoot()
}

// Ensure the expected version update was applied to the expected partition.
func (s *SystemImagePart) verifyUpgradeWasApplied() error {
	// The upgrade has now been applied, so check that the expected
	// update was applied by comparing "self" (which is the newest
	// system-image revision with that installed on the other
	// partition.

	// Determine the latest installed part.
	latestPart := makeOtherPart(s.partition)
	if latestPart == nil {
		// If there is no other part, this system must be a
		// single rootfs one, so re-query current to find the
		// latest installed part.
		latestPart = makeCurrentPart(s.partition)
	}

	if latestPart == nil {
		return &ErrUpgradeVerificationFailed{
			msg: "could not find latest installed partition",
		}
	}

	if s.version != latestPart.Version() {
		return &ErrUpgradeVerificationFailed{
			msg: fmt.Sprintf("found %q but expected %q", latestPart.Version(), s.version),
		}
	}

	return nil
}

// Uninstall can not be used for "core" snaps
func (s *SystemImagePart) Uninstall() (err error) {
	return ErrPackageNotRemovable
}

// Config is used to to configure the snap
func (s *SystemImagePart) Config(configuration []byte) (newConfig string, err error) {
	if cfg := string(configuration); cfg != "" {
		return coreconfig.Set(cfg)
	}

	return coreconfig.Get()
}

// NeedsReboot returns true if the snap becomes active on the next reboot
func (s *SystemImagePart) NeedsReboot() bool {

	if !s.IsActive() && s.partition.IsNextBootOther() {
		return true
	}

	return false
}

// MarkBootSuccessful marks the *currently* booted rootfs as "good"
// (it booted :)
// Note: Not part of the Part interface.
func (s *SystemImagePart) MarkBootSuccessful() (err error) {

	return s.partition.MarkBootSuccessful()
}

// Channel returns the system-image-server channel used
func (s *SystemImagePart) Channel() string {
	return s.channelName
}

// Icon returns the icon path
func (s *SystemImagePart) Icon() string {
	return ""
}

// SystemImageRepository is the type used for the system-image-server
type SystemImageRepository struct {
	partition partition.Interface
}

// NewSystemImageRepository returns a new SystemImageRepository
func NewSystemImageRepository() *SystemImageRepository {
	return &SystemImageRepository{partition: newPartition()}
}

func makePartFromSystemImageConfigFile(p partition.Interface, channelIniPath string, isActive bool) (part Part, err error) {
	cfg := goconfigparser.New()
	f, err := os.Open(channelIniPath)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	err = cfg.Read(f)
	if err != nil {
		log.Printf("Can not parse config '%s': %s", channelIniPath, err)
		return nil, err
	}
	st, err := os.Stat(channelIniPath)
	if err != nil {
		log.Printf("Can stat '%s': %s", channelIniPath, err)
		return nil, err
	}

	currentBuildNumber, err := cfg.Get("service", "build_number")
	versionDetails, err := cfg.Get("service", "version_detail")
	channelName, err := cfg.Get("service", "channel")
	return &SystemImagePart{
		isActive:       isActive,
		isInstalled:    true,
		version:        currentBuildNumber,
		versionDetails: versionDetails,
		channelName:    channelName,
		lastUpdate:     st.ModTime(),
		partition:      p}, err
}

// Returns the part associated with the current rootfs
func makeCurrentPart(p partition.Interface) Part {
	configFile := filepath.Join(systemImageRoot, systemImageChannelConfig)
	part, err := makePartFromSystemImageConfigFile(p, configFile, true)
	if err != nil {
		return nil
	}
	return part
}

// Returns the part associated with the other rootfs (if any)
func makeOtherPart(p partition.Interface) Part {
	var part Part
	err := p.RunWithOther(partition.RO, func(otherRoot string) (err error) {
		configFile := filepath.Join(systemImageRoot, otherRoot, systemImageChannelConfig)
		_, err = os.Stat(configFile)
		if err != nil && os.IsNotExist(err) {
			// config file doesn't exist, meaning the other
			// partition is empty. However, this is not an
			// error condition (atleast for amd64 images
			// which only have 1 partition pre-installed).
			return nil
		}
		part, err = makePartFromSystemImageConfigFile(p, configFile, false)
		if err != nil {
			log.Printf("Can not make system-image part for %s: %s", configFile, err)
		}
		return err
	})
	if err == partition.ErrNoDualPartition {
		return nil
	}
	return part
}

// Description describes the repository
func (s *SystemImageRepository) Description() string {
	return "SystemImageRepository"
}

// Search searches the SystemImageRepository for the given terms
func (s *SystemImageRepository) Search(terms string) (versions []Part, err error) {
	if strings.Contains(terms, systemImagePartName) {
		part := makeCurrentPart(s.partition)
		versions = append(versions, part)
	}
	return versions, err
}

// Details returns details for the given snap
func (s *SystemImageRepository) Details(snapName string) (versions []Part, err error) {
	if snapName == systemImagePartName {
		part := makeCurrentPart(s.partition)
		versions = append(versions, part)
	}
	return versions, err
}

// Updates returns the available updates
func (s *SystemImageRepository) Updates() (parts []Part, err error) {
	configFile := filepath.Join(systemImageRoot, systemImageChannelConfig)
	updateStatus, err := systemImageClientCheckForUpdates(configFile)

	current := makeCurrentPart(s.partition)
	// no VersionCompare here because the channel provides a "order" and
	// that may go backwards when switching channels(?)
	if current.Version() != updateStatus.targetVersion {
		parts = append(parts, &SystemImagePart{
			version:        updateStatus.targetVersion,
			versionDetails: updateStatus.targetVersionDetails,
			lastUpdate:     updateStatus.lastUpdate,
			updateSize:     updateStatus.updateSize,
			channelName:    current.(*SystemImagePart).channelName,
			partition:      s.partition})
	}

	return parts, err
}

// Installed returns the installed snaps from this repository
func (s *SystemImageRepository) Installed() (parts []Part, err error) {
	// current partition
	curr := makeCurrentPart(s.partition)
	if curr != nil {
		parts = append(parts, curr)
	}

	// other partition
	other := makeOtherPart(s.partition)
	if other != nil {
		parts = append(parts, other)
	}

	return parts, err
}