File: helpers.go

package info (click to toggle)
snapd 2.73-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 81,460 kB
  • sloc: sh: 16,736; ansic: 16,652; python: 11,215; makefile: 1,966; exp: 190; awk: 58; xml: 22
file content (528 lines) | stat: -rw-r--r-- 15,714 bytes parent folder | download
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// -*- Mode: Go; indent-tabs-mode: t -*-

/*
 * Copyright (C) 2017 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 ctlcmd

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/snapcore/snapd/i18n"
	"github.com/snapcore/snapd/jsonutil"
	"github.com/snapcore/snapd/overlord/configstate"
	"github.com/snapcore/snapd/overlord/hookstate"
	"github.com/snapcore/snapd/overlord/servicestate"
	"github.com/snapcore/snapd/overlord/snapstate"
	"github.com/snapcore/snapd/overlord/state"
	"github.com/snapcore/snapd/overlord/swfeats"
	"github.com/snapcore/snapd/snap"
	"github.com/snapcore/snapd/snap/naming"
)

var finalTasks map[string]bool

var (
	servicestateControl        = servicestate.Control
	snapstateInstallComponents = snapstate.InstallComponents
	snapstateRemoveComponents  = snapstate.RemoveComponents
)

var (
	serviceControlChangeKind = swfeats.RegisterChangeKind("service-control")
	snapctlInstallChangeKind = swfeats.RegisterChangeKind("snapctl-install")
	snapctlRemoveChangeKind  = swfeats.RegisterChangeKind("snapctl-remove")
)

func init() {
	finalTasks = make(map[string]bool, len(snapstate.FinalTasks))
	for _, kind := range snapstate.FinalTasks {
		finalTasks[kind] = true
	}
}

// finalSeedTask is the last task that should run during seeding. This is used
// in the special handling of the "seed" change, which requires that we
// introspect the change for this specific task. Finding this task allows us to
// properly organize the hook tasks in the chain of tasks in the change.
const finalSeedTask = "mark-seeded"

func currentSnapInfo(st *state.State, snapInstance string) (*snap.Info, error) {
	var snapst snapstate.SnapState
	if err := snapstate.Get(st, snapInstance, &snapst); err != nil {
		return nil, err
	}

	return snapst.CurrentInfo()
}

func getServiceInfos(st *state.State, snapInstance string, serviceNames []string) ([]*snap.AppInfo, error) {
	st.Lock()
	defer st.Unlock()

	info, err := currentSnapInfo(st, snapInstance)
	if err != nil {
		return nil, err
	}

	if len(serviceNames) == 0 {
		// all services
		return info.Services(), nil
	}

	var svcs []*snap.AppInfo
	for _, svcName := range serviceNames {
		if svcName == snapInstance {
			// implicit all services
			return info.Services(), nil
		}
		if !strings.HasPrefix(svcName, snapInstance+".") {
			return nil, fmt.Errorf(i18n.G("unknown service: %q"), svcName)
		}
		// this doesn't support service aliases
		app, ok := info.Apps[svcName[1+len(snapInstance):]]
		if !(ok && app.IsService()) {
			return nil, fmt.Errorf(i18n.G("unknown service: %q"), svcName)
		}
		svcs = append(svcs, app)
	}

	return svcs, nil
}

func prepareQueueCommand(context *hookstate.Context, tts []*state.TaskSet) (change *state.Change, tasks []*state.Task, err error) {
	hookTask, ok := context.Task()
	if !ok {
		return nil, nil, fmt.Errorf("attempted to queue command with ephemeral context")
	}

	change = hookTask.Change()
	hookTaskLanes := hookTask.Lanes()
	tasks = change.LaneTasks(hookTaskLanes...)

	// When installing or updating multiple snaps, there is one lane per snap.
	// We want service command to join respective lane (it's the lane the hook belongs to).
	// In case there are no lanes, only the default lane no. 0, there is no need to join it.
	if len(hookTaskLanes) == 1 && hookTaskLanes[0] == 0 {
		hookTaskLanes = nil
	}
	for _, l := range hookTaskLanes {
		for _, ts := range tts {
			ts.JoinLane(l)
		}
	}

	return change, tasks, err
}

// queueCommand queues service command after all tasks, except for final tasks which must come after service commands.
func queueCommand(context *hookstate.Context, tts []*state.TaskSet) error {
	st := context.State()
	st.Lock()
	defer st.Unlock()

	change, tasks, err := prepareQueueCommand(context, tts)
	if err != nil {
		return err
	}

	if change.Kind() != "seed" {
		// Note: Multiple snaps could be installed in single transaction mode
		// where all snap tasksets are in a single lane.
		// This is non-issue for configure hook since the command tasks are
		// queued at the very end of the change unlike the default-configure
		// hook.
		for _, ts := range tts {
			for _, t := range tasks {
				if finalTasks[t.Kind()] {
					t.WaitAll(ts)
				} else {
					ts.WaitFor(t)
				}
			}
			change.AddAll(ts)
		}
	} else {
		// as a special case, we handle the seeding change slightly differently.
		// we must look at all tasks for the "mark-seeded" task, without
		// considering lanes. this is because seeding uses lanes to put
		// essential snaps and non-essential snaps in separate lanes, but the
		// mark-seeded task isn't in a lane with them.
		for _, ts := range tts {
			for _, t := range change.Tasks() {
				if t.Kind() == finalSeedTask {
					t.WaitAll(ts)
				} else {
					ts.WaitFor(t)
				}
			}
			change.AddAll(ts)
		}
	}

	// As this can be run from what was originally the last task of a change,
	// make sure the tasks added to the change are considered immediately.
	st.EnsureBefore(0)

	return nil
}

// queueDefaultConfigureHookCommand queues service command exactly after start-snap-services.
//
// This is possible because the default-configure hook is run on first-install only and right
// after start-snap-services is the nearest we can queue the service commands safely to make
// sure all the needed state is setup properly.
func queueDefaultConfigureHookCommand(context *hookstate.Context, tts []*state.TaskSet) error {
	st := context.State()
	st.Lock()
	defer st.Unlock()

	_, tasks, err := prepareQueueCommand(context, tts)
	if err != nil {
		return err
	}

	for _, t := range tasks {
		if t.Kind() == "start-snap-services" {
			snapsup, err := snapstate.TaskSnapSetup(t)
			if err != nil {
				return err
			}
			// Multiple snaps could be installed in single transaction mode
			// where all snap tasksets are in a single lane.
			// Check that the task belongs to the relevant snap.
			if snapsup.InstanceName() != context.InstanceName() {
				continue
			}
			for _, ts := range tts {
				snapstate.InjectTasks(t, ts)
			}
			break
		}
	}

	// As this can be run from what was originally the last task of a change,
	// make sure the tasks added to the change are considered immediately.
	st.EnsureBefore(0)

	return nil
}

func maybePatchServiceNames(snapInstance string, serviceNames []string) (
	updatedServiceNames []string, patched bool, err error,
) {
	snapName, snapInstanceKey := snap.SplitInstanceName(snapInstance)
	hasInstanceKey := snapInstanceKey != ""

	if !hasInstanceKey {
		// no patching needed, return names as they are
		return serviceNames, false, nil
	}

	// Backward compatibility path for a scenario when snapctl service operation
	// is called in a context of a snap with instance key. It is possible that
	// the request uses service names of form 'snap.app' which does not include
	// an instance key. We want to 'patch' them to 'snap_foo.app', such that
	// existing snaps that aren't completely aware of parallel installs work
	// correctly.

	updatedServiceNames = make([]string, 0, len(serviceNames))
	// Count of service names which included an instance key in their snap name.
	// We can only do the patching if either all service names had an instance
	// key, in which case the names aren't changed, or none of them and so the
	// names were fixed up as needed.
	withInstanceKeyCnt := 0
	for _, svcN := range serviceNames {
		if svcN == snapName {
			// same as base snap name (without instance key), a short hand
			// syntax for restart all services of a snap
			updatedServiceNames = append(updatedServiceNames, snapInstance)
			patched = true
			continue
		}

		svcSnapInstanceName, svcApp := snap.SplitSnapApp(svcN)
		svcSnapName, svcSnapInstanceKey := snap.SplitInstanceName(svcSnapInstanceName)

		if svcSnapName == snapName {
			// only apply patching if the snap name matches

			if svcSnapInstanceKey == "" {
				// snap name used in the full service name does not include instance
				// key, needs patching
				updatedServiceNames = append(updatedServiceNames, snap.JoinSnapApp(snapInstance, svcApp))
				patched = true
				continue
			}

			withInstanceKeyCnt++

			if svcSnapInstanceKey != snapInstanceKey {
				return nil, false, fmt.Errorf(i18n.G("unexpected snap instance key: %q"), svcSnapInstanceKey)
			}
		}

		updatedServiceNames = append(updatedServiceNames, svcN)
	}

	if withInstanceKeyCnt != 0 && withInstanceKeyCnt != len(serviceNames) {
		return nil, false, fmt.Errorf(i18n.G("inconsistent use of snap instance key"))
	}

	return updatedServiceNames, patched, nil
}

func runServiceCommand(context *hookstate.Context, inst *servicestate.Instruction) error {
	if context == nil {
		return &MissingContextError{inst.Action}
	}

	// patch service names for parallel installed snap if needed
	var err error
	inst.Names, _, err = maybePatchServiceNames(context.InstanceName(), inst.Names)
	if err != nil {
		return err
	}

	st := context.State()
	appInfos, err := getServiceInfos(st, context.InstanceName(), inst.Names)
	if err != nil {
		return err
	}

	flags := &servicestate.Flags{CreateExecCommandTasks: true}
	// passing context so we can ignore self-conflicts with the current change
	st.Lock()
	tts, err := servicestateControl(st, appInfos, inst, nil, flags, context)
	st.Unlock()
	if err != nil {
		return err
	}

	if !context.IsEphemeral() {
		// queue service command for default-configure and configure hooks.
		switch context.HookName() {
		case "configure":
			return queueCommand(context, tts)
		case "default-configure":
			return queueDefaultConfigureHookCommand(context, tts)
		}
	}

	st.Lock()
	chg := st.NewChange(serviceControlChangeKind, fmt.Sprintf("Running service command for snap %q", context.InstanceName()))
	for _, ts := range tts {
		chg.AddAll(ts)
	}
	st.EnsureBefore(0)
	st.Unlock()

	select {
	case <-chg.Ready():
		st.Lock()
		defer st.Unlock()
		return chg.Err()
	case <-time.After(configstate.ConfigureHookTimeout() / 2):
		return fmt.Errorf("%s command is taking too long", inst.Action)
	}
}

func validateSnapAndCompsNames(names []string, ctxSnap string) ([]string, error) {
	var allComps []string
	for _, name := range names {
		snap, comps := snap.SplitSnapInstanceAndComponents(name)
		// if snap is present it must be the context snap for the moment
		if snap != "" && snap != ctxSnap {
			return nil, errors.New("cannot install snaps using snapctl")
		}
		for _, comp := range comps {
			if err := naming.ValidateSnap(comp); err != nil {
				return nil, err
			}
		}
		allComps = append(allComps, comps...)
	}
	return allComps, nil
}

type managementCommandOp int

const (
	installManagementCommand managementCommandOp = iota
	removeManagementCommand
)

type managementCommand struct {
	operation  managementCommandOp
	components []string
}

func changeIDIfNotEphemeral(hctx *hookstate.Context) string {
	if !hctx.IsEphemeral() {
		return hctx.ChangeID()
	}
	return ""
}

func createSnapctlInstallTasks(hctx *hookstate.Context, cmd managementCommand) (tss []*state.TaskSet, err error) {
	st := hctx.State()
	st.Lock()
	defer st.Unlock()

	// note, vsets might be nil if no validation sets are going to be enforced
	// by the current change
	vsets, err := hctx.PendingValidationSets()
	if err != nil {
		return nil, err
	}

	info, err := currentSnapInfo(st, hctx.InstanceName())
	if err != nil {
		return nil, err
	}
	return snapstateInstallComponents(context.TODO(), st, cmd.components, info, vsets,
		snapstate.Options{ExpectOneSnap: true, FromChange: changeIDIfNotEphemeral(hctx)})
}

func createSnapctlRemoveTasks(hctx *hookstate.Context, cmd managementCommand) (tss []*state.TaskSet, err error) {
	st := hctx.State()
	st.Lock()
	defer st.Unlock()

	return snapstateRemoveComponents(st, hctx.InstanceName(), cmd.components,
		snapstate.RemoveComponentsOpts{RefreshProfile: true,
			FromChange: changeIDIfNotEphemeral(hctx)})
}

func runSnapManagementCommand(hctx *hookstate.Context, cmd managementCommand) error {
	st := hctx.State()
	var tss []*state.TaskSet
	var err error
	var cmdStr, cmdVerb string

	var changeKind string
	switch cmd.operation {
	case installManagementCommand:
		tss, err = createSnapctlInstallTasks(hctx, cmd)
		cmdStr = "install"
		cmdVerb = "Installing"
		changeKind = snapctlInstallChangeKind
	case removeManagementCommand:
		tss, err = createSnapctlRemoveTasks(hctx, cmd)
		cmdStr = "remove"
		cmdVerb = "Removing"
		changeKind = snapctlRemoveChangeKind
	default:
		err = fmt.Errorf("internal error: %q is not a valid snap management command", cmd.operation)
	}
	if err != nil {
		return err
	}

	if !hctx.IsEphemeral() {
		// Differently to service control commands, we always queue the
		// management tasks if run from a hook.
		return queueCommand(hctx, tss)
	}

	st.Lock()
	chg := st.NewChange(changeKind,
		fmt.Sprintf("%s components %v for snap %s",
			cmdVerb, cmd.components, hctx.InstanceName()))
	for _, ts := range tss {
		chg.AddAll(ts)
	}
	st.EnsureBefore(0)
	st.Unlock()

	select {
	case <-chg.Ready():
		st.Lock()
		defer st.Unlock()
		return chg.Err()
	case <-time.After(10 * time.Minute):
		return fmt.Errorf("snapctl %s command is taking too long", cmdStr)
	}
}

// NoAttributeError indicates that an interface attribute is not set.
type NoAttributeError struct {
	Attribute string
}

func (e *NoAttributeError) Error() string {
	return fmt.Sprintf("no %q attribute", e.Attribute)
}

// isNoAttribute returns whether the provided error is a *NoAttributeError.
func isNoAttribute(err error) bool {
	_, ok := err.(*NoAttributeError)
	return ok
}

func jsonRaw(v any) *json.RawMessage {
	data, err := json.Marshal(v)
	if err != nil {
		panic(fmt.Errorf("internal error: cannot marshal attributes: %v", err))
	}
	raw := json.RawMessage(data)
	return &raw
}

// getAttribute unmarshals into result the value of the provided key from attributes map.
// If the key does not exist, an error of type *NoAttributeError is returned.
// The provided key may be formed as a dotted key path through nested maps.
// For example, the "a.b.c" key describes the {a: {b: {c: value}}} map.
func getAttribute(snapName string, subkeys []string, pos int, attrs map[string]any, result any) error {
	if pos >= len(subkeys) {
		return fmt.Errorf("internal error: invalid subkeys index %d for subkeys %q", pos, subkeys)
	}
	value, ok := attrs[subkeys[pos]]
	if !ok {
		return &NoAttributeError{Attribute: strings.Join(subkeys[:pos+1], ".")}
	}

	if pos+1 == len(subkeys) {
		raw, ok := value.(*json.RawMessage)
		if !ok {
			raw = jsonRaw(value)
		}
		if err := jsonutil.DecodeWithNumber(bytes.NewReader(*raw), &result); err != nil {
			key := strings.Join(subkeys, ".")
			return fmt.Errorf("internal error: cannot unmarshal snap %s attribute %q into %T: %s, json: %s", snapName, key, result, err, *raw)
		}
		return nil
	}

	attrsm, ok := value.(map[string]any)
	if !ok {
		raw, ok := value.(*json.RawMessage)
		if !ok {
			raw = jsonRaw(value)
		}
		if err := jsonutil.DecodeWithNumber(bytes.NewReader(*raw), &attrsm); err != nil {
			return fmt.Errorf("snap %q attribute %q is not a map", snapName, strings.Join(subkeys[:pos+1], "."))
		}
	}
	return getAttribute(snapName, subkeys, pos+1, attrsm, result)
}