Skip to content
Closed
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
52 changes: 52 additions & 0 deletions api/core.openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3292,6 +3292,13 @@ paths:
error:
type: string
type: object
"409":
description: Conflict
schema:
properties:
error:
type: string
type: object
security:
- BearerAuth: []
summary: Delete a compute allocation
Expand Down Expand Up @@ -3649,6 +3656,51 @@ paths:
summary: Update a compute allocation -> resource mapping
tags:
- Compute Allocation Resources
/compute-allocations/{id}/status:
put:
consumes:
- application/json
parameters:
- description: Compute allocation ID
in: path
name: id
required: true
type: string
- description: Status patch
in: body
name: request
required: true
schema:
properties:
status:
$ref: '#/definitions/AllocationStatus'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/ComputeAllocation'
"400":
description: Bad Request
schema:
properties:
error:
type: string
type: object
"404":
description: Not Found
schema:
properties:
error:
type: string
type: object
security:
- BearerAuth: []
summary: Update a compute allocation's status
tags:
- Compute Allocations
/compute-allocations/{id}/usages:
get:
description: Callers without the allocations read privilege must hold a membership
Expand Down
2 changes: 1 addition & 1 deletion docs/storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ Core makes or changes storages and publishes `storage::create` for each, a paren
|---|---|
| An allocation or membership is set `INACTIVE` | Retires the storages it gave |
| An account is deleted | Retires its `{user}` and member storages |
| An allocation is deleted | Retires its `{allocation}` and member storages |
| An `INACTIVE` allocation is deleted | Its retired storages stay `pending_deletion` |
| A user is deleted, or a connector stops holding them | Retires their `{name}` storages |

Making storages also retires those of the same holders the targets no longer give, so a sweep retires every storage
Expand Down
28 changes: 28 additions & 0 deletions internal/server/allocation.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ func (s *Server) getComputeAllocation(w http.ResponseWriter, r *http.Request) {
// @Param id path string true "Compute allocation ID"
// @Success 204 "No Content"
// @Failure 404 {object} object{error=string}
// @Failure 409 {object} object{error=string}
// @Router /compute-allocations/{id} [delete]
func (s *Server) deleteComputeAllocation(w http.ResponseWriter, r *http.Request) {
if err := s.svc.DeleteComputeAllocation(r.Context(), r.PathValue("id")); err != nil {
Expand All @@ -85,6 +86,33 @@ func (s *Server) deleteComputeAllocation(w http.ResponseWriter, r *http.Request)
w.WriteHeader(http.StatusNoContent)
}

// @Summary Update a compute allocation's status
// @Tags Compute Allocations
// @Security BearerAuth
// @Accept json
// @Produce json
// @Param id path string true "Compute allocation ID"
// @Param request body object{status=models.AllocationStatus} true "Status patch"
// @Success 200 {object} models.ComputeAllocation
// @Failure 400 {object} object{error=string}
// @Failure 404 {object} object{error=string}
// @Router /compute-allocations/{id}/status [put]
func (s *Server) updateComputeAllocationStatus(w http.ResponseWriter, r *http.Request) {
var body struct {
Status models.AllocationStatus `json:"status"`
}
if err := common.DecodeJSON(r, &body); err != nil {
common.WriteError(w, http.StatusBadRequest, err)
return
}
updated, err := s.svc.UpdateComputeAllocationStatus(r.Context(), r.PathValue("id"), body.Status)
if err != nil {
common.WriteServiceError(w, err)
return
}
common.WriteJSON(w, http.StatusOK, updated)
}

// @Summary Create a compute allocation diff
// @Description Records a discrete change against a compute allocation (e.g. USAGE_UPDATE or ALLOCATION_STATUS_CHANGE).
// @Tags Compute Allocation Diffs
Expand Down
1 change: 1 addition & 0 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ func (s *Server) routes() {
s.router.RequirePrivilege("POST /compute-allocations", models.AllocationsWrite, s.createComputeAllocation)
s.router.RequireScoped("GET /compute-allocations/{id}", s.canReadAllocation, s.getComputeAllocation)
s.router.RequirePrivilege("DELETE /compute-allocations/{id}", models.AllocationsWrite, s.deleteComputeAllocation)
s.router.RequirePrivilege("PUT /compute-allocations/{id}/status", models.AllocationsWrite, s.updateComputeAllocationStatus)

s.router.RequirePrivilege("POST /compute-allocation-resources", models.AllocationsWrite, s.createComputeAllocationResource)
s.router.RequirePrivilege("GET /compute-allocation-resources", models.AllocationsRead, s.listComputeAllocationResources)
Expand Down
47 changes: 40 additions & 7 deletions pkg/service/compute_allocation.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,14 +216,17 @@ func (s *Service) DeleteComputeAllocation(ctx context.Context, id string) error
if id == "" {
return fmt.Errorf("%w: compute allocation id is required", ErrInvalidInput)
}
alloc, err := s.allocs.FindByID(ctx, id)
if err != nil {
return fmt.Errorf("lookup compute allocation: %w", err)
}
if alloc == nil {
return ErrNotFound
}
if err := s.inTx(ctx, func(tx *sql.Tx) error {
alloc, err := s.allocs.FindByIDTx(ctx, tx, id, store.UpdateLock)
if err != nil {
return fmt.Errorf("lookup compute allocation: %w", err)
}
if alloc == nil {
return ErrNotFound
}
if alloc.Status == models.ACTIVE {
return fmt.Errorf("%w: compute allocation %q is active, set it INACTIVE first", ErrInUse, id)
}
if err := s.allocs.Delete(ctx, tx, id); err != nil {
return err
}
Expand All @@ -236,3 +239,33 @@ func (s *Service) DeleteComputeAllocation(ctx context.Context, id string) error
}
return nil
}

// UpdateComputeAllocationStatus sets an allocation's status and records a diff; INACTIVE ends its members' access.
func (s *Service) UpdateComputeAllocationStatus(ctx context.Context, id string, status models.AllocationStatus) (alloc *models.ComputeAllocation, err error) {
if status != models.ACTIVE && status != models.INACTIVE {
return nil, fmt.Errorf("%w: status must be ACTIVE or INACTIVE", ErrInvalidInput)
}
err = s.inTx(ctx, func(tx *sql.Tx) (err error) {
if alloc, err = s.allocs.FindByIDTx(ctx, tx, id, store.UpdateLock); err != nil {
return err
}
if alloc == nil {
return ErrNotFound
}
if alloc.Status == status {
return nil
}
alloc.Status = status
if err = s.UpdateComputeAllocationTx(ctx, tx, alloc); err != nil {
return err
}
_, err = s.CreateComputeAllocationDiffTx(ctx, tx, &models.ComputeAllocationDiff{
ComputeAllocationID: id,
DiffType: "ALLOCATION_STATUS_CHANGE",
Status: status,
Description: "Set by an admin",
})
return err
})
return
}
57 changes: 57 additions & 0 deletions pkg/service/compute_allocation_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//go:build integration

// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package service

import (
"errors"
"testing"

"github.com/google/uuid"

"github.com/apache/airavata-custos/pkg/models"
)

// Make sure an admin status change records one diff, and setting the same status records none.
func TestUpdateComputeAllocationStatus_RecordsDiff(t *testing.T) {
database := setupTestDB(t)
svc := newTestService(database)
_, allocID := newClusterAllocation(t, svc, seedUser(t, database, uuid.NewString()+"@example.edu"))
for range 2 {
if _, err := svc.UpdateComputeAllocationStatus(ctx(), allocID, models.INACTIVE); err != nil {
t.Fatalf("update status: %v", err)
}
}
diffs, err := svc.ListDiffsForAllocation(ctx(), allocID)
if err != nil || len(diffs) != 1 || diffs[0].DiffType != "ALLOCATION_STATUS_CHANGE" || diffs[0].Status != models.INACTIVE {
t.Fatalf("diffs: %+v, %v; want one INACTIVE ALLOCATION_STATUS_CHANGE", diffs, err)
}
if _, err := svc.UpdateComputeAllocationStatus(ctx(), allocID, models.DELETED); !errors.Is(err, ErrInvalidInput) {
t.Fatalf("status DELETED: %v, want ErrInvalidInput", err)
}
}

func TestDeleteComputeAllocation_RefusedWhileActive(t *testing.T) {
database := setupTestDB(t)
svc := newTestService(database)
_, allocID := newClusterAllocation(t, svc, seedUser(t, database, uuid.NewString()+"@example.edu"))
if err := svc.DeleteComputeAllocation(ctx(), allocID); !errors.Is(err, ErrInUse) {
t.Fatalf("delete active allocation: %v, want ErrInUse", err)
}
}
3 changes: 2 additions & 1 deletion pkg/service/storage_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,8 @@ func TestStorageLifecycle(t *testing.T) {
if err := svc.UpdateStorage(ctx(), byPath()[siblingPath].ID, 1, &until, "", "admin"); !errors.Is(err, ErrNotFound) {
t.Errorf("quota on a storage without one of its own: got %v, want ErrNotFound", err)
}
err = errors.Join(svc.DeleteComputeClusterUser(ctx(), cu.ID), svc.DeleteComputeAllocation(ctx(), sibling.ID))
_, err = svc.UpdateComputeAllocationStatus(ctx(), sibling.ID, models.INACTIVE)
err = errors.Join(err, svc.DeleteComputeClusterUser(ctx(), cu.ID), svc.DeleteComputeAllocation(ctx(), sibling.ID))
if got := byPath(); err != nil || got["/home/jdoe"].Status != "pending_deletion" || got[siblingPath].Status != "pending_deletion" ||
got["/home/jdoe"].ComputeClusterUserID != nil || got[siblingPath].AllocationID != nil {
t.Fatalf("deleting the account and an allocation: err=%v got=%+v, want theirs retired and unlinked", err, got)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import type { ComputeAllocation } from "@/generated/core/zod.gen";
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";

const status = { mutate: vi.fn(), reset: vi.fn(), isPending: false, error: null };
vi.mock("@/shared/casl/permissions", () => ({
usePermissions: () => ({ allocationsWrite: true }),
requires: () => "",
}));
vi.mock("../queries", () => ({ useSetAllocationStatus: () => status }));

import { AllocationStatusButton } from "../components/AllocationStatusButton";

const allocation = (s: ComputeAllocation["status"]) =>
({ id: "a-1", name: "Alpha", status: s }) as ComputeAllocation;

describe("<AllocationStatusButton />", () => {
beforeEach(() => status.mutate.mockClear());

it("deactivates only after the confirm", () => {
render(<AllocationStatusButton allocation={allocation("ACTIVE")} />);
fireEvent.click(screen.getByRole("button", { name: "Deactivate" }));
expect(status.mutate).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Deactivate allocation" }));
expect(status.mutate).toHaveBeenCalledWith("INACTIVE", expect.anything());
});

it("reactivates at once", () => {
render(<AllocationStatusButton allocation={allocation("INACTIVE")} />);
fireEvent.click(screen.getByRole("button", { name: "Reactivate" }));
expect(status.mutate).toHaveBeenCalledWith("ACTIVE", expect.anything());
});
});
11 changes: 11 additions & 0 deletions web/src/features/core/allocations/__tests__/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
removeMember,
submitChangeRequest,
} from "../api";
import { setAllocationStatus } from "../api";

const fetchMock = vi.fn<typeof fetch>();
vi.stubGlobal("fetch", fetchMock);
Expand Down Expand Up @@ -185,6 +186,16 @@ describe("removeMember", () => {
});
});

describe("setAllocationStatus", () => {
it("PUTs INACTIVE to deactivate the allocation", async () => {
fetchMock.mockResolvedValueOnce(mockResponse(200, {}));
await setAllocationStatus("alloc-001", "INACTIVE");
const [url, init] = fetchMock.mock.calls[0] ?? [];
expect(String(url)).toMatch(/\/compute-allocations\/alloc-001\/status$/);
expect(init).toMatchObject({ method: "PUT", body: '{"status":"INACTIVE"}' });
});
});

describe("listChangeRequests", () => {
it("scopes to allocation when allocation_id present", async () => {
fetchMock.mockResolvedValueOnce(mockResponse(200, [changeRequest]));
Expand Down
4 changes: 4 additions & 0 deletions web/src/features/core/allocations/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,10 @@ export async function removeMember(id: string): Promise<void> {
await apiFetch(`/compute-allocation-memberships/${id}`, { method: "DELETE" });
}

export async function setAllocationStatus(id: string, status: "ACTIVE" | "INACTIVE") {
await apiFetch(`/compute-allocations/${id}/status`, { method: "PUT", body: { status } });
}

export async function listChangeRequests(
params: ChangeRequestListParams = {},
): Promise<ChangeRequest[]> {
Expand Down
26 changes: 15 additions & 11 deletions web/src/features/core/allocations/components/AllocationDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { AllocationDetailHeader } from "./AllocationDetailHeader";
import { AllocationHistoryTab } from "./AllocationHistoryTab";
import { AllocationMembersTab } from "./AllocationMembersTab";
import { AllocationOverviewTab } from "./AllocationOverviewTab";
import { AllocationStatusButton } from "./AllocationStatusButton";
import { AllocationUsageTab } from "./AllocationUsageTab";

export type AllocationDetailProps = {
Expand Down Expand Up @@ -65,17 +66,20 @@ export function AllocationDetail({ allocationId }: AllocationDetailProps) {
<section className="space-y-6">
<div className="flex items-start justify-between gap-4">
<AllocationDetailHeader allocation={allocation} memberCount={memberCount} />
<DeleteButton
noun="Allocation"
id={allocation.id}
name={allocation.name}
mutation={remove}
redirectTo="/allocations"
allowed={can.allocationsWrite}
reason={requires("allocationsWrite")}
>
Its members, resources and usage records are deleted with it. This cannot be undone.
</DeleteButton>
<div className="flex gap-2">
<AllocationStatusButton allocation={allocation} />
<DeleteButton
noun="Allocation"
id={allocation.id}
name={allocation.name}
mutation={remove}
redirectTo="/allocations"
allowed={can.allocationsWrite && allocation.status !== "ACTIVE"}
reason={can.allocationsWrite ? "Deactivate it first" : requires("allocationsWrite")}
>
Its members, resources and usage records are deleted with it. This cannot be undone.
</DeleteButton>
</div>
</div>
<TabsRouter
defaultValue="overview"
Expand Down
Loading