Skip to content
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

Add new user_data API helpers (#150) #161

Merged
merged 3 commits into from
Sep 6, 2015
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1128,7 +1128,7 @@ $ scw inspect myserver | jq '.[0].public_ip.address'
#### Features

* `scw info` now prints user/organization info from the API ([#142](https://github.com/scaleway/scaleway-cli/issues/130)
*
* Added helpers to manipulate new `user_data` API ([#150](https://github.com/scaleway/scaleway-cli/issues/150))

#### Fixes

Expand Down
93 changes: 93 additions & 0 deletions pkg/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
Expand Down Expand Up @@ -1322,6 +1323,98 @@ func (s *ScalewayAPI) GetBootscript(bootscriptID string) (*ScalewayBootscript, e
return &oneBootscript.Bootscript, nil
}

type ScalewayUserdatas struct {
UserData []string `json:"user_data"`
}

// GetUserdatas gets list of userdata for a server
func (s *ScalewayAPI) GetUserdatas(serverID string) (*ScalewayUserdatas, error) {
resp, err := s.GetResponse("servers/" + serverID + "/user_data")
if err != nil {
return nil, err
}
defer resp.Body.Close()
var userdatas ScalewayUserdatas
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&userdatas)
if err != nil {
return nil, err
}
return &userdatas, nil
}

type ScalewayUserdata []byte

func (s *ScalewayUserdata) String() string {
return string(*s)
}

// GetUserdata gets a specific userdata for a server
func (s *ScalewayAPI) GetUserdata(serverID string, key string) (*ScalewayUserdata, error) {
var data ScalewayUserdata
var err error
resp, err := s.GetResponse("servers/" + serverID + "/user_data/" + key)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("no such user_data %q (%d)", key, resp.StatusCode)
}

defer resp.Body.Close()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line should not be after the line 1359 ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep :)

data, err = ioutil.ReadAll(resp.Body)
return &data, err
}

// PatchUserdata sets a user data
func (s *ScalewayAPI) PatchUserdata(serverID string, key string, value []byte) error {
resource := fmt.Sprintf("servers/%s/user_data/%s", serverID, key)
uri := fmt.Sprintf("%s/%s", strings.TrimRight(s.APIUrl, "/"), resource)
payload := new(bytes.Buffer)
payload.Write(value)

req, err := http.NewRequest("PATCH", uri, payload)
if err != nil {
return err
}

req.Header.Set("X-Auth-Token", s.Token)
req.Header.Set("Content-Type", "text/plain")

curl, err := http2curl.GetCurlCommand(req)
if os.Getenv("SCW_SENSITIVE") != "1" {
log.Debug(s.HideAPICredentials(curl.String()))
} else {
log.Debug(curl.String())
}

resp, err := s.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()

if resp.StatusCode == 204 {
return nil
}

return fmt.Errorf("cannot set user_data (%d)", resp.StatusCode)
}

// DeleteUserdata deletes a server user_data
func (s *ScalewayAPI) DeleteUserdata(serverID string, key string) error {
resp, err := s.DeleteResponse(fmt.Sprintf("servers/%s/user_data/%s", serverID, key))
if err != nil {
return err
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

defer resp.Body.Close()

// Succeed POST code
if resp.StatusCode == 204 {
return nil
}
return fmt.Errorf("cannot delete user_data (%d)", resp.StatusCode)
}

// GetTasks get the list of tasks from the ScalewayAPI
func (s *ScalewayAPI) GetTasks() (*[]ScalewayTask, error) {
query := url.Values{}
Expand Down
1 change: 1 addition & 0 deletions pkg/cli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ var Commands = []*Command{
cmdStop,
cmdTag,
cmdTop,
cmdUserdata,
cmdVersion,
cmdWait,
}
2 changes: 1 addition & 1 deletion pkg/cli/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ var (
"version", "wait",
}
secretCommands []string = []string{
"_patch", "_completion", "_flush-cache",
"_patch", "_completion", "_flush-cache", "_userdata",
}
publicOptions []string = []string{
"-h, --help=false",
Expand Down
85 changes: 85 additions & 0 deletions pkg/cli/x_userdata.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Copyright (C) 2015 Scaleway. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.md file.

package cli

import (
"fmt"
"strings"
)

var cmdUserdata = &Command{
Exec: runUserdata,
UsageLine: "_userdata [OPTIONS] SERVER [FIELD[=VALUE]]",
Description: "",
Hidden: true,
Help: "List, read and write and delete server's userdata",
Examples: `
$ scw _userdata myserver
$ scw _userdata myserver key
$ scw _userdata myserver key=value
$ scw _userdata myserver key=""
`,
}

func init() {
cmdUserdata.Flag.BoolVar(&userdataHelp, []string{"h", "-help"}, false, "Print usage")
}

// Flags
var userdataHelp bool // -h, --help flag

func runUserdata(cmd *Command, args []string) error {
if userdataHelp {
return cmd.PrintUsage()
}
if len(args) < 1 {
return cmd.PrintShortUsage()
}

ctx := cmd.GetContext(args)
serverID := ctx.API.GetServerID(args[0])

switch len(args) {
case 1:
// List userdata
res, err := ctx.API.GetUserdatas(serverID)
if err != nil {
return err
}
for _, key := range res.UserData {
fmt.Fprintln(ctx.Stdout, key)
}
default:
parts := strings.Split(args[1], "=")
key := parts[0]
switch len(parts) {
case 1:
// Get userdatas
res, err := ctx.API.GetUserdata(serverID, key)
if err != nil {
return err
}
fmt.Fprintf(ctx.Stdout, "%s\n", res.String())
default:
value := parts[1]
if value != "" {
// Set userdata
err := ctx.API.PatchUserdata(serverID, key, []byte(value))
if err != nil {
return err
}
fmt.Fprintln(ctx.Stdout, key)
} else {
// Delete userdata
err := ctx.API.DeleteUserdata(serverID, key)
if err != nil {
return err
}
}
}
}

return nil
}