File: context_test.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 (413 lines) | stat: -rw-r--r-- 11,975 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
// -*- Mode: Go; indent-tabs-mode: t -*-

/*
 * Copyright (C) 2016 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 hookstate

import (
	"encoding/json"
	"os"
	"time"

	. "gopkg.in/check.v1"

	"github.com/snapcore/snapd/asserts"
	"github.com/snapcore/snapd/asserts/assertstest"
	"github.com/snapcore/snapd/asserts/snapasserts"
	"github.com/snapcore/snapd/logger"
	"github.com/snapcore/snapd/overlord/state"
	"github.com/snapcore/snapd/snap"
	"github.com/snapcore/snapd/snap/snaptest"
)

type contextSuite struct {
	context *Context
	task    *state.Task
	state   *state.State
	setup   *HookSetup

	componentContext *Context
	componentSetup   *HookSetup
	componentTask    *state.Task
}

var _ = Suite(&contextSuite{})

func (s *contextSuite) SetUpTest(c *C) {
	s.state = state.New(nil)
	s.state.Lock()
	defer s.state.Unlock()

	s.task = s.state.NewTask("test-task", "my test task")
	s.setup = &HookSetup{Snap: "test-snap", Revision: snap.R(1), Hook: "test-hook"}
	var err error
	s.context, err = NewContext(s.task, s.task.State(), s.setup, nil, "")
	c.Check(err, IsNil)

	s.componentTask = s.state.NewTask("standard-component-task", "my test component task")
	s.componentSetup = &HookSetup{
		Snap:              "test-snap",
		Revision:          snap.R(1),
		Hook:              "test-hook",
		Component:         "standard-component",
		ComponentRevision: snap.R(2),
	}
	s.componentContext, err = NewContext(s.componentTask, s.componentTask.State(), s.componentSetup, nil, "")
	c.Check(err, IsNil)
}

func (s *contextSuite) TestHookSetup(c *C) {
	c.Check(s.context.HookName(), Equals, "test-hook")
	c.Check(s.context.InstanceName(), Equals, "test-snap")
	c.Check(s.context.IsSnapHook(), Equals, true)
	c.Check(s.context.IsComponentHook(), Equals, false)

	c.Check(s.componentContext.ComponentName(), Equals, "standard-component")
	c.Check(s.componentContext.ComponentRevision(), Equals, snap.R(2))
	c.Check(s.componentContext.IsSnapHook(), Equals, false)
	c.Check(s.componentContext.IsComponentHook(), Equals, true)
}

func (s *contextSuite) TestHookSource(c *C) {
	c.Check(s.context.HookSource(), Equals, "test-snap")
	c.Check(s.componentContext.HookSource(), Equals, "test-snap+standard-component")

	// insert an instance key for a quick test
	s.componentContext.setup.Snap = "test-snap_instance-key"
	defer func() { s.componentContext.setup.Snap = "test-snap" }()

	c.Check(s.componentContext.HookSource(), Equals, "test-snap_instance-key+standard-component")
}

func (s *contextSuite) TestSetAndGet(c *C) {
	s.context.Lock()
	defer s.context.Unlock()

	var output string
	c.Check(s.context.Get("foo", &output), NotNil)

	s.context.Set("foo", "bar")
	c.Check(s.context.Get("foo", &output), IsNil, Commentf("Expected context to contain 'foo'"))
	c.Check(output, Equals, "bar")

	// Test another non-existing key, but after the context data was created.
	c.Check(s.context.Get("baz", &output), NotNil)
}

func (s *contextSuite) TestSetAndGetNumber(c *C) {
	s.context.Lock()
	defer s.context.Unlock()

	s.context.Set("num", 1234567890)

	var output any
	c.Check(s.context.Get("num", &output), IsNil)
	c.Assert(output, Equals, json.Number("1234567890"))
}

func (s *contextSuite) TestSetPersistence(c *C) {
	s.context.Lock()
	s.context.Set("foo", "bar")
	s.context.Unlock()

	// Verify that "foo" is still "bar" within another context of the same hook
	// on the same task.
	anotherContext := &Context{task: s.task, state: s.task.State(), setup: s.setup}
	anotherContext.Lock()
	defer anotherContext.Unlock()

	var output string
	c.Check(anotherContext.Get("foo", &output), IsNil, Commentf("Expected new context to also contain 'foo'"))
	c.Check(output, Equals, "bar")
}

func (s *contextSuite) TestSetUnmarshalable(c *C) {
	s.context.Lock()
	defer s.context.Unlock()

	defer func() {
		c.Check(recover(), Matches, ".*cannot marshal context value.*", Commentf("Expected panic when attempting install"))
	}()

	s.context.Set("foo", func() {})
}

func (s *contextSuite) TestGetIsolatedFromTask(c *C) {
	// Set data in the task itself
	s.task.State().Lock()
	s.task.Set("foo", "bar")
	s.task.State().Unlock()

	s.context.Lock()
	defer s.context.Unlock()

	// Verify that "foo" is not set when asking for data from the hook context
	var output string
	c.Check(s.context.Get("foo", &output), NotNil, Commentf("Expected context data to be isolated from task"))
}

func (s *contextSuite) TestCache(c *C) {
	s.context.Lock()
	defer s.context.Unlock()

	c.Check(s.context.Cached("foo"), IsNil)

	s.context.Cache("foo", "bar")
	c.Check(s.context.Cached("foo"), Equals, "bar")

	// Test another non-existing key, but after the context cache was created.
	c.Check(s.context.Cached("baz"), IsNil)
}

func (s *contextSuite) TestDone(c *C) {
	s.context.Lock()
	defer s.context.Unlock()

	called := false
	s.context.OnDone(func() error {
		called = true
		return nil
	})

	s.context.Done()
	c.Check(called, Equals, true, Commentf("Expected finalizer to be called"))
}

func (s *contextSuite) TestEphemeralContextGetSet(c *C) {
	context, err := NewContext(nil, s.state, &HookSetup{Snap: "test-snap"}, nil, "")
	c.Assert(err, IsNil)
	context.Lock()
	defer context.Unlock()

	var output string
	c.Check(context.Get("foo", &output), NotNil)

	context.Set("foo", "bar")
	c.Check(context.Get("foo", &output), IsNil, Commentf("Expected context to contain 'foo'"))
	c.Check(output, Equals, "bar")

	// Test another non-existing key, but after the context data was created.
	c.Check(context.Get("baz", &output), NotNil)
}

func (s *contextSuite) TestChangeID(c *C) {
	context, err := NewContext(nil, s.state, &HookSetup{Snap: "test-snap"}, nil, "")
	c.Assert(err, IsNil)
	c.Check(context.ChangeID(), Equals, "")

	s.state.Lock()
	defer s.state.Unlock()

	task := s.state.NewTask("foo", "")
	context, err = NewContext(task, s.state, &HookSetup{Snap: "test-snap"}, nil, "")
	c.Assert(err, IsNil)
	c.Check(context.ChangeID(), Equals, "")

	chg := s.state.NewChange("bar", "")
	chg.AddTask(task)
	context, err = NewContext(task, s.state, &HookSetup{Snap: "test-snap"}, nil, "")
	c.Assert(err, IsNil)
	c.Check(context.ChangeID(), Equals, chg.ID())
}

func (s *contextSuite) TestChangeErrorf(c *C) {
	mockLog, restore := logger.MockLogger()
	defer restore()

	if v, ok := os.LookupEnv("SNAPD_DEBUG"); ok {
		os.Unsetenv("SNAPD_DEBUG")
		defer os.Setenv("SNAPD_DEBUG=%v", v)
	}

	s.state.Lock()
	task1 := s.state.NewTask("foo1", "summary foo1")
	task2 := s.state.NewTask("foo2", "summary foo2")
	s.state.Unlock()

	for _, tc := range []struct {
		task                 *state.Task
		ignoreError          bool
		expectedLoggerOutput string
		expectedTaskLog      string
	}{
		{nil, false, `.* context.go:.*: some error\n`, ``},
		{nil, true, `.* context.go:.*: some error\n`, ``},
		// ignore error hooks log errors to both logger and task
		{task1, true, `.* context.go:.*: ERROR task ` + task1.ID() + ` \(summary foo1\): some error\n`, `.* ERROR some error`},
		// normal hooks only log errors to the task
		{task2, false, ``, `.* ERROR some error`},
	} {
		hs := &HookSetup{Snap: "test-snap", IgnoreError: tc.ignoreError}
		context, err := NewContext(tc.task, s.state, hs, nil, "")
		c.Assert(err, IsNil)
		context.Lock()
		context.Errorf("some error")
		context.Unlock()
		c.Check(mockLog.String(), Matches, tc.expectedLoggerOutput)
		mockLog.Reset()
		if tc.task != nil {
			s.state.Lock()
			taskLog := tc.task.Log()
			s.state.Unlock()
			if tc.expectedTaskLog != "" {
				c.Assert(taskLog, HasLen, 1)
				c.Check(taskLog[0], Matches, tc.expectedTaskLog)
			} else {
				c.Assert(taskLog, HasLen, 0)
			}
		}
	}
}

func (s *contextSuite) TestChangeErrorfHookSetupNilPointerDoesNotCausePanic(c *C) {
	s.state.Lock()
	task := s.state.NewTask("foo", "")
	s.state.Unlock()

	var hookSetup *HookSetup = nil
	context, err := NewContext(task, s.state, hookSetup, nil, "")
	c.Assert(err, IsNil)
	// it's enough to check here that there is no panic from "nil" hookSetup
	context.Lock()
	context.Errorf("some error")
	context.Unlock()
}

func (s *contextSuite) TestPendingValidationSets(c *C) {
	s.state.Lock()
	defer s.state.Unlock()

	signing := assertstest.NewStoreStack("can0nical", nil)
	headers := map[string]any{
		"type":         "validation-set",
		"timestamp":    time.Now().Format(time.RFC3339),
		"authority-id": "foo",
		"series":       "16",
		"account-id":   "foo",
		"name":         "set-one",
		"sequence":     "3",
		"snaps": []any{
			map[string]any{
				"name":     "snap-1",
				"id":       snaptest.AssertedSnapID("snap-1"),
				"presence": "required",
			},
		},
	}

	assertion, err := signing.Sign(asserts.ValidationSetType, headers, nil, "")
	c.Assert(err, IsNil)
	vs := assertion.(*asserts.ValidationSet)

	encode := func(vs *asserts.ValidationSet) map[string][]byte {
		key := string(snapasserts.NewValidationSetKey(vs))
		return map[string][]byte{key: asserts.Encode(vs)}
	}

	tests := []struct {
		name    string
		context func() *Context
		keys    []snapasserts.ValidationSetKey
	}{
		{
			name: "ephemeral context returns nil",
			context: func() *Context {
				ctx, err := NewContext(nil, s.state, s.setup, nil, "")
				c.Assert(err, IsNil)
				return ctx
			},
		},
		{
			name: "no change associated returns nil",
			context: func() *Context {
				task := s.state.NewTask("hook-task", "")
				ctx, err := NewContext(task, s.state, s.setup, nil, "")
				c.Assert(err, IsNil)
				return ctx
			},
		},
		{
			name: "no enforce task returns nil",
			context: func() *Context {
				task := s.state.NewTask("hook-task", "")
				chg := s.state.NewChange("test-change", "")
				chg.AddTask(task)
				ctx, err := NewContext(task, s.state, s.setup, nil, "")
				c.Assert(err, IsNil)
				return ctx
			},
		},
		{
			name: "enforce task without validation-sets returns nil",
			context: func() *Context {
				task := s.state.NewTask("hook-task", "")
				chg := s.state.NewChange("test-change", "")
				chg.AddTask(task)
				chg.AddTask(s.state.NewTask("enforce-validation-sets", "enforce"))
				ctx, err := NewContext(task, s.state, s.setup, nil, "")
				c.Assert(err, IsNil)
				return ctx
			},
		},
		{
			name: "enforce task with empty validatio sets returns nil",
			context: func() *Context {
				task := s.state.NewTask("hook-task", "")
				chg := s.state.NewChange("test-change", "")
				chg.AddTask(task)

				enforce := s.state.NewTask("enforce-validation-sets", "enforce")
				enforce.Set("validation-sets", map[string][]byte{})
				chg.AddTask(enforce)

				ctx, err := NewContext(task, s.state, s.setup, nil, "")
				c.Assert(err, IsNil)
				return ctx
			},
		},
		{
			name: "valid case",
			context: func() *Context {
				task := s.state.NewTask("hook-task", "")
				chg := s.state.NewChange("test-change", "")
				chg.AddTask(task)

				enforce := s.state.NewTask("enforce-validation-sets", "enforce")
				enforce.Set("validation-sets", encode(vs))
				chg.AddTask(enforce)

				ctx, err := NewContext(task, s.state, s.setup, nil, "")
				c.Assert(err, IsNil)
				return ctx
			},
			keys: []snapasserts.ValidationSetKey{snapasserts.NewValidationSetKey(vs)},
		},
	}

	for _, tc := range tests {
		ctx := tc.context()
		pending, err := ctx.PendingValidationSets()
		c.Assert(err, IsNil, Commentf(tc.name))
		if tc.keys == nil {
			c.Check(pending, IsNil, Commentf(tc.name))
		} else {
			c.Assert(pending, NotNil, Commentf(tc.name))
			c.Check(pending.Keys(), DeepEquals, tc.keys, Commentf(tc.name))
		}
	}
}