-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
362 lines (340 loc) · 11.7 KB
/
errors.go
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
// Copyright 2020 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package errors
import (
"fmt"
"net/http"
"strings"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/txn/v2"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/core/leadership"
"github.com/juju/juju/core/lease"
stateerrors "github.com/juju/juju/state/errors"
)
var logger = loggo.GetLogger("juju.apiserver.common.errors")
var (
ErrBadId = errors.New("id not found")
ErrBadCreds = errors.New("invalid entity name or password")
ErrNoCreds = errors.New("no credentials provided")
ErrLoginExpired = errors.New("login expired")
ErrPerm = errors.New("permission denied")
ErrNotLoggedIn = errors.New("not logged in")
ErrUnknownWatcher = errors.New("unknown watcher id")
ErrStoppedWatcher = errors.New("watcher has been stopped")
ErrBadRequest = errors.New("invalid request")
ErrTryAgain = errors.New("try again")
ErrActionNotAvailable = errors.New("action no longer available")
)
// OperationBlockedError returns an error which signifies that
// an operation has been blocked; the message should describe
// what has been blocked.
func OperationBlockedError(msg string) error {
if msg == "" {
msg = "the operation has been blocked"
}
return ¶ms.Error{
Message: msg,
Code: params.CodeOperationBlocked,
}
}
var singletonErrorCodes = map[error]string{
stateerrors.ErrCannotEnterScopeYet: params.CodeCannotEnterScopeYet,
stateerrors.ErrCannotEnterScope: params.CodeCannotEnterScope,
stateerrors.ErrUnitHasSubordinates: params.CodeUnitHasSubordinates,
stateerrors.ErrDead: params.CodeDead,
txn.ErrExcessiveContention: params.CodeExcessiveContention,
leadership.ErrClaimDenied: params.CodeLeadershipClaimDenied,
lease.ErrClaimDenied: params.CodeLeaseClaimDenied,
ErrBadId: params.CodeNotFound,
ErrBadCreds: params.CodeUnauthorized,
ErrNoCreds: params.CodeNoCreds,
ErrLoginExpired: params.CodeLoginExpired,
ErrPerm: params.CodeUnauthorized,
ErrNotLoggedIn: params.CodeUnauthorized,
ErrUnknownWatcher: params.CodeNotFound,
ErrStoppedWatcher: params.CodeStopped,
ErrTryAgain: params.CodeTryAgain,
ErrActionNotAvailable: params.CodeActionNotAvailable,
}
func singletonCode(err error) (string, bool) {
// All error types may not be hashable; deal with
// that by catching the panic if we try to look up
// a non-hashable type.
defer func() {
_ = recover()
}()
code, ok := singletonErrorCodes[err]
return code, ok
}
func singletonError(err error) (bool, error) {
errCode := params.ErrCode(err)
for singleton, code := range singletonErrorCodes {
if errCode == code && singleton.Error() == err.Error() {
return true, singleton
}
}
return false, nil
}
// ServerErrorAndStatus is like ServerError but also
// returns an HTTP status code appropriate for using
// in a response holding the given error.
func ServerErrorAndStatus(err error) (*params.Error, int) {
err1 := ServerError(err)
if err1 == nil {
return nil, http.StatusOK
}
status := http.StatusInternalServerError
switch err1.Code {
case params.CodeUnauthorized:
status = http.StatusUnauthorized
case params.CodeNotFound,
params.CodeUserNotFound,
params.CodeModelNotFound:
status = http.StatusNotFound
case params.CodeBadRequest:
status = http.StatusBadRequest
case params.CodeMethodNotAllowed:
status = http.StatusMethodNotAllowed
case params.CodeOperationBlocked:
// This should really be http.StatusForbidden but earlier versions
// of juju clients rely on the 400 status, so we leave it like that.
status = http.StatusBadRequest
case params.CodeForbidden:
status = http.StatusForbidden
case params.CodeDischargeRequired:
status = http.StatusUnauthorized
case params.CodeRedirect:
status = http.StatusMovedPermanently
case params.CodeNotYetAvailable:
// The request could not be completed due to a conflict with
// the current state of the resource. This code is only allowed
// in situations where it is expected that the user might be
// able to resolve the conflict and resubmit the request.
//
// See https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.10
status = http.StatusConflict
case params.CodeNotLeader:
status = http.StatusTemporaryRedirect
case params.CodeLeaseError:
status = leaseStatusCode(err1)
}
return err1, status
}
// ServerError returns an error suitable for returning to an API
// client, with an error code suitable for various kinds of errors
// generated in packages outside the API.
func ServerError(err error) *params.Error {
if err == nil {
return nil
}
logger.Tracef("server RPC error %v", errors.Details(err))
var (
info map[string]interface{}
msg = err.Error()
)
// Skip past annotations when looking for the code.
err = errors.Cause(err)
code, ok := singletonCode(err)
switch {
case ok:
case errors.IsUnauthorized(err):
code = params.CodeUnauthorized
case errors.IsNotFound(err):
code = params.CodeNotFound
case errors.IsUserNotFound(err):
code = params.CodeUserNotFound
case errors.IsAlreadyExists(err):
code = params.CodeAlreadyExists
case errors.IsNotAssigned(err):
code = params.CodeNotAssigned
case stateerrors.IsHasAssignedUnitsError(err):
code = params.CodeHasAssignedUnits
case stateerrors.IsHasHostedModelsError(err):
code = params.CodeHasHostedModels
case stateerrors.IsHasPersistentStorageError(err):
code = params.CodeHasPersistentStorage
case stateerrors.IsModelNotEmptyError(err):
code = params.CodeModelNotEmpty
case isNoAddressSetError(err):
code = params.CodeNoAddressSet
case errors.IsNotProvisioned(err):
code = params.CodeNotProvisioned
case IsUpgradeInProgressError(err):
code = params.CodeUpgradeInProgress
case stateerrors.IsHasAttachmentsError(err):
code = params.CodeMachineHasAttachedStorage
case stateerrors.IsHasContainersError(err):
code = params.CodeMachineHasContainers
case stateerrors.IsStorageAttachedError(err):
code = params.CodeStorageAttached
case isUnknownModelError(err):
code = params.CodeModelNotFound
case errors.IsNotSupported(err):
code = params.CodeNotSupported
case errors.IsBadRequest(err):
code = params.CodeBadRequest
case errors.IsMethodNotAllowed(err):
code = params.CodeMethodNotAllowed
case errors.IsNotImplemented(err):
code = params.CodeNotImplemented
case errors.IsForbidden(err):
code = params.CodeForbidden
case IsIncompatibleSeriesError(err), stateerrors.IsIncompatibleSeriesError(err):
code = params.CodeIncompatibleSeries
case IsDischargeRequiredError(err):
dischErr := errors.Cause(err).(*DischargeRequiredError)
code = params.CodeDischargeRequired
info = params.DischargeRequiredErrorInfo{
Macaroon: dischErr.LegacyMacaroon,
BakeryMacaroon: dischErr.Macaroon,
// One macaroon fits all.
MacaroonPath: "/",
}.AsMap()
case IsUpgradeSeriesValidationError(err):
rawErr := errors.Cause(err).(*UpgradeSeriesValidationError)
info = params.UpgradeSeriesValidationErrorInfo{
Status: rawErr.Status,
}.AsMap()
case IsRedirectError(err):
redirErr := errors.Cause(err).(*RedirectError)
code = params.CodeRedirect
// Check for a zero-value tag. We don't send it over the wire if it is.
controllerTag := ""
if redirErr.ControllerTag.Id() != "" {
controllerTag = redirErr.ControllerTag.String()
}
info = params.RedirectErrorInfo{
Servers: params.FromProviderHostsPorts(redirErr.Servers),
CACert: redirErr.CACert,
ControllerTag: controllerTag,
ControllerAlias: redirErr.ControllerAlias,
}.AsMap()
case errors.IsQuotaLimitExceeded(err):
code = params.CodeQuotaLimitExceeded
case errors.IsNotYetAvailable(err):
code = params.CodeNotYetAvailable
case params.IsIncompatibleClientError(err):
code = params.CodeIncompatibleClient
rawErr := errors.Cause(err).(*params.IncompatibleClientError)
info = rawErr.AsMap()
case IsNotLeaderError(err):
code = params.CodeNotLeader
rawErr := errors.Cause(err).(*NotLeaderError)
info = rawErr.AsMap()
case IsDeadlineExceededError(err):
code = params.CodeDeadlineExceeded
case lease.IsLeaseError(err):
code = params.CodeLeaseError
info = leaseErrorInfoMap(err)
default:
code = params.ErrCode(err)
}
return ¶ms.Error{
Message: msg,
Code: code,
Info: info,
}
}
func DestroyErr(desc string, ids []string, errs []error) error {
// TODO(waigani) refactor DestroyErr to take a map of ids to errors.
if len(errs) == 0 {
return nil
}
msg := "some %s were not destroyed"
if len(errs) == len(ids) {
msg = "no %s were destroyed"
}
msg = fmt.Sprintf(msg, desc)
errStrings := make([]string, len(errs))
for i, err := range errs {
errStrings[i] = err.Error()
}
return errors.Errorf("%s: %s", msg, strings.Join(errStrings, "; "))
}
// RestoreError makes a best effort at converting the given error
// back into an error originally converted by ServerError().
func RestoreError(err error) error {
err = errors.Cause(err)
if apiErr, ok := err.(*params.Error); !ok {
return err
} else if apiErr == nil {
return nil
}
if params.ErrCode(err) == "" {
return err
}
msg := err.Error()
if ok, singleton := singletonError(err); ok {
return singleton
}
// TODO(ericsnow) Support the other error types handled by ServerError().
switch {
case params.IsCodeUnauthorized(err):
return errors.NewUnauthorized(nil, msg)
case params.IsCodeNotFound(err):
// TODO(ericsnow) UnknownModelError should be handled here too.
// ...by parsing msg?
return errors.NewNotFound(nil, msg)
case params.IsCodeUserNotFound(err):
return errors.NewUserNotFound(nil, msg)
case params.IsCodeAlreadyExists(err):
return errors.NewAlreadyExists(nil, msg)
case params.IsCodeNotAssigned(err):
return errors.NewNotAssigned(nil, msg)
case params.IsCodeHasAssignedUnits(err):
// TODO(ericsnow) Handle stateerrors.HasAssignedUnitsError here.
// ...by parsing msg?
return err
case params.IsCodeHasHostedModels(err):
return err
case params.IsCodeHasPersistentStorage(err):
return err
case params.IsCodeModelNotEmpty(err):
return err
case params.IsCodeNoAddressSet(err):
// TODO(ericsnow) Handle isNoAddressSetError here.
// ...by parsing msg?
return err
case params.IsCodeNotProvisioned(err):
return errors.NewNotProvisioned(nil, msg)
case params.IsCodeUpgradeInProgress(err):
// TODO(ericsnow) Handle stateerrors.UpgradeInProgressError here.
// ...by parsing msg?
return err
case params.IsCodeMachineHasAttachedStorage(err):
// TODO(ericsnow) Handle stateerrors.HasAttachmentsError here.
// ...by parsing msg?
return err
case params.IsCodeStorageAttached(err):
return err
case params.IsCodeNotSupported(err):
return errors.NewNotSupported(nil, msg)
case params.IsBadRequest(err):
return errors.NewBadRequest(nil, msg)
case params.IsMethodNotAllowed(err):
return errors.NewMethodNotAllowed(nil, msg)
case params.ErrCode(err) == params.CodeDischargeRequired:
// TODO(ericsnow) Handle DischargeRequiredError here.
return err
case params.IsCodeQuotaLimitExceeded(err):
return errors.NewQuotaLimitExceeded(nil, msg)
case params.IsCodeNotYetAvailable(err):
return errors.NewNotYetAvailable(nil, msg)
case params.IsCodeNotLeader(err):
e, ok := err.(*params.Error)
if !ok {
return err
}
serverAddress, _ := e.Info["server-address"].(string)
serverID, _ := e.Info["server-id"].(string)
return NewNotLeaderError(serverAddress, serverID)
case params.IsCodeDeadlineExceeded(err):
return NewDeadlineExceededError(msg)
case params.IsLeaseError(err):
return rehydrateLeaseError(err)
default:
return err
}
}