Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
32 changes: 29 additions & 3 deletions api/batch.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ func batchJSON(w http.ResponseWriter, value any) {

func (b *batchBackend) api(w http.ResponseWriter, r *http.Request) {
operation := strings.TrimPrefix(r.URL.Path, batchAPI+"/")
methods := map[string]string{"state": "GET", "details": "GET", "review": "GET", "result": "GET", "simulate": "POST", "action": "POST", "apply": "POST", "discard": "POST", "primitive/create": "POST", "group/children": "POST", "group/create": "POST", "clone/children": "POST", "clone/create": "POST", "tag/objects": "POST", "tag/create": "POST", "tag/fetch": "GET", "tag/update": "POST", "tag/rename": "POST", "tag/delete": "POST", "alert/create": "POST", "alert/fetch": "GET", "alert/update": "POST", "alert/rename": "POST", "alert/delete": "POST", "colocation/fetch": "POST", "colocation/update": "POST", "colocation/rename": "POST", "colocation/delete": "POST", "colocation/options": "POST", "colocation/create": "POST", "location/options": "POST", "location/create": "POST", "location/fetch": "POST", "location/update": "POST", "location/rename": "POST", "location/delete": "POST"}
methods := map[string]string{"state": "GET", "details": "GET", "review": "GET", "result": "GET", "simulate": "POST", "action": "POST", "apply": "POST", "discard": "POST", "primitive/create": "POST", "group/children": "POST", "group/create": "POST", "clone/children": "POST", "clone/create": "POST", "tag/objects": "POST", "tag/create": "POST", "tag/fetch": "GET", "tag/update": "POST", "tag/rename": "POST", "tag/delete": "POST", "alert/create": "POST", "alert/fetch": "GET", "alert/update": "POST", "alert/rename": "POST", "alert/delete": "POST", "colocation/fetch": "POST", "colocation/update": "POST", "colocation/rename": "POST", "colocation/delete": "POST", "order/fetch": "GET", "order/update": "POST", "order/rename": "POST", "order/delete": "POST", "order/options": "POST", "order/create": "POST", "colocation/options": "POST", "colocation/create": "POST", "location/options": "POST", "location/create": "POST", "location/fetch": "POST", "location/update": "POST", "location/rename": "POST", "location/delete": "POST"}
method, ok := methods[operation]
if !ok {
http.NotFound(w, r)
Expand Down Expand Up @@ -374,7 +374,7 @@ func (b *batchBackend) api(w http.ResponseWriter, r *http.Request) {
}, func(ctx context.Context, args ...string) error {
return runColocationUpdateUsing(ctx, run, args...)
}, batchBase)
case "colocation/options":
case "colocation/options", "order/options":
var input struct{}
if !readBatchJSON(w, r, &input) {
return
Expand All @@ -385,6 +385,30 @@ func (b *batchBackend) api(w http.ResponseWriter, r *http.Request) {
return
}
batchJSON(w, cib.ColocationResources)
case "order/fetch":
fetchOrderEdit(w, r, func(ctx context.Context, name string, args []string, input string) ([]byte, error) {
return b.run(ctx, false, name, args, input)
})
case "order/update":
var order orderCreate
if !readBatchJSON(w, r, &order) {
return
}
saveOrderEdit(w, r, order, func(ctx context.Context, name string, args []string, input string) ([]byte, error) {
return b.run(ctx, false, name, args, input)
})
case "order/create":
var order orderCreate
if !readBatchJSON(w, r, &order) {
return
}
saveOrder(w, r, order, func() (CIB, int, error) {
cib, _, err := b.readCIB(ctx, false)
return cib, 0, err
}, func(ctx context.Context, args ...string) error {
_, err := b.run(ctx, false, "crm", args, "")
return err
}, batchBase)
case "colocation/create":
var colocation colocationCreate
if !readBatchJSON(w, r, &colocation) {
Expand Down Expand Up @@ -453,7 +477,7 @@ func (b *batchBackend) api(w http.ResponseWriter, r *http.Request) {
saveTagUpdate(w, r, tag, func(ctx context.Context, name string, args []string, input string) ([]byte, error) {
return b.run(ctx, false, name, args, input)
})
case "colocation/rename", "colocation/delete", "tag/rename", "tag/delete", "alert/rename", "alert/delete", "location/rename", "location/delete":
case "order/rename", "order/delete", "colocation/rename", "colocation/delete", "tag/rename", "tag/delete", "alert/rename", "alert/delete", "location/rename", "location/delete":
var id, newID string
if strings.HasSuffix(operation, "/rename") {
var input struct {
Expand All @@ -478,6 +502,8 @@ func (b *batchBackend) api(w http.ResponseWriter, r *http.Request) {
action = locationAction
} else if strings.HasPrefix(operation, "colocation/") {
action = colocationAction
} else if strings.HasPrefix(operation, "order/") {
action = orderAction
}
status, err := action(ctx, id, newID, func(ctx context.Context, name string, args []string, input string) ([]byte, error) {
return b.run(ctx, false, name, args, input)
Expand Down
20 changes: 17 additions & 3 deletions api/order.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ type orderCreate struct {
}

func OrderNewHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/cib/live/orders/new" && r.URL.Path != "/cib/live/orders/new/" {
base := "/cib/live"
switch r.URL.Path {
case "/cib/live/orders/new", "/cib/live/orders/new/":
case batchBase + "/orders/new", batchBase + "/orders/new/":
base = batchBase
default:
http.NotFound(w, r)
return
}
Expand All @@ -26,7 +31,13 @@ func OrderNewHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Method not allowed", 405)
return
}
renderTemplate(w, "order_new", map[string]any{"Title": "Create Order"})
data := map[string]any{"Title": "Create Order", "CIBBase": base}
if base == batchBase {
data["BatchMode"] = true
data["BatchConfig"] = map[string]string{"base": batchBase, "api": batchAPI, "id": batchID}
data["OrderAPI"] = batchAPI + "/order"
}
renderTemplate(w, "order_new", data)
}

func orderCreateArgs(order orderCreate) ([]string, error) {
Expand Down Expand Up @@ -95,6 +106,9 @@ func createOrder(w http.ResponseWriter, r *http.Request, read func() (CIB, int,
http.Error(w, "Invalid request", 400)
return
}
saveOrder(w, r, order, read, run, "/cib/live")
}
func saveOrder(w http.ResponseWriter, r *http.Request, order orderCreate, read func() (CIB, int, error), run func(context.Context, ...string) error, base string) {
args, err := orderCreateArgs(order)
if err != nil {
http.Error(w, err.Error(), 400)
Expand Down Expand Up @@ -123,7 +137,7 @@ func createOrder(w http.ResponseWriter, r *http.Request, read func() (CIB, int,
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok", "redirect": "/cib/live/orders/" + url.PathEscape(order.ID) + "/edit?flash=created"})
_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok", "redirect": base + "/orders/" + url.PathEscape(order.ID) + "/edit?flash=created"})
}
func OrderRubyHandler(w http.ResponseWriter, r *http.Request) {
resourceRubyHandler(w, r, "Constraint")
Expand Down
20 changes: 17 additions & 3 deletions api/order_edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ func readOrderEdit(ctx context.Context, id string, run clusterConfigCommand) (or
}
func OrderEditHandler(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
if len(parts) != 5 || parts[0] != "cib" || parts[1] != "live" || parts[2] != "orders" || parts[4] != "edit" {
if len(parts) != 5 || parts[0] != "cib" || (parts[1] != "live" && parts[1] != batchID) || parts[2] != "orders" || parts[4] != "edit" {
OrderRubyHandler(w, r)
return
}
Expand All @@ -111,7 +111,14 @@ func OrderEditHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Method not allowed", 405)
return
}
renderTemplate(w, "order_new", map[string]any{"Title": "Edit Order", "Editing": true, "OrderID": parts[3]})
base := "/cib/" + parts[1]
data := map[string]any{"Title": "Edit Order", "Editing": true, "OrderID": parts[3], "CIBBase": base}
if base == batchBase {
data["BatchMode"] = true
data["BatchConfig"] = map[string]string{"base": batchBase, "api": batchAPI, "id": batchID}
data["OrderAPI"] = batchAPI + "/order"
}
renderTemplate(w, "order_new", data)
}
func OrderFetchHandler(w http.ResponseWriter, r *http.Request) {
fetchOrderEdit(w, r, runClusterConfigCommand)
Expand Down Expand Up @@ -148,6 +155,9 @@ func updateOrderEdit(w http.ResponseWriter, r *http.Request, run clusterConfigCo
http.Error(w, "Invalid request", 400)
return
}
saveOrderEdit(w, r, request, run)
}
func saveOrderEdit(w http.ResponseWriter, r *http.Request, request orderCreate, run clusterConfigCommand) {
args, err := orderCreateArgs(request)
if err != nil {
http.Error(w, err.Error(), 400)
Expand Down Expand Up @@ -178,10 +188,14 @@ func updateOrderEdit(w http.ResponseWriter, r *http.Request, run clusterConfigCo
for _, arg := range args[1:] {
tokens = append(tokens, "'"+strings.ReplaceAll(arg, "'", "'\"'\"'")+"'")
}
if _, err := run(r.Context(), "crm", []string{"-F", "configure", "load", "update", "/dev/stdin"}, strings.Join(tokens, " ")+"\n"); err != nil {
if _, err := run(r.Context(), "crm", []string{"-F", "configure", "load", "update", "-"}, strings.Join(tokens, " ")+"\n"); err != nil {
http.Error(w, tagCreateError(request.ID, err), 500)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok", "message": "Constraint updated successfully"})
}

func orderAction(ctx context.Context, id, newID string, run clusterConfigCommand) (int, error) {
return constraintAction(ctx, id, newID, "order", run)
}
53 changes: 52 additions & 1 deletion api/order_edit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func TestOrderEditAPI(t *testing.T) {
}
writes++
require.Equal(t, "crm", name)
require.Equal(t, []string{"-F", "configure", "load", "update", "/dev/stdin"}, args)
require.Equal(t, []string{"-F", "configure", "load", "update", "-"}, args)
require.Equal(t, "'order' 'o' 'Optional:' 'b:promote' 'a:start' 'symmetrical=false'\n", input)
if tt.fail {
return nil, fmt.Errorf("Permission denied")
Expand Down Expand Up @@ -98,3 +98,54 @@ func TestOrderEditPage(t *testing.T) {
require.Contains(t, w.Body.String(), text)
}
}

func TestBatchOrderEdit(t *testing.T) {
backend, calls := batchTestBackend(t)
original := backend.run
backend.run = func(ctx context.Context, live bool, name string, args []string, input string) ([]byte, error) {
out, err := original(ctx, live, name, args, input)
if name == "cibadmin" {
return []byte(orderEditFixture), nil
}
return out, err
}
response := batchTestRequest(backend, "GET", "order/fetch?id=o", "")
require.Equal(t, 200, response.Code, response.Body.String())
require.Contains(t, response.Body.String(), `"score":"Mandatory"`)
response = batchTestRequest(backend, "POST", "order/update", `{"id":"o","score":"Optional","symmetrical":false,"resources":[{"sequential":true,"action":"promote","resources":["b"]},{"sequential":true,"action":"start","resources":["a"]}]}`)
require.Equal(t, 200, response.Code, response.Body.String())
require.JSONEq(t, `{"status":"ok","message":"Constraint updated successfully"}`, response.Body.String())
last := (*calls)[len(*calls)-1]
require.Equal(t, []string{"-F", "configure", "load", "update", "-"}, last.args)
require.Equal(t, "'order' 'o' 'Optional:' 'b:promote' 'a:start' 'symmetrical=false'\n", last.input)
for _, operation := range []string{"rename", "delete"} {
body := `"o"`
if operation == "rename" {
body = `{"oldID":"o","newID":"o2"}`
}
response = batchTestRequest(backend, "POST", "order/"+operation, body)
require.Equal(t, 200, response.Code, response.Body.String())
response = batchTestRequest(backend, "POST", "order/"+operation, strings.ReplaceAll(body, `"o"`, `"a"`))
require.Equal(t, 404, response.Code, response.Body.String())
}
for _, call := range *calls {
require.False(t, call.live)
}
*calls = nil
response = batchTestRequest(backend, "POST", "order/update", `{"id":"missing","score":"Mandatory","symmetrical":true,"resources":[{"sequential":true,"resources":["a"]},{"sequential":true,"resources":["b"]}]}`)
require.Equal(t, 404, response.Code, response.Body.String())
require.Len(t, *calls, 1)
}

func TestBatchOrderEditPage(t *testing.T) {
cwd, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(".."))
t.Cleanup(func() { _ = os.Chdir(cwd) })
response := httptest.NewRecorder()
OrderEditHandler(response, httptest.NewRequest("GET", batchBase+"/orders/o/edit?flash=created", nil))
require.Equal(t, 200, response.Code)
for _, value := range []string{`data-editing="true"`, `data-order-id="o"`, `data-api-base="` + batchAPI + `/order"`, `data-rename-api="` + batchAPI + `/order/rename"`, `data-delete-api="` + batchAPI + `/order/delete"`, `href="` + batchBase + `/orders/new"`, `href="` + batchBase + `/config/edit#constraints"`, `/static/js/batch.js`, `id="rename-order"`, `id="delete-order"`, `id="revert-order"`} {
require.Contains(t, response.Body.String(), value)
}
}
62 changes: 62 additions & 0 deletions api/order_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"html/template"
"net/http/httptest"
"os"
"strings"
"testing"

Expand Down Expand Up @@ -113,3 +114,64 @@ func TestOrderTemplate(t *testing.T) {
OrderNewHandler(response, httptest.NewRequest("POST", "/cib/live/orders/new", nil))
require.Equal(t, 405, response.Code)
}

func TestBatchOrderCreate(t *testing.T) {
backend, calls := batchTestBackend(t)
original := backend.run
backend.run = func(ctx context.Context, live bool, name string, args []string, input string) ([]byte, error) {
out, err := original(ctx, live, name, args, input)
if name == "cibadmin" {
return []byte(`<cib><configuration><resources><primitive id="r2"/><group id="g"><primitive id="nested"/></group><template id="t"/></resources></configuration></cib>`), nil
}
return out, err
}
response := batchTestRequest(backend, "POST", "order/options", `{}`)
require.Equal(t, 200, response.Code, response.Body.String())
require.JSONEq(t, `["g","r2","t"]`, response.Body.String())
payload := `{"id":"order1","score":"Mandatory","symmetrical":false,"resources":[{"sequential":true,"action":"promote","resources":["g"]},{"sequential":false,"action":"start","resources":["r2","t"]}]}`
response = batchTestRequest(backend, "POST", "order/create", payload)
require.Equal(t, 200, response.Code, response.Body.String())
require.JSONEq(t, `{"status":"ok","redirect":"/cib/hacluster/orders/order1/edit?flash=created"}`, response.Body.String())
last := (*calls)[len(*calls)-1]
require.Equal(t, "crm", last.name)
require.Equal(t, []string{"configure", "order", "order1", "Mandatory:", "g:promote", "(", "r2:start", "t:start", ")", "symmetrical=false"}, last.args)
for _, call := range *calls {
require.False(t, call.live)
}
*calls = nil
response = batchTestRequest(backend, "POST", "order/create", strings.Replace(payload, `"r2"`, `"nested"`, 1))
require.Equal(t, 409, response.Code, response.Body.String())
for _, call := range *calls {
require.NotEqual(t, "crm", call.name)
}
*calls = nil
response = batchTestRequest(backend, "POST", "order/create", strings.Replace(payload, `"Mandatory"`, `"invalid"`, 1))
require.Equal(t, 400, response.Code, response.Body.String())
require.Empty(t, *calls)
}

func TestOrderNewCIBContext(t *testing.T) {
cwd, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(".."))
t.Cleanup(func() { _ = os.Chdir(cwd) })
for _, base := range []string{"/cib/live", batchBase} {
for _, suffix := range []string{"", "/"} {
response := httptest.NewRecorder()
OrderNewHandler(response, httptest.NewRequest("GET", base+"/orders/new"+suffix, nil))
require.Equal(t, 200, response.Code)
html := response.Body.String()
require.Contains(t, html, `href="`+base+`/constraints/types"`)
api := "/api/cib/order"
options := api + "/options/fetch"
if base == batchBase {
api = batchAPI + "/order"
options = api + "/options"
}
require.Contains(t, html, `data-api-base="`+api+`"`)
require.Contains(t, html, `data-options-api="`+options+`"`)
require.Equal(t, base == batchBase, strings.Contains(html, `/static/js/batch.js`))
require.NotContains(t, html, `id="rename-order"`)
}
}
}
3 changes: 3 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,11 @@ func main() {
mux.HandleFunc("/cib/hacluster/commands/", authMiddleware(api.CommandsHandler))
mux.HandleFunc("/cib/live/commands", authMiddleware(api.CommandsHandler))
mux.HandleFunc("/cib/live/commands/", authMiddleware(api.CommandsHandler))
mux.HandleFunc("/cib/hacluster/orders/new", authMiddleware(api.OrderNewHandler))
mux.HandleFunc("/cib/hacluster/orders/new/", authMiddleware(api.OrderNewHandler))
mux.HandleFunc("/cib/live/orders/new", authMiddleware(api.OrderNewHandler))
mux.HandleFunc("/cib/live/orders/new/", authMiddleware(api.OrderNewHandler))
mux.HandleFunc("/cib/hacluster/orders/", authMiddleware(api.OrderEditHandler))
mux.HandleFunc("/cib/live/orders/", authMiddleware(api.OrderEditHandler))
mux.HandleFunc("/api/cib/order/options/fetch", authMiddleware(api.FetchColocationOptions))
mux.HandleFunc("/api/cib/order/create", authMiddleware(api.OrderCreateHandler))
Expand Down
3 changes: 2 additions & 1 deletion static/js/classes/Order.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ class Order {
async update() { return this.save("update"); }

async save(operation) {
const response = await fetch(`/api/cib/order/${operation}`, {
const api = document.getElementById("order-create-form").dataset.apiBase || "/api/cib/order";
const response = await fetch(`${api}/${operation}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
Expand Down
Loading
Loading