Skip to content

Commit

Permalink
fix(daemon): Export error responders from daemon.response
Browse files Browse the repository at this point in the history
  • Loading branch information
thp-canonical committed Feb 14, 2024
1 parent 0a1127e commit edb95bf
Show file tree
Hide file tree
Showing 14 changed files with 113 additions and 113 deletions.
22 changes: 11 additions & 11 deletions internals/daemon/api_changes.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ func v1GetChanges(c *Command, r *http.Request, _ *UserState) Response {
case "ready":
filter = func(chg *state.Change) bool { return chg.Status().Ready() }
default:
return statusBadRequest("select should be one of: all,in-progress,ready")
return BadRequest("select should be one of: all,in-progress,ready")
}

if wantedName := query.Get("for"); wantedName != "" {
Expand Down Expand Up @@ -177,7 +177,7 @@ func v1GetChange(c *Command, r *http.Request, _ *UserState) Response {
defer st.Unlock()
chg := st.Change(changeID)
if chg == nil {
return statusNotFound("cannot find change with id %q", changeID)
return NotFound("cannot find change with id %q", changeID)
}

return SyncResponse(change2changeInfo(chg))
Expand All @@ -190,12 +190,12 @@ func v1GetChangeWait(c *Command, r *http.Request, _ *UserState) Response {
change := st.Change(changeID)
st.Unlock()
if change == nil {
return statusNotFound("cannot find change with id %q", changeID)
return NotFound("cannot find change with id %q", changeID)
}

timeout, err := parseOptionalDuration(r.URL.Query().Get("timeout"))
if err != nil {
return statusBadRequest("invalid timeout: %v", err)
return BadRequest("invalid timeout: %v", err)
}
if timeout != 0 {
// Timeout specified, wait till change is ready or timeout occurs,
Expand All @@ -205,16 +205,16 @@ func v1GetChangeWait(c *Command, r *http.Request, _ *UserState) Response {
case <-change.Ready():
timer.Stop() // change ready, release timer resources
case <-timer.C:
return statusGatewayTimeout("timed out waiting for change after %s", timeout)
return GatewayTimeout("timed out waiting for change after %s", timeout)
case <-r.Context().Done():
return statusInternalError("request cancelled")
return InternalError("request cancelled")
}
} else {
// No timeout, wait indefinitely for change to be ready.
select {
case <-change.Ready():
case <-r.Context().Done():
return statusInternalError("request cancelled")
return InternalError("request cancelled")
}
}

Expand All @@ -230,7 +230,7 @@ func v1PostChange(c *Command, r *http.Request, _ *UserState) Response {
defer state.Unlock()
chg := state.Change(chID)
if chg == nil {
return statusNotFound("cannot find change with id %q", chID)
return NotFound("cannot find change with id %q", chID)
}

var reqData struct {
Expand All @@ -239,15 +239,15 @@ func v1PostChange(c *Command, r *http.Request, _ *UserState) Response {

decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&reqData); err != nil {
return statusBadRequest("cannot decode data from request body: %v", err)
return BadRequest("cannot decode data from request body: %v", err)
}

if reqData.Action != "abort" {
return statusBadRequest("change action %q is unsupported", reqData.Action)
return BadRequest("change action %q is unsupported", reqData.Action)
}

if chg.Status().Ready() {
return statusBadRequest("cannot abort change %s with nothing pending", chID)
return BadRequest("cannot abort change %s with nothing pending", chID)
}

// flag the change
Expand Down
4 changes: 2 additions & 2 deletions internals/daemon/api_checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ func v1GetChecks(c *Command, r *http.Request, _ *UserState) Response {
switch level {
case plan.UnsetLevel, plan.AliveLevel, plan.ReadyLevel:
default:
return statusBadRequest(`level must be "alive" or "ready"`)
return BadRequest(`level must be "alive" or "ready"`)
}

names := strutil.MultiCommaSeparatedList(query["names"])

checkMgr := c.d.overlord.CheckManager()
checks, err := checkMgr.Checks()
if err != nil {
return statusInternalError("%v", err)
return InternalError("%v", err)
}

infos := []checkInfo{} // if no checks, return [] instead of null
Expand Down
16 changes: 8 additions & 8 deletions internals/daemon/api_exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,26 +47,26 @@ func v1PostExec(c *Command, req *http.Request, _ *UserState) Response {
var payload execPayload
decoder := json.NewDecoder(req.Body)
if err := decoder.Decode(&payload); err != nil {
return statusBadRequest("cannot decode request body: %v", err)
return BadRequest("cannot decode request body: %v", err)
}
if len(payload.Command) < 1 {
return statusBadRequest("must specify command")
return BadRequest("must specify command")
}

timeout, err := parseOptionalDuration(payload.Timeout)
if err != nil {
return statusBadRequest("invalid timeout: %v", err)
return BadRequest("invalid timeout: %v", err)
}

// Check up-front that the executable exists.
_, err = exec.LookPath(payload.Command[0])
if err != nil {
return statusBadRequest("cannot find executable %q", payload.Command[0])
return BadRequest("cannot find executable %q", payload.Command[0])
}

p, err := c.d.overlord.ServiceManager().Plan()
if err != nil {
return statusBadRequest("%v", err)
return BadRequest("%v", err)
}
overrides := plan.ContextOptions{
Environment: payload.Environment,
Expand All @@ -78,13 +78,13 @@ func v1PostExec(c *Command, req *http.Request, _ *UserState) Response {
}
merged, err := plan.MergeServiceContext(p, payload.ServiceContext, overrides)
if err != nil {
return statusBadRequest("%v", err)
return BadRequest("%v", err)
}

// Convert User/UserID and Group/GroupID combinations into raw uid/gid.
uid, gid, err := osutil.NormalizeUidGid(merged.UserID, merged.GroupID, merged.User, merged.Group)
if err != nil {
return statusBadRequest("%v", err)
return BadRequest("%v", err)
}

st := c.d.overlord.State()
Expand All @@ -106,7 +106,7 @@ func v1PostExec(c *Command, req *http.Request, _ *UserState) Response {
}
task, metadata, err := cmdstate.Exec(st, args)
if err != nil {
return statusInternalError("cannot call exec: %v", err)
return InternalError("cannot call exec: %v", err)
}

change := st.NewChange("exec", fmt.Sprintf("Execute command %q", args.Command[0]))
Expand Down
40 changes: 20 additions & 20 deletions internals/daemon/api_files.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,25 +44,25 @@ func v1GetFiles(_ *Command, req *http.Request, _ *UserState) Response {
case "read":
paths := query["path"]
if len(paths) == 0 {
return statusBadRequest("must specify one or more paths")
return BadRequest("must specify one or more paths")
}
if req.Header.Get("Accept") != "multipart/form-data" {
return statusBadRequest(`must accept multipart/form-data`)
return BadRequest(`must accept multipart/form-data`)
}
return readFilesResponse{paths: paths}
case "list":
path := query.Get("path")
if path == "" {
return statusBadRequest("must specify path")
return BadRequest("must specify path")
}
pattern := query.Get("pattern")
itself := query.Get("itself")
if itself != "true" && itself != "false" && itself != "" {
return statusBadRequest(`itself parameter must be "true" or "false"`)
return BadRequest(`itself parameter must be "true" or "false"`)
}
return listFilesResponse(path, pattern, itself == "true")
default:
return statusBadRequest("invalid action %q", action)
return BadRequest("invalid action %q", action)
}
}

Expand Down Expand Up @@ -283,7 +283,7 @@ func fileInfoToResult(fullPath string, info os.FileInfo, userCache, groupCache m

func listFilesResponse(path, pattern string, itself bool) Response {
if !pathpkg.IsAbs(path) {
return statusBadRequest("path must be absolute, got %q", path)
return BadRequest("path must be absolute, got %q", path)
}
result, err := listFiles(path, pattern, itself)
if err != nil {
Expand Down Expand Up @@ -341,14 +341,14 @@ func v1PostFiles(_ *Command, req *http.Request, _ *UserState) Response {
contentType := req.Header.Get("Content-Type")
mediaType, params, err := mime.ParseMediaType(contentType)
if err != nil {
return statusBadRequest("invalid Content-Type %q", contentType)
return BadRequest("invalid Content-Type %q", contentType)
}

switch mediaType {
case "multipart/form-data":
boundary := params["boundary"]
if len(boundary) < minBoundaryLength {
return statusBadRequest("invalid boundary %q", boundary)
return BadRequest("invalid boundary %q", boundary)
}
return writeFiles(req.Body, boundary)
case "application/json":
Expand All @@ -359,20 +359,20 @@ func v1PostFiles(_ *Command, req *http.Request, _ *UserState) Response {
}
decoder := json.NewDecoder(req.Body)
if err := decoder.Decode(&payload); err != nil {
return statusBadRequest("cannot decode request body: %v", err)
return BadRequest("cannot decode request body: %v", err)
}
switch payload.Action {
case "make-dirs":
return makeDirs(payload.Dirs)
case "remove":
return removePaths(payload.Paths)
case "write":
return statusBadRequest(`must use multipart with "write" action`)
return BadRequest(`must use multipart with "write" action`)
default:
return statusBadRequest("invalid action %q", payload.Action)
return BadRequest("invalid action %q", payload.Action)
}
default:
return statusBadRequest("invalid media type %q", mediaType)
return BadRequest("invalid media type %q", mediaType)
}
}

Expand All @@ -393,10 +393,10 @@ func writeFiles(body io.Reader, boundary string) Response {
mr := multipart.NewReader(body, boundary)
part, err := mr.NextPart()
if err != nil {
return statusBadRequest("cannot read request metadata: %v", err)
return BadRequest("cannot read request metadata: %v", err)
}
if part.FormName() != "request" {
return statusBadRequest(`metadata field name must be "request", got %q`, part.FormName())
return BadRequest(`metadata field name must be "request", got %q`, part.FormName())
}

// Decode metadata about files to write.
Expand All @@ -406,13 +406,13 @@ func writeFiles(body io.Reader, boundary string) Response {
}
decoder := json.NewDecoder(part)
if err := decoder.Decode(&payload); err != nil {
return statusBadRequest("cannot decode request metadata: %v", err)
return BadRequest("cannot decode request metadata: %v", err)
}
if payload.Action != "write" {
return statusBadRequest(`multipart action must be "write", got %q`, payload.Action)
return BadRequest(`multipart action must be "write", got %q`, payload.Action)
}
if len(payload.Files) == 0 {
return statusBadRequest("must specify one or more files")
return BadRequest("must specify one or more files")
}
infos := make(map[string]writeFilesItem)
for _, file := range payload.Files {
Expand All @@ -426,15 +426,15 @@ func writeFiles(body io.Reader, boundary string) Response {
break
}
if err != nil {
return statusBadRequest("cannot read file part %d: %v", i, err)
return BadRequest("cannot read file part %d: %v", i, err)
}
if part.FormName() != "files" {
return statusBadRequest(`field name must be "files", got %q`, part.FormName())
return BadRequest(`field name must be "files", got %q`, part.FormName())
}
path := multipartFilename(part)
info, ok := infos[path]
if !ok {
return statusBadRequest("no metadata for path %q", path)
return BadRequest("no metadata for path %q", path)
}
errors[path] = writeFile(info, part)
part.Close()
Expand Down
4 changes: 2 additions & 2 deletions internals/daemon/api_health.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,15 @@ func v1Health(c *Command, r *http.Request, _ *UserState) Response {
switch level {
case plan.UnsetLevel, plan.AliveLevel, plan.ReadyLevel:
default:
return statusBadRequest(`level must be "alive" or "ready"`)
return BadRequest(`level must be "alive" or "ready"`)
}

names := strutil.MultiCommaSeparatedList(query["names"])

checks, err := getChecks(c.d.overlord)
if err != nil {
logger.Noticef("Cannot fetch checks: %v", err.Error())
return statusInternalError("internal server error")
return InternalError("internal server error")
}

healthy := true
Expand Down
8 changes: 4 additions & 4 deletions internals/daemon/api_logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (r logsResponse) ServeHTTP(w http.ResponseWriter, req *http.Request) {

followStr := query.Get("follow")
if followStr != "" && followStr != "true" && followStr != "false" {
response := statusBadRequest(`follow parameter must be "true" or "false"`)
response := BadRequest(`follow parameter must be "true" or "false"`)
response.ServeHTTP(w, req)
return
}
Expand All @@ -72,7 +72,7 @@ func (r logsResponse) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if nStr != "" {
n, err := strconv.Atoi(nStr)
if err != nil || n < -1 {
response := statusBadRequest("n must be -1, 0, or a positive integer")
response := BadRequest("n must be -1, 0, or a positive integer")
response.ServeHTTP(w, req)
return
}
Expand All @@ -87,7 +87,7 @@ func (r logsResponse) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if len(services) == 0 {
infos, err := r.svcMgr.Services(nil)
if err != nil {
response := statusInternalError("cannot fetch services: %v", err)
response := InternalError("cannot fetch services: %v", err)
response.ServeHTTP(w, req)
return
}
Expand All @@ -99,7 +99,7 @@ func (r logsResponse) ServeHTTP(w http.ResponseWriter, req *http.Request) {

itsByName, err := r.svcMgr.ServiceLogs(services, numLogs)
if err != nil {
response := statusInternalError("cannot fetch log iterators: %v", err)
response := InternalError("cannot fetch log iterators: %v", err)
response.ServeHTTP(w, req)
return
}
Expand Down
Loading

0 comments on commit edb95bf

Please sign in to comment.