117 lines
2.4 KiB
Go
117 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"io/ioutil"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/google/subcommands"
|
|
"tulpa.dev/within/wasmcloud/cmd/internal"
|
|
"within.website/olin/policy"
|
|
)
|
|
|
|
type handlerUpdateCmd struct {
|
|
abi, policyFile string
|
|
}
|
|
|
|
func (handlerUpdateCmd) Name() string { return "update" }
|
|
func (handlerUpdateCmd) Synopsis() string { return "update a handler" }
|
|
func (handlerUpdateCmd) Usage() string {
|
|
return `wasmcloud update [options] <filename.wasm>
|
|
|
|
$ wasmcloud update shaman-of-hearts-23813 filename.wasm
|
|
|
|
Updates a handler on wasmcloud. Returns new details about the handler.
|
|
|
|
Flags:
|
|
`
|
|
}
|
|
|
|
func (h *handlerUpdateCmd) SetFlags(fs *flag.FlagSet) {
|
|
fs.StringVar(&h.abi, "abi", "cwa", "WebAssembly ABI to use for the handler")
|
|
fs.StringVar(&h.policyFile, "policy", "", "if set, use this policy file for the handler")
|
|
}
|
|
|
|
func (h handlerUpdateCmd) Execute(ctx context.Context, fs *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
|
|
if fs.NArg() != 2 {
|
|
fmt.Println("usage: wasmcloud update [options] <handler-name> <filename>")
|
|
return subcommands.ExitUsageError
|
|
}
|
|
|
|
hname := fs.Arg(0)
|
|
fname := fs.Arg(1)
|
|
data, err := ioutil.ReadFile(fname)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
hdlr := internal.Handler{
|
|
ABI: h.abi,
|
|
WASM: data,
|
|
}
|
|
|
|
if h.policyFile != "" {
|
|
data, err := ioutil.ReadFile(h.policyFile)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
pol, err := policy.Parse(h.policyFile, data)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
err = internal.ValidatePolicy(pol)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
hdlr.Policy = data
|
|
}
|
|
|
|
bodyData, _ := json.Marshal(hdlr)
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, *apiServer+"/api/handler/update?name="+hname, bytes.NewBuffer(bodyData))
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
withAPI(req)
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
io.Copy(os.Stdout, resp.Body)
|
|
return subcommands.ExitFailure
|
|
}
|
|
|
|
type apiResp struct {
|
|
ID int `json:"ID"`
|
|
CreatedAt time.Time `json:"CreatedAt"`
|
|
UpdatedAt time.Time `json:"UpdatedAt"`
|
|
Name string `json:"Name"`
|
|
Path string `json:"Path"`
|
|
}
|
|
|
|
var result apiResp
|
|
err = json.NewDecoder(resp.Body).Decode(&result)
|
|
resp.Body.Close()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
fmt.Println("updated handler")
|
|
fmt.Printf("name: %s\nIPFS ID: %s\n", result.Name, result.Path)
|
|
|
|
return subcommands.ExitSuccess
|
|
}
|