File: error.go

package info (click to toggle)
snapd 2.72-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 80,412 kB
  • sloc: sh: 16,506; ansic: 16,211; python: 11,213; makefile: 1,919; exp: 190; awk: 58; xml: 22
file content (448 lines) | stat: -rw-r--r-- 15,298 bytes parent folder | download | duplicates (2)
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
// -*- Mode: Go; indent-tabs-mode: t -*-

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

import (
	"bytes"
	"errors"
	"fmt"
	"go/doc"
	"os"
	"strings"
	"text/tabwriter"

	"golang.org/x/crypto/ssh/terminal"

	"github.com/snapcore/snapd/client"
	"github.com/snapcore/snapd/i18n"
	"github.com/snapcore/snapd/logger"
	"github.com/snapcore/snapd/osutil"
	"github.com/snapcore/snapd/osutil/user"
	"github.com/snapcore/snapd/snap/channel"
	"github.com/snapcore/snapd/strutil"
)

var errorPrefix = i18n.G("error: %v\n")

var termSize = termSizeImpl

func termSizeImpl() (width, height int) {
	if f, ok := Stdout.(*os.File); ok {
		width, height, _ = terminal.GetSize(int(f.Fd()))
	}

	if width <= 0 {
		width = int(osutil.GetenvInt64("COLUMNS"))
	}

	if height <= 0 {
		height = int(osutil.GetenvInt64("LINES"))
	}

	if width < 40 {
		width = 80
	}

	if height < 15 {
		height = 25
	}

	return width, height
}

func fill(para string, indent int) string {
	width, _ := termSize()

	if width > 100 {
		width = 100
	}

	// some terminals aren't happy about writing in the last
	// column (they'll add line for you). We could check terminfo
	// for "sam" (semi_auto_right_margin), but that's a lot of
	// work just for this.
	width--

	var buf bytes.Buffer
	indentStr := strings.Repeat(" ", indent)
	doc.ToText(&buf, para, indentStr, indentStr, width-indent)

	return strings.TrimSpace(buf.String())
}

// errorToCmdMessage returns the appropriate error message and value based on the
// client error and some context information. The opName is the lowercase name
// of the failed operation (e.g., "refresh").
func errorToCmdMessage(snapName string, opName string, e error, opts *client.SnapOptions) (string, error) {
	// do this here instead of in the caller for more DRY
	err, ok := e.(*client.Error)
	if !ok {
		return "", e
	}
	// retryable errors are just passed through
	if client.IsRetryable(err) {
		return "", err
	}

	// ensure the "real" error is available if we ask for it
	logger.Debugf("error: %s", err)

	// FIXME: using err.Message in user-facing messaging is not
	// l10n-friendly, and probably means we're missing ad-hoc messaging.
	isError := true
	usesSnapName := true
	var msg string
	switch err.Kind {
	case client.ErrorKindNotSnap:
		msg = i18n.G(`%q does not contain an unpacked snap.

Try 'snapcraft prime' in your project directory, then 'snap try' again.`)
		if snapName == "" || snapName == "./" {
			errValStr, ok := err.Value.(string)
			if ok && errValStr != "" {
				snapName = errValStr
			}
		}
	case client.ErrorKindSnapNotFound:
		msg = i18n.G("snap %q not found")
		if snapName == "" {
			errValStr, ok := err.Value.(string)
			if ok && errValStr != "" {
				snapName = errValStr
			}
		}
	case client.ErrorKindSnapChannelNotAvailable,
		client.ErrorKindSnapArchitectureNotAvailable:
		values, ok := err.Value.(map[string]any)
		if ok {
			candName, _ := values["snap-name"].(string)
			if candName != "" {
				snapName = candName
			}
			action, _ := values["action"].(string)
			arch, _ := values["architecture"].(string)
			channel, _ := values["channel"].(string)
			releases, _ := values["releases"].([]any)
			if snapName != "" && action != "" && arch != "" && channel != "" && len(releases) != 0 {
				usesSnapName = false
				msg = snapRevisionNotAvailableMessage(err.Kind, snapName, action, arch, channel, releases)
				break
			}
		}
		fallthrough
	case client.ErrorKindSnapRevisionNotAvailable:
		if snapName == "" {
			errValStr, ok := err.Value.(string)
			if ok && errValStr != "" {
				snapName = errValStr
			}
		}

		usesSnapName = false
		// TRANSLATORS: %[1]q and %[1]s refer to the same thing (a snap name).
		msg = fmt.Sprintf(i18n.G(`snap %[1]q not available as specified (see 'snap info %[1]s')`), snapName)

		if opts != nil {
			if opts.Revision != "" {
				// TRANSLATORS: %[1]q and %[1]s refer to the same thing (a snap name); %s is whatever the user used for --revision=
				msg = fmt.Sprintf(i18n.G(`snap %[1]q revision %s not available (see 'snap info %[1]s')`), snapName, opts.Revision)
			} else if opts.Channel != "" {
				// (note --revision overrides --channel)

				// TRANSLATORS: %[1]q and %[1]s refer to the same thing (a snap name); %q is whatever foo the user used for --channel=foo
				msg = fmt.Sprintf(i18n.G(`snap %[1]q not available on channel %q (see 'snap info %[1]s')`), snapName, opts.Channel)
			}
		}
	case client.ErrorKindSnapAlreadyInstalled:
		isError = false
		msg = i18n.G(`snap %q is already installed, see 'snap help refresh'`)
	case client.ErrorKindSnapNeedsDevMode:
		if opts != nil && opts.Dangerous {
			msg = i18n.G("snap %q requires devmode or confinement override")
			break
		}
		msg = i18n.G(`
The publisher of snap %q has indicated that they do not consider this revision
to be of production quality and that it is only meant for development or testing
at this point. As a consequence this snap will not refresh automatically and may
perform arbitrary system changes outside of the security sandbox snaps are
generally confined to, which may put your system at risk.

If you understand and want to proceed repeat the command including --devmode;
if instead you want to install the snap forcing it into strict confinement
repeat the command including --jailmode.`)
	case client.ErrorKindSnapNeedsClassic:
		msg = i18n.G(`
This revision of snap %q was published using classic confinement and thus may
perform arbitrary system changes outside of the security sandbox that snaps are
usually confined to, which may put your system at risk.

If you understand and want to proceed repeat the command including --classic.
`)
	case client.ErrorKindSnapNotClassic:
		msg = i18n.G(`snap %q is not compatible with --classic`)
	case client.ErrorKindLoginRequired:
		usesSnapName = false
		u, _ := user.Current()
		if u != nil && u.Username == "root" {
			// TRANSLATORS: %s is an error message (e.g. “cannot yadda yadda: permission denied”)
			msg = fmt.Sprintf(i18n.G(`%s (see 'snap help login')`), err.Message)
		} else {
			// TRANSLATORS: %s is an error message (e.g. “cannot yadda yadda: permission denied”)
			msg = fmt.Sprintf(i18n.G(`%s (try with sudo)`), err.Message)
		}
	case client.ErrorKindSnapLocal:
		msg = i18n.G("local snap %q is unknown to the store, use --amend to proceed anyway")
	case client.ErrorKindSnapNoUpdateAvailable:
		isError = false
		msg = i18n.G("snap %q has no updates available")
	case client.ErrorKindSnapNotInstalled:
		isError = true
		// if the snap isn't installed, then remove can ignore this error
		if opName == "remove" {
			isError = false
		}

		usesSnapName = false
		msg = err.Message
	case client.ErrorKindNetworkTimeout:
		isError = true
		usesSnapName = false
		msg = i18n.G("unable to contact snap store")
	case client.ErrorKindSystemRestart:
		isError = false
		usesSnapName = false
		msg = i18n.G("snapd is about to reboot the system")
		values, ok := err.Value.(map[string]any)
		if ok {
			op, ok := values["op"].(string)
			if ok {
				switch op {
				case "halt":
					msg = i18n.G("snapd is about to halt the system")
				case "poweroff":
					msg = i18n.G("snapd is about to power off the system")
				}
			}
		}
	case client.ErrorKindInsufficientDiskSpace:
		// this error carries multiple snap names
		usesSnapName = false
		values, ok := err.Value.(map[string]any)
		if ok {
			changeKind, _ := values["change-kind"].(string)
			snaps, _ := values["snap-names"].([]any)
			snapNames := make([]string, len(snaps))
			for i, v := range snaps {
				snapNames[i] = fmt.Sprint(v)
			}
			names := strutil.Quoted(snapNames)
			switch changeKind {
			case "remove":
				msg = fmt.Sprintf(i18n.G("cannot remove %s due to low disk space for automatic snapshot, use --purge to avoid creating a snapshot"), names)
			case "install":
				msg = fmt.Sprintf(i18n.G("cannot install %s due to low disk space"), names)
			case "refresh":
				msg = fmt.Sprintf(i18n.G("cannot refresh %s due to low disk space"), names)
			default:
				msg = err.Error()
			}
			break
		}
		fallthrough
	default:
		usesSnapName = false
		msg = err.Message
	}

	if usesSnapName {
		msg = fmt.Sprintf(msg, snapName)
	}
	// 3 is the %v\n, which will be present in any locale
	msg = fill(msg, len(errorPrefix)-3)
	if isError {
		return "", errors.New(msg)
	}

	return msg, nil
}

func snapRevisionNotAvailableMessage(kind client.ErrorKind, snapName, action, arch, snapChannel string, releases []any) string {
	// releases contains all available (arch x channel)
	// as reported by the store through the daemon
	req, err := channel.Parse(snapChannel, arch)
	if err != nil {
		// XXX: this is no longer possible (should be caught before hitting the store), unless the state itself has an invalid channel
		// TRANSLATORS: %q is the invalid request channel, %s is the snap name
		msg := fmt.Sprintf(i18n.G("requested channel %q is not valid (see 'snap info %s' for valid ones)"), snapChannel, snapName)
		return msg
	}
	avail := make([]*channel.Channel, 0, len(releases))
	for _, v := range releases {
		rel, _ := v.(map[string]any)
		relCh, _ := rel["channel"].(string)
		relArch, _ := rel["architecture"].(string)
		if relArch == "" {
			logger.Debugf("internal error: %q daemon error carries a release with invalid/empty architecture: %v", kind, v)
			continue
		}
		a, err := channel.Parse(relCh, relArch)
		if err != nil {
			logger.Debugf("internal error: %q daemon error carries a release with invalid/empty channel (%v): %v", kind, err, v)
			continue
		}
		avail = append(avail, &a)
	}

	matches := map[string][]*channel.Channel{}
	for _, a := range avail {
		m := req.Match(a)
		matchRepr := m.String()
		if matchRepr != "" {
			matches[matchRepr] = append(matches[matchRepr], a)
		}
	}

	// no release is for this architecture
	if kind == client.ErrorKindSnapArchitectureNotAvailable {
		// TODO: add "Get more information..." hints once snap info
		// support showing multiple/all archs

		// there are matching track+risk releases for other archs
		if hits := matches["track:risk"]; len(hits) != 0 {
			archs := strings.Join(archsForChannels(hits), ", ")
			// TRANSLATORS: %q is for the snap name, %v is the requested channel, first %s is the system architecture short name, second %s is a comma separated list of available arch short names
			msg := fmt.Sprintf(i18n.G("snap %q is not available on %v for this architecture (%s) but exists on other architectures (%s)."), snapName, req, arch, archs)
			return msg
		}

		// not even that, generic error
		archs := strings.Join(archsForChannels(avail), ", ")
		// TRANSLATORS: %q is for the snap name, first %s is the system architecture short name, second %s is a comma separated list of available arch short names
		msg := fmt.Sprintf(i18n.G("snap %q is not available on this architecture (%s) but exists on other architectures (%s)."), snapName, arch, archs)
		return msg
	}

	// a branch was requested
	if req.Branch != "" {
		// there are matching arch+track+risk, give main track info
		if len(matches["architecture:track:risk"]) != 0 {
			trackRisk := channel.Channel{Track: req.Track, Risk: req.Risk}
			trackRisk = trackRisk.Clean()

			// TRANSLATORS: %q is for the snap name, first %s is the full requested channel
			msg := fmt.Sprintf(i18n.G("requested a non-existing branch on %s for snap %q: %s"), trackRisk.Full(), snapName, req.Branch)
			return msg
		}

		msg := fmt.Sprintf(i18n.G("requested a non-existing branch for snap %q: %s"), snapName, req.Full())
		return msg
	}

	// TRANSLATORS: can optionally be concatenated after a blank line at the end of other error messages, together with the "Get more information ..." hint
	preRelWarn := i18n.G("Please be mindful pre-release channels may include features not completely tested or implemented.")
	// TRANSLATORS: can optionally be concatenated after a blank line at the end of other error messages, together with the "Get more information ..." hint
	trackWarn := i18n.G("Please be mindful that different tracks may include different features.")
	// TRANSLATORS: %s is for the snap name, will be concatenated after at the end of other error messages, possibly after a blank line
	moreInfoHint := fmt.Sprintf(i18n.G("Get more information with 'snap info %s'."), snapName)

	// there are matching arch+track releases => give hint and instructions
	// about pre-release channels
	if hits := matches["architecture:track"]; len(hits) != 0 {
		// TRANSLATORS: %q is for the snap name, %v is the requested channel
		msg := fmt.Sprintf(i18n.G("snap %q is not available on %v but is available to install on the following channels:\n"), snapName, req)
		msg += installTable(snapName, action, hits, false)
		msg += "\n"
		if req.Risk == "stable" {
			msg += "\n" + preRelWarn
		}
		msg += "\n" + moreInfoHint
		return msg
	}

	// there are matching arch+risk releases => give hints and instructions
	// about these other tracks
	if hits := matches["architecture:risk"]; len(hits) != 0 {
		// TRANSLATORS: %q is for the snap name, %s is the full requested channel
		msg := fmt.Sprintf(i18n.G("snap %q is not available on %s but is available to install on the following tracks:\n"), snapName, req.Full())
		msg += installTable(snapName, action, hits, true)
		msg += "\n\n" + trackWarn
		msg += "\n" + moreInfoHint
		return msg
	}

	// generic error
	// TRANSLATORS: %q is for the snap name, %s is the full requested channel
	msg := fmt.Sprintf(i18n.G("snap %q is not available on %s but other tracks exist.\n"), snapName, req.Full())
	msg += "\n\n" + trackWarn
	msg += "\n" + moreInfoHint
	return msg
}

func installTable(snapName, action string, avail []*channel.Channel, full bool) string {
	b := &bytes.Buffer{}
	w := tabwriter.NewWriter(b, len("candidate")+2, 1, 2, ' ', 0)
	first := true
	for _, a := range avail {
		if first {
			first = false
		} else {
			fmt.Fprint(w, "\n")
		}
		var ch string
		if full {
			ch = a.Full()
		} else {
			ch = a.String()
		}
		chOption := channelOption(a)
		fmt.Fprintf(w, "%s\tsnap %s %s %s", ch, action, chOption, snapName)
	}
	w.Flush()
	tbl := b.String()
	// indent to drive fill/ToText to keep the tabulations intact
	lines := strings.SplitAfter(tbl, "\n")
	for i := range lines {
		lines[i] = "  " + lines[i]
	}
	return strings.Join(lines, "")
}

func channelOption(c *channel.Channel) string {
	if c.Branch == "" {
		if c.Track == "" {
			return fmt.Sprintf("--%s", c.Risk)
		}
		if c.Risk == "stable" {
			return fmt.Sprintf("--channel=%s", c.Track)
		}
	}
	return fmt.Sprintf("--channel=%s", c)
}

func archsForChannels(cs []*channel.Channel) []string {
	archs := []string{}
	for _, c := range cs {
		if !strutil.ListContains(archs, c.Architecture) {
			archs = append(archs, c.Architecture)
		}
	}
	return archs
}