-
Notifications
You must be signed in to change notification settings - Fork 574
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
cmd/snap: add debug api
command
#14116
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
// -*- Mode: Go; indent-tabs-mode: t -*- | ||
|
||
/* | ||
* Copyright (C) 2024 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 ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"io" | ||
"net/url" | ||
"strings" | ||
|
||
"github.com/jessevdk/go-flags" | ||
"github.com/snapcore/snapd/logger" | ||
) | ||
|
||
var longDebugAPIHelp = ` | ||
Execute a raw query to snapd API. Complex input can be read from stdin, while | ||
output is printed to stdout. See examples below: | ||
|
||
List all snaps: | ||
$ snap debug api /v2/snaps | ||
|
||
Find snaps with name foo: | ||
$ snap debug api '/v2/find?name=foo' | ||
|
||
Request refresh of snap 'some-snap': | ||
$ echo '{"action": "refresh"}' | snap debug api -X POST \ | ||
-H 'Content-Type: application/json' /v2/snaps/some-snap | ||
` | ||
|
||
type cmdDebugAPI struct { | ||
clientMixin | ||
|
||
Headers []string `short:"H" long:"header"` | ||
Method string `short:"X" long:"request"` | ||
Fail bool `long:"fail"` | ||
// TODO support -F/--form like curl | ||
// TODO support -d/--data like curl | ||
|
||
Positional struct { | ||
PathAndQuery string `positional-arg-name:"<path-and-query>"` | ||
} `positional-args:"yes" required:"yes"` | ||
} | ||
|
||
func init() { | ||
addDebugCommand("api", | ||
"Execute raw query to snapd API", | ||
longDebugAPIHelp, | ||
func() flags.Commander { | ||
return &cmdDebugAPI{} | ||
}, map[string]string{ | ||
"header": "Set header (can be repeated multiple times), header kind and value are separated with ': '", | ||
"request": "HTTP method to use (defaults to GET)", | ||
"fail": "Fail on request errors", | ||
}, nil) | ||
} | ||
|
||
func (x *cmdDebugAPI) Execute(args []string) error { | ||
method := x.Method | ||
switch method { | ||
case "GET", "POST", "PUT": | ||
case "": | ||
method = "GET" | ||
default: | ||
return fmt.Errorf("unsupported method %q", method) | ||
} | ||
|
||
var in io.Reader | ||
switch method { | ||
case "POST", "PUT": | ||
in = Stdin | ||
} | ||
|
||
u, err := url.Parse(x.Positional.PathAndQuery) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
hdrs := x.Headers | ||
reqHdrs := make(map[string]string, len(hdrs)) | ||
for _, hdr := range x.Headers { | ||
before, after, sep := strings.Cut(hdr, ": ") | ||
if !sep { | ||
return fmt.Errorf("cannot parse header %q", hdr) | ||
} | ||
reqHdrs[before] = after | ||
} | ||
logger.Debugf("url: %v", u.Path) | ||
logger.Debugf("query: %v", u.RawQuery) | ||
logger.Debugf("headers: %s", reqHdrs) | ||
|
||
rsp, err := x.client.DebugRaw(context.Background(), method, u.Path, u.Query(), reqHdrs, in) | ||
if err != nil { | ||
return err | ||
} | ||
defer rsp.Body.Close() | ||
|
||
logger.Debugf("response: %v", rsp.Status) | ||
logger.Debugf("response headers: %v", rsp.Header) | ||
logger.Debugf("response length: %v", rsp.ContentLength) | ||
|
||
if rsp.Header.Get("Content-Type") == "application/json" { | ||
// pretty print JSON response by default | ||
|
||
var temp map[string]interface{} | ||
if err := json.NewDecoder(rsp.Body).Decode(&temp); err != nil { | ||
return err | ||
} | ||
enc := json.NewEncoder(Stdout) | ||
enc.SetIndent("", " ") | ||
if err := enc.Encode(temp); err != nil { | ||
return err | ||
} | ||
} else { | ||
if _, err := io.Copy(Stdout, rsp.Body); err != nil { | ||
return err | ||
} | ||
} | ||
|
||
if x.Fail && rsp.StatusCode >= 400 { | ||
// caller wants to fail on non success requests | ||
return fmt.Errorf("request failed with status %v", rsp.Status) | ||
} | ||
|
||
return nil | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think somewhere here it warrants a simple example just to show how it's used
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If you add an example (like you have in the PR description), you could add it to the command's long description so it's easily accessible
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've added some examples in long description of the command.