Skip to content

Commit

Permalink
feat(daemon): add ErrorResponse to allow external error creation (#303)
Browse files Browse the repository at this point in the history
#265 provides the ability for the daemon REST API to be extended by appending new handlers to the API list.

For example, the following new reboot command can be added now:

// requestReboot asks the daemon to gracefully shut down the system
// and issue a reboot.
func requestReboot(d *daemon.Daemon) daemon.Response {
        d.HandleRestart(restart.RestartSystem)
        result := deviceResult{}
        return daemon.SyncResponse(result)
}

Note that SyncResponse was already public, which allows the code above to work.

Following this patch, we can now reply with a suitable error response:

:
    switch(...) {
    case reboot:
        requestReboot(...)
    default:    
        return daemon.ErrorResponse(http.StatusBadRequest,"invalid media type %q", mediaType)
    {
:
  • Loading branch information
flotter authored Sep 29, 2023
1 parent 4540a7b commit ae456c9
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 38 deletions.
6 changes: 5 additions & 1 deletion client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -416,11 +416,15 @@ func (e *Error) Error() string {
return e.Message
}

// Error kinds for use as a response or maintenance result
const (
ErrorKindLoginRequired = "login-required"
ErrorKindNoDefaultServices = "no-default-services"
ErrorKindNotFound = "not-found"
ErrorKindPermissionDenied = "permission-denied"
ErrorKindGenericFileError = "generic-file-error"
ErrorKindSystemRestart = "system-restart"
ErrorKindDaemonRestart = "daemon-restart"
ErrorKindNoDefaultServices = "no-default-services"
)

func (rsp *response) err(cli *Client) error {
Expand Down
71 changes: 39 additions & 32 deletions internals/daemon/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,11 @@ func (r *resp) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
if err != nil {
logger.Noticef("Cannot marshal %#v to JSON: %v", *r, err)
bs = nil
status = 500
status = http.StatusInternalServerError
}

hdr := w.Header()
if r.Status == 202 || r.Status == 201 {
if r.Status == http.StatusAccepted || r.Status == http.StatusCreated {
if m, ok := r.Result.(map[string]interface{}); ok {
if location, ok := m["resource"]; ok {
if location, ok := location.(string); ok && location != "" {
Expand All @@ -116,22 +116,21 @@ func (r *resp) ServeHTTP(w http.ResponseWriter, _ *http.Request) {

type errorKind string

// Error kinds for use as a response or maintenance result
const (
errorKindLoginRequired = errorKind("login-required")
errorKindDaemonRestart = errorKind("daemon-restart")
errorKindSystemRestart = errorKind("system-restart")
errorKindNoDefaultServices = errorKind("no-default-services")
errorKindNotFound = errorKind("not-found")
errorKindPermissionDenied = errorKind("permission-denied")
errorKindGenericFileError = errorKind("generic-file-error")
errorKindSystemRestart = errorKind("system-restart")
errorKindDaemonRestart = errorKind("daemon-restart")
)

type errorValue interface{}

type errorResult struct {
Message string `json:"message"` // note no omitempty
Kind errorKind `json:"kind,omitempty"`
Value errorValue `json:"value,omitempty"`
Message string `json:"message"` // note no omitempty
Kind errorKind `json:"kind,omitempty"`
Value interface{} `json:"value,omitempty"`
}

func SyncResponse(result interface{}) Response {
Expand All @@ -145,15 +144,15 @@ func SyncResponse(result interface{}) Response {

return &resp{
Type: ResponseTypeSync,
Status: 200,
Status: http.StatusOK,
Result: result,
}
}

func AsyncResponse(result map[string]interface{}, change string) Response {
return &resp{
Type: ResponseTypeAsync,
Status: 202,
Status: http.StatusAccepted,
Result: result,
Change: change,
}
Expand All @@ -169,22 +168,30 @@ func (f fileResponse) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, string(f))
}

// ErrorResponse builds an error Response that returns the status and formatted message.
//
// If no arguments are provided, formatting is disabled, and the format string
// is used as is and not interpreted in any way.
func ErrorResponse(status int, format string, v ...interface{}) Response {
res := &errorResult{}
if len(v) == 0 {
res.Message = format
} else {
res.Message = fmt.Sprintf(format, v...)
}
if status == http.StatusUnauthorized {
res.Kind = errorKindLoginRequired
}
return &resp{
Type: ResponseTypeError,
Result: res,
Status: status,
}
}

func makeErrorResponder(status int) errorResponder {
return func(format string, v ...interface{}) Response {
res := &errorResult{}
if len(v) == 0 {
res.Message = format
} else {
res.Message = fmt.Sprintf(format, v...)
}
if status == 401 {
res.Kind = errorKindLoginRequired
}
return &resp{
Type: ResponseTypeError,
Result: res,
Status: status,
}
return ErrorResponse(status, format, v...)
}
}

Expand All @@ -194,11 +201,11 @@ type errorResponder func(string, ...interface{}) Response

// Standard error responses.
var (
statusBadRequest = makeErrorResponder(400)
statusUnauthorized = makeErrorResponder(401)
statusForbidden = makeErrorResponder(403)
statusNotFound = makeErrorResponder(404)
statusMethodNotAllowed = makeErrorResponder(405)
statusInternalError = makeErrorResponder(500)
statusGatewayTimeout = makeErrorResponder(504)
statusBadRequest = makeErrorResponder(http.StatusBadRequest)
statusUnauthorized = makeErrorResponder(http.StatusUnauthorized)
statusForbidden = makeErrorResponder(http.StatusForbidden)
statusNotFound = makeErrorResponder(http.StatusNotFound)
statusMethodNotAllowed = makeErrorResponder(http.StatusMethodNotAllowed)
statusInternalError = makeErrorResponder(http.StatusInternalServerError)
statusGatewayTimeout = makeErrorResponder(http.StatusGatewayTimeout)
)
10 changes: 5 additions & 5 deletions internals/daemon/response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func (s *responseSuite) TestRespSetsLocationIfAccepted(c *check.C) {
rec := httptest.NewRecorder()

rsp := &resp{
Status: 202,
Status: http.StatusAccepted,
Result: map[string]interface{}{
"resource": "foo/bar",
},
Expand All @@ -49,7 +49,7 @@ func (s *responseSuite) TestRespSetsLocationIfCreated(c *check.C) {
rec := httptest.NewRecorder()

rsp := &resp{
Status: 201,
Status: http.StatusCreated,
Result: map[string]interface{}{
"resource": "foo/bar",
},
Expand All @@ -64,7 +64,7 @@ func (s *responseSuite) TestRespDoesNotSetLocationIfOther(c *check.C) {
rec := httptest.NewRecorder()

rsp := &resp{
Status: 418, // I'm a teapot
Status: http.StatusTeapot, // I'm a teapot
Result: map[string]interface{}{
"resource": "foo/bar",
},
Expand Down Expand Up @@ -104,7 +104,7 @@ func (s *responseSuite) TestRespJSONWithNullResult(c *check.C) {
}

func (s *responseSuite) TestErrorResponderPrintfsWithArgs(c *check.C) {
teapot := makeErrorResponder(418)
teapot := makeErrorResponder(http.StatusTeapot)

rec := httptest.NewRecorder()
rsp := teapot("system memory below %d%%.", 1)
Expand All @@ -119,7 +119,7 @@ func (s *responseSuite) TestErrorResponderPrintfsWithArgs(c *check.C) {
}

func (s *responseSuite) TestErrorResponderDoesNotPrintfAlways(c *check.C) {
teapot := makeErrorResponder(418)
teapot := makeErrorResponder(http.StatusTeapot)

rec := httptest.NewRecorder()
rsp := teapot("system memory below 1%.")
Expand Down

0 comments on commit ae456c9

Please sign in to comment.