Handle occupied VMID holes and recover read-only runner updates
This commit is contained in:
1 parent
dfb285fc2e
commit
b3373373e8
10 files changed
+261
-70
No files matched your search
@@ -144,6 +144,7 @@ func (s *Server) jobRoutes() {
|
|||||||
}))
|
}))
|
||||||
m.HandleFunc("GET /api/v1/dashboard", s.protected(false, s.dashboard))
|
m.HandleFunc("GET /api/v1/dashboard", s.protected(false, s.dashboard))
|
||||||
}
|
}
|
||||||
|
|
||||||
const ownerStorageQuery = `SELECT COALESCE((SELECT sum(size) FROM uploads WHERE owner_id=$1),0)+COALESCE((SELECT sum(a.size) FROM artifacts a JOIN jobs j ON j.id=a.job_id WHERE j.owner_id=$1),0)`
|
const ownerStorageQuery = `SELECT COALESCE((SELECT sum(size) FROM uploads WHERE owner_id=$1),0)+COALESCE((SELECT sum(a.size) FROM artifacts a JOIN jobs j ON j.id=a.job_id WHERE j.owner_id=$1),0)`
|
||||||
|
|
||||||
func (s *Server) upload(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) upload(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|||||||
@@ -79,11 +79,15 @@ func (c *Client) endpoint(path string, q url.Values) string {
|
|||||||
u.RawQuery = q.Encode()
|
u.RawQuery = q.Encode()
|
||||||
return u.String()
|
return u.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
const responseLimit = 24 << 20
|
const responseLimit = 24 << 20
|
||||||
|
|
||||||
var errTransport = errors.New("PVE transport failed")
|
var errTransport = errors.New("PVE transport failed")
|
||||||
var errResponseRead = errors.New("PVE response read failed")
|
var errResponseRead = errors.New("PVE response read failed")
|
||||||
|
|
||||||
|
// ErrVMIDInUse identifies only the documented nextid validation collision.
|
||||||
|
var ErrVMIDInUse = errors.New("PVE VMID is already in use")
|
||||||
|
|
||||||
func (c *Client) decode(req *http.Request, out any) error {
|
func (c *Client) decode(req *http.Request, out any) error {
|
||||||
for attempt := 0; ; attempt++ {
|
for attempt := 0; ; attempt++ {
|
||||||
err := c.decodeOnce(req, out)
|
err := c.decodeOnce(req, out)
|
||||||
@@ -112,6 +116,20 @@ func (c *Client) decodeOnce(req *http.Request, out any) error {
|
|||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
|
if resp.StatusCode == http.StatusBadRequest && req.Method == http.MethodGet && req.URL.Path == "/api2/json/cluster/nextid" {
|
||||||
|
query, queryErr := url.ParseQuery(req.URL.RawQuery)
|
||||||
|
vmid, idErr := strconv.Atoi(query.Get("vmid"))
|
||||||
|
if queryErr == nil && idErr == nil && vmid >= 100 && vmid <= 999999999 && strconv.Itoa(vmid) == query.Get("vmid") && len(query) == 1 && len(query["vmid"]) == 1 {
|
||||||
|
const collisionLimit = 4096
|
||||||
|
body, readErr := io.ReadAll(io.LimitReader(resp.Body, collisionLimit+1))
|
||||||
|
var failure struct {
|
||||||
|
Errors map[string]string `json:"errors"`
|
||||||
|
}
|
||||||
|
if readErr == nil && len(body) <= collisionLimit && json.Unmarshal(body, &failure) == nil && len(failure.Errors) == 1 && failure.Errors["vmid"] == fmt.Sprintf("VM %d already exists", vmid) {
|
||||||
|
return ErrVMIDInUse
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
return &HTTPError{resp.StatusCode}
|
return &HTTPError{resp.StatusCode}
|
||||||
}
|
}
|
||||||
b, err := io.ReadAll(io.LimitReader(resp.Body, responseLimit+1))
|
b, err := io.ReadAll(io.LimitReader(resp.Body, responseLimit+1))
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -374,3 +375,50 @@ func TestGETRetriesInterruptedResponse(t *testing.T) {
|
|||||||
t.Fatalf("interrupted response not retried: result=%q calls=%d error=%v", result, calls, err)
|
t.Fatalf("interrupted response not retried: result=%q calls=%d error=%v", result, calls, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestNextIDClassifiesOnlyExactVMIDCollision(t *testing.T) {
|
||||||
|
const collision = `{"data":null,"errors":{"vmid":"VM 106 already exists"}}`
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, method, path, query, body string
|
||||||
|
status int
|
||||||
|
occupied bool
|
||||||
|
}{
|
||||||
|
{"occupied", "GET", "/cluster/nextid", "vmid=106", collision, 400, true},
|
||||||
|
{"permission", "GET", "/cluster/nextid", "vmid=106", `{"errors":{"vmid":"permission denied"}}`, 400, false},
|
||||||
|
{"different-id", "GET", "/cluster/nextid", "vmid=107", collision, 400, false},
|
||||||
|
{"additional-error", "GET", "/cluster/nextid", "vmid=106", `{"errors":{"vmid":"VM 106 already exists","other":"validation failed"}}`, 400, false},
|
||||||
|
{"malformed", "GET", "/cluster/nextid", "vmid=106", `{"errors":`, 400, false},
|
||||||
|
{"oversized", "GET", "/cluster/nextid", "vmid=106", collision + strings.Repeat(" ", 4096), 400, false},
|
||||||
|
{"wrong-status", "GET", "/cluster/nextid", "vmid=106", collision, 403, false},
|
||||||
|
{"wrong-path", "GET", "/nodes/node/qemu", "vmid=106", collision, 400, false},
|
||||||
|
{"mutation", "POST", "/cluster/nextid", "vmid=106", collision, 400, false},
|
||||||
|
{"missing-query", "GET", "/cluster/nextid", "", collision, 400, false},
|
||||||
|
{"ambiguous-query", "GET", "/cluster/nextid", "vmid=106&vmid=107", collision, 400, false},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
calls := 0
|
||||||
|
c := fixture(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
calls++
|
||||||
|
w.WriteHeader(tc.status)
|
||||||
|
_, _ = io.WriteString(w, tc.body)
|
||||||
|
})
|
||||||
|
query, err := url.ParseQuery(tc.query)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
err = c.Do(context.Background(), tc.method, tc.path, query, nil)
|
||||||
|
if errors.Is(err, ErrVMIDInUse) != tc.occupied {
|
||||||
|
t.Fatalf("occupied=%v error=%v", tc.occupied, err)
|
||||||
|
}
|
||||||
|
if !tc.occupied {
|
||||||
|
var status *HTTPError
|
||||||
|
if !errors.As(err, &status) || status.Status != tc.status {
|
||||||
|
t.Fatalf("unexpected error classification: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err == nil || strings.Contains(err.Error(), "106") || strings.Contains(err.Error(), "permission denied") || calls != 1 {
|
||||||
|
t.Fatalf("response exposed or validation request retried: calls=%d error=%v", calls, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,7 +27,7 @@ func queuedClaimFixture(t *testing.T, ctx context.Context, db *pgxpool.Pool, nam
|
|||||||
}
|
}
|
||||||
defer tx.Rollback(ctx)
|
defer tx.Rollback(ctx)
|
||||||
for _, statement := range []struct {
|
for _, statement := range []struct {
|
||||||
sql string
|
sql string
|
||||||
args []any
|
args []any
|
||||||
}{
|
}{
|
||||||
{"INSERT INTO users(id,username,password_hash,role)VALUES($1::uuid,$1::text,'unused','operator')", []any{owner}},
|
{"INSERT INTO users(id,username,password_hash,role)VALUES($1::uuid,$1::text,'unused','operator')", []any{owner}},
|
||||||
@@ -186,9 +186,9 @@ func TestReservationAdmissionIsAtomic(t *testing.T) {
|
|||||||
// Pending clones must consume capacity before their disks/RAM materialize.
|
// Pending clones must consume capacity before their disks/RAM materialize.
|
||||||
binding.MaxOwnedDiskBytes = 1 << 40
|
binding.MaxOwnedDiskBytes = 1 << 40
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
name string
|
name string
|
||||||
disk, memory, artifact int64
|
disk, memory, artifact int64
|
||||||
want string
|
want string
|
||||||
}{
|
}{
|
||||||
{"memory-boundary", 0, 91 << 30, 0, ""},
|
{"memory-boundary", 0, 91 << 30, 0, ""},
|
||||||
{"memory-exhausted", 0, 92 << 30, 0, "node memory reservation insufficient for another clone"},
|
{"memory-exhausted", 0, 92 << 30, 0, "node memory reservation insufficient for another clone"},
|
||||||
@@ -230,3 +230,69 @@ func TestSourceLockHonorsCallerDeadline(t *testing.T) {
|
|||||||
t.Fatalf("unexpected lock timeout: %v", err)
|
t.Fatalf("unexpected lock timeout: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestNextVMIDSkipsReservedOccupiedAndProtectedIDs(t *testing.T) {
|
||||||
|
ctx, db := workerTestDB(t)
|
||||||
|
owner, ids := queuedClaimFixture(t, ctx, db, "A", "B", "C", "D")
|
||||||
|
for i, id := range ids {
|
||||||
|
var err error
|
||||||
|
if i%2 == 0 {
|
||||||
|
_, err = db.Exec(ctx, `INSERT INTO allocations(id,attempt_id,owner_id,node,vmid,pool,state)VALUES($1,$2,$3,'test',$4,'owner','reserved')`, newID(), id, owner, 102+i)
|
||||||
|
} else {
|
||||||
|
_, err = db.Exec(ctx, `INSERT INTO extractor_allocations(id,attempt_id,owner_id,node,vmid,state,disk_slot,disk_serial,disk_bytes)VALUES($1,$2,$3,'test',$4,'clone_intent','scsi0','test',1)`, newID(), id, owner, 102+i)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e := engine{db: db, cfg: Config{Sources: map[string]Source{"source": {VMID: 7002}}, Extractor: &ExtractorConfig{SourceVMID: 7003}}}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, suggested string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{"reserved-and-cluster-hole", "102", 107},
|
||||||
|
{"protected-sources", "7000", 7004},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet || r.URL.Path != "/api2/json/cluster/nextid" {
|
||||||
|
http.Error(w, "unexpected request", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
candidate := r.URL.Query().Get("vmid")
|
||||||
|
if candidate == "106" {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
_, _ = w.Write([]byte(`{"errors":{"vmid":"VM 106 already exists"},"data":null,"message":"Parameter verification failed.\n"}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if candidate == "" {
|
||||||
|
candidate = tc.suggested
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]string{"data": candidate})
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
root := t.TempDir()
|
||||||
|
ca, token := filepath.Join(root, "ca.pem"), filepath.Join(root, "token.json")
|
||||||
|
if err := os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(token, []byte(`{"token_id":"test@pve!test","secret":"test"}`), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
client, err := pve.New(server.URL, ca, token)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer client.Close()
|
||||||
|
ref := "nextid-" + server.URL
|
||||||
|
conn, err := sourceLock(ctx, db, ref)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer unlockSource(conn, ref)
|
||||||
|
if id, err := e.nextVMID(ctx, conn, client); err != nil || id != tc.want {
|
||||||
|
t.Fatalf("next VMID = %d, %v; want %d", id, err, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -246,26 +246,10 @@ func (e *engine) extractHeld(parent context.Context, a attempt, l allocation, b
|
|||||||
unlockSource(conn, "nextid-"+b.Endpoint)
|
unlockSource(conn, "nextid-"+b.Endpoint)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
var next string
|
id, err := e.nextVMID(ctx, conn, cs.provisioner)
|
||||||
if err = cs.provisioner.Do(ctx, "GET", "/cluster/nextid", nil, &next); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
id, err := strconv.Atoi(next)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.New("invalid extractor nextid")
|
|
||||||
}
|
|
||||||
for _, p := range e.cfg.protected() {
|
|
||||||
if id == p {
|
|
||||||
return errors.New("PVE suggested protected extractor VMID")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var reserved bool
|
|
||||||
if err = e.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM allocations WHERE vmid=$1 AND state<>'deleted') OR EXISTS(SELECT 1 FROM extractor_allocations WHERE vmid=$1 AND state<>'deleted')`, id).Scan(&reserved); err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if reserved {
|
|
||||||
return errors.New("extractor VMID reserved by existing allocation")
|
|
||||||
}
|
|
||||||
x := extractionAllocation{ID: newID(), VMID: id, State: "reserved", DiskSlot: slot, Serial: "otche" + strings.ReplaceAll(a.ID, "-", "")[:16], DiskBytes: size}
|
x := extractionAllocation{ID: newID(), VMID: id, State: "reserved", DiskSlot: slot, Serial: "otche" + strings.ReplaceAll(a.ID, "-", "")[:16], DiskBytes: size}
|
||||||
tx, err := conn.Begin(ctx)
|
tx, err := conn.Begin(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
"net/url"
|
"net/url"
|
||||||
"otche/internal/pve"
|
"otche/internal/pve"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -50,38 +51,9 @@ func (e *engine) provision(ctx context.Context, a attempt, b Binding, cs clients
|
|||||||
unlockSource(idConn, "nextid-"+b.Endpoint)
|
unlockSource(idConn, "nextid-"+b.Endpoint)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
var suggested string
|
id, err := e.nextVMID(ctx, idConn, cs.provisioner)
|
||||||
if err = cs.provisioner.Do(ctx, "GET", "/cluster/nextid", nil, &suggested); err != nil {
|
|
||||||
return l, err
|
|
||||||
}
|
|
||||||
id, err := strconv.Atoi(suggested)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return l, errors.New("invalid PVE nextid")
|
return l, err
|
||||||
}
|
|
||||||
for tries := range 64 {
|
|
||||||
blocked := false
|
|
||||||
for _, n := range e.cfg.protected() {
|
|
||||||
if id == n {
|
|
||||||
blocked = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var exists bool
|
|
||||||
if err = e.db.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM allocations WHERE vmid=$1 AND state<>'deleted') OR EXISTS(SELECT 1 FROM extractor_allocations WHERE vmid=$1 AND state<>'deleted')", id).Scan(&exists); err != nil {
|
|
||||||
return l, err
|
|
||||||
}
|
|
||||||
if !blocked && !exists {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if err = cs.provisioner.Do(ctx, "GET", "/cluster/nextid", url.Values{"vmid": {strconv.Itoa(id + 1)}}, &suggested); err != nil {
|
|
||||||
return l, err
|
|
||||||
}
|
|
||||||
id, err = strconv.Atoi(suggested)
|
|
||||||
if err != nil {
|
|
||||||
return l, err
|
|
||||||
}
|
|
||||||
if tries == 63 {
|
|
||||||
return l, errors.New("could not reserve next free VMID")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
l = allocation{ID: newID(), VMID: id, State: "reserved"}
|
l = allocation{ID: newID(), VMID: id, State: "reserved"}
|
||||||
memoryMiB, err := strconv.ParseInt(pve.Text(source["memory"]), 10, 64)
|
memoryMiB, err := strconv.ParseInt(pve.Text(source["memory"]), 10, 64)
|
||||||
@@ -143,6 +115,55 @@ func (e *engine) provision(ctx context.Context, a attempt, b Binding, cs clients
|
|||||||
return l, nil
|
return l, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The caller holds the nextid session lock through its reservation INSERT.
|
||||||
|
// PVE's vmid parameter asserts one exact ID; it never searches past collisions.
|
||||||
|
func (e *engine) nextVMID(ctx context.Context, conn *pgxpool.Conn, c *pve.Client) (int, error) {
|
||||||
|
var suggested string
|
||||||
|
if err := c.Do(ctx, "GET", "/cluster/nextid", nil, &suggested); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
id, err := strconv.Atoi(suggested)
|
||||||
|
if err != nil || id < 100 || id > 999999999 {
|
||||||
|
return 0, errors.New("invalid PVE nextid")
|
||||||
|
}
|
||||||
|
protected := e.cfg.protected()
|
||||||
|
for ; id <= 999999999; id++ {
|
||||||
|
if err = ctx.Err(); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
blocked := false
|
||||||
|
for _, vmid := range protected {
|
||||||
|
if id == vmid {
|
||||||
|
blocked = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if blocked {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var reserved bool
|
||||||
|
if err = conn.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM allocations WHERE vmid=$1 AND state<>'deleted') OR EXISTS(SELECT 1 FROM extractor_allocations WHERE vmid=$1 AND state<>'deleted')", id).Scan(&reserved); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if reserved {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
candidate := strconv.Itoa(id)
|
||||||
|
var confirmed string
|
||||||
|
if err = c.Do(ctx, "GET", "/cluster/nextid", url.Values{"vmid": {candidate}}, &confirmed); err != nil {
|
||||||
|
if errors.Is(err, pve.ErrVMIDInUse) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if confirmed != candidate {
|
||||||
|
return 0, errors.New("PVE nextid did not confirm requested VMID")
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
return 0, errors.New("could not reserve next free VMID")
|
||||||
|
}
|
||||||
|
|
||||||
// All owner accounting and the caller's INSERT share this transaction. The
|
// All owner accounting and the caller's INSERT share this transaction. The
|
||||||
// artifact-root lock also serializes reservations by owners on different nodes.
|
// artifact-root lock also serializes reservations by owners on different nodes.
|
||||||
func (e *engine) reserveResources(ctx context.Context, tx pgx.Tx, a attempt, b Binding, c *pve.Client, diskBytes, memoryBytes, artifactBytes int64) error {
|
func (e *engine) reserveResources(ctx context.Context, tx pgx.Tx, a attempt, b Binding, c *pve.Client, diskBytes, memoryBytes, artifactBytes int64) error {
|
||||||
@@ -186,16 +207,16 @@ func (e *engine) reserveResources(ctx context.Context, tx pgx.Tx, a attempt, b B
|
|||||||
var node struct {
|
var node struct {
|
||||||
Memory struct {
|
Memory struct {
|
||||||
Total int64 `json:"total"`
|
Total int64 `json:"total"`
|
||||||
Used int64 `json:"used"`
|
Used int64 `json:"used"`
|
||||||
} `json:"memory"`
|
} `json:"memory"`
|
||||||
}
|
}
|
||||||
if err := c.Do(ctx, "GET", "/nodes/"+b.Node+"/status", nil, &node); err != nil {
|
if err := c.Do(ctx, "GET", "/nodes/"+b.Node+"/status", nil, &node); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
var vms []struct {
|
var vms []struct {
|
||||||
VMID int `json:"vmid"`
|
VMID int `json:"vmid"`
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
Mem int64 `json:"mem"`
|
Mem int64 `json:"mem"`
|
||||||
}
|
}
|
||||||
if err := c.Do(ctx, "GET", "/nodes/"+b.Node+"/qemu", nil, &vms); err != nil {
|
if err := c.Do(ctx, "GET", "/nodes/"+b.Node+"/qemu", nil, &vms); err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ func recoveryAttempt(t *testing.T, ctx context.Context, db *pgxpool.Pool) attemp
|
|||||||
a := attempt{ID: newID(), RunID: newID(), JobID: newID(), OwnerID: newID(), ProfileID: newID(), RevisionID: newID(), CommandID: newID()}
|
a := attempt{ID: newID(), RunID: newID(), JobID: newID(), OwnerID: newID(), ProfileID: newID(), RevisionID: newID(), CommandID: newID()}
|
||||||
upload := newID()
|
upload := newID()
|
||||||
statements := []struct {
|
statements := []struct {
|
||||||
sql string
|
sql string
|
||||||
args []any
|
args []any
|
||||||
}{
|
}{
|
||||||
{"INSERT INTO users(id,username,password_hash,role)VALUES($1,$2,'unused','operator')", []any{a.OwnerID, a.OwnerID}},
|
{"INSERT INTO users(id,username,password_hash,role)VALUES($1,$2,'unused','operator')", []any{a.OwnerID, a.OwnerID}},
|
||||||
@@ -81,8 +81,8 @@ func TestSettleJobAccountsForAllRunsAndCancellation(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
first, second string
|
first, second string
|
||||||
cancelled bool
|
cancelled bool
|
||||||
want string
|
want string
|
||||||
}{
|
}{
|
||||||
{"failed", "queued", false, "running"},
|
{"failed", "queued", false, "running"},
|
||||||
{"failed", "running", true, "running"},
|
{"failed", "running", true, "running"},
|
||||||
|
|||||||
@@ -121,6 +121,7 @@ func Run(ctx context.Context, db *pgxpool.Pool, artifactRoot, configPath string)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var healthMessages = struct {
|
var healthMessages = struct {
|
||||||
sync.Mutex
|
sync.Mutex
|
||||||
last map[string]time.Time
|
last map[string]time.Time
|
||||||
|
|||||||
@@ -124,21 +124,62 @@ function Test-SourceInstall([switch]$ForUpdate) {
|
|||||||
}
|
}
|
||||||
return [ordered]@{ok=($problems.Count -eq 0);errors=@($problems.ToArray())}
|
return [ordered]@{ok=($problems.Count -eq 0);errors=@($problems.ToArray())}
|
||||||
}
|
}
|
||||||
|
function Update-SourceRunnerFiles([string]$SourceDirectory,[string]$RunnerDirectory,[string[]]$Names) {
|
||||||
|
$staged=New-Object 'Collections.Generic.List[object]'
|
||||||
|
$failure=$null
|
||||||
|
try {
|
||||||
|
foreach ($name in $Names) {
|
||||||
|
$supplied=Join-Path $SourceDirectory $name;$destination=Join-Path $RunnerDirectory $name;$temp=$destination+'.new'
|
||||||
|
$installed=Get-Item -LiteralPath $destination -Force
|
||||||
|
if ($installed.PSIsContainer -or ($installed.Attributes -band [IO.FileAttributes]::ReparsePoint)) {throw "Runner file is not a regular file: $name"}
|
||||||
|
if ((Get-AuthenticodeSignature -LiteralPath $supplied).Status -ne 'Valid') {throw "Update requires valid trusted Authenticode signature: $name"}
|
||||||
|
$hash=(Get-FileHash -LiteralPath $supplied -Algorithm SHA256).Hash
|
||||||
|
# An interrupted update may leave .new behind. Never overwrite or delete
|
||||||
|
# unrecognized bytes: only a regular file matching this signed bundle is reusable.
|
||||||
|
$item=Get-Item -LiteralPath $temp -Force -ErrorAction SilentlyContinue
|
||||||
|
if ($null -eq $item) {[IO.File]::Copy($supplied,$temp,$false);$item=Get-Item -LiteralPath $temp -Force}
|
||||||
|
if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {throw "Staged runner is not a regular file; inspect manually: $temp"}
|
||||||
|
if ((Get-FileHash -LiteralPath $temp -Algorithm SHA256).Hash -cne $hash -or (Get-AuthenticodeSignature -LiteralPath $supplied).Status -ne 'Valid' -or (Get-FileHash -LiteralPath $supplied -Algorithm SHA256).Hash -cne $hash) {throw "Staged runner differs from signed bundle; inspect manually: $temp"}
|
||||||
|
$staged.Add(@{path=$temp;hash=$hash})
|
||||||
|
# File.Copy preserves ISO ReadOnly. Change only staged attributes, never
|
||||||
|
# the supplied file, installed file or any ACL.
|
||||||
|
[IO.File]::SetAttributes($temp,($item.Attributes -band (-bnot [IO.FileAttributes]::ReadOnly)))
|
||||||
|
}
|
||||||
|
foreach ($name in $Names) {
|
||||||
|
$destination=Join-Path $RunnerDirectory $name
|
||||||
|
$originalAttributes=[IO.File]::GetAttributes($destination)
|
||||||
|
try {
|
||||||
|
# Older ISO-based installations also retained ReadOnly on the target.
|
||||||
|
# All staged signatures/hashes have passed before touching this bit.
|
||||||
|
[IO.File]::SetAttributes($destination,($originalAttributes -band (-bnot [IO.FileAttributes]::ReadOnly)))
|
||||||
|
[IO.File]::Replace(($destination+'.new'),$destination,[System.Management.Automation.Language.NullString]::Value)
|
||||||
|
} catch {
|
||||||
|
$replaceFailure=$_
|
||||||
|
try {[IO.File]::SetAttributes($destination,$originalAttributes)} catch {Write-Warning ('Cannot restore runner attributes: '+$_.Exception.Message) -WarningAction Continue}
|
||||||
|
throw $replaceFailure
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {$failure=$_;throw} finally {
|
||||||
|
$cleanupErrors=New-Object 'Collections.Generic.List[string]'
|
||||||
|
foreach ($entry in $staged) {
|
||||||
|
try {
|
||||||
|
$item=Get-Item -LiteralPath $entry.path -Force -ErrorAction SilentlyContinue
|
||||||
|
if ($null -eq $item) {continue}
|
||||||
|
if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or (Get-FileHash -LiteralPath $entry.path -Algorithm SHA256).Hash -cne $entry.hash) {throw "Staged runner changed; refusing cleanup: $($entry.path)"}
|
||||||
|
[IO.File]::SetAttributes($entry.path,($item.Attributes -band (-bnot [IO.FileAttributes]::ReadOnly)))
|
||||||
|
[IO.File]::Delete($entry.path)
|
||||||
|
} catch {$cleanupErrors.Add($_.Exception.Message)}
|
||||||
|
}
|
||||||
|
if ($cleanupErrors.Count) {
|
||||||
|
$message='Staged runner cleanup failed: '+($cleanupErrors -join '; ')
|
||||||
|
if ($null -ne $failure) {Write-Warning $message -WarningAction Continue} else {throw $message}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if ($Verify -or $UpdateRunner) {
|
if ($Verify -or $UpdateRunner) {
|
||||||
$check=Test-SourceInstall -ForUpdate:$UpdateRunner
|
$check=Test-SourceInstall -ForUpdate:$UpdateRunner
|
||||||
if ($Verify -or !$check.ok) {$check|ConvertTo-Json -Depth 5 -Compress;if (!$check.ok) {exit 1};exit 0}
|
if ($Verify -or !$check.ok) {$check|ConvertTo-Json -Depth 5 -Compress;if (!$check.ok) {exit 1};exit 0}
|
||||||
$staged=New-Object 'Collections.Generic.List[string]'
|
Update-SourceRunnerFiles $PSScriptRoot "$root\runner" $files
|
||||||
try {
|
|
||||||
foreach ($name in $files) {
|
|
||||||
$supplied=Join-Path $PSScriptRoot $name;$destination="$root\runner\$name";$temp=$destination+'.new'
|
|
||||||
if ((Get-Item -LiteralPath $destination).Attributes -band [IO.FileAttributes]::ReparsePoint) {throw "Runner file is a reparse point: $name"}
|
|
||||||
if ((Get-AuthenticodeSignature -LiteralPath $supplied).Status -ne 'Valid') {throw "Update requires valid trusted Authenticode signature: $name"}
|
|
||||||
$hash=(Get-FileHash -LiteralPath $supplied -Algorithm SHA256).Hash
|
|
||||||
[IO.File]::Copy($supplied,$temp,$false);$staged.Add($temp)
|
|
||||||
if ((Get-FileHash -LiteralPath $temp -Algorithm SHA256).Hash -cne $hash -or (Get-AuthenticodeSignature -LiteralPath $supplied).Status -ne 'Valid' -or (Get-FileHash -LiteralPath $supplied -Algorithm SHA256).Hash -cne $hash) {throw "Staged runner changed: $name"}
|
|
||||||
}
|
|
||||||
foreach ($name in $files) {[IO.File]::Replace("$root\runner\$name.new","$root\runner\$name",[System.Management.Automation.Language.NullString]::Value)}
|
|
||||||
} finally {foreach ($path in $staged) {if ([IO.File]::Exists($path)) {[IO.File]::Delete($path)}}}
|
|
||||||
Import-Module "$root\runner\Otche.Common.psm1" -Force
|
Import-Module "$root\runner\Otche.Common.psm1" -Force
|
||||||
Get-OtcheBaseline|ConvertTo-Json -Depth 18 -Compress
|
Get-OtcheBaseline|ConvertTo-Json -Depth 18 -Compress
|
||||||
exit 0
|
exit 0
|
||||||
@@ -217,7 +258,11 @@ try {
|
|||||||
$rw.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($account.SID,'Modify','ContainerInherit,ObjectInherit','None','Allow'))
|
$rw.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($account.SID,'Modify','ContainerInherit,ObjectInherit','None','Allow'))
|
||||||
[IO.Directory]::SetAccessControl("$root\$dir",$rw)
|
[IO.Directory]::SetAccessControl("$root\$dir",$rw)
|
||||||
}
|
}
|
||||||
foreach ($name in $files) {[IO.File]::Copy((Join-Path $PSScriptRoot $name),"$root\runner\$name",$false)}
|
foreach ($name in $files) {
|
||||||
|
$destination="$root\runner\$name"
|
||||||
|
[IO.File]::Copy((Join-Path $PSScriptRoot $name),$destination,$false)
|
||||||
|
[IO.File]::SetAttributes($destination,([IO.File]::GetAttributes($destination) -band (-bnot [IO.FileAttributes]::ReadOnly)))
|
||||||
|
}
|
||||||
Import-Module "$root\runner\Otche.Common.psm1" -Force
|
Import-Module "$root\runner\Otche.Common.psm1" -Force
|
||||||
Write-OtcheJson "$root\source.json" @{account_sid=$account.SID.Value;account="$env:COMPUTERNAME\$user";installed_at=(Get-OtcheUtc);runner_version='1.0.0';autologon=[bool]$EnableAutoLogon} -CreateNew
|
Write-OtcheJson "$root\source.json" @{account_sid=$account.SID.Value;account="$env:COMPUTERNAME\$user";installed_at=(Get-OtcheUtc);runner_version='1.0.0';autologon=[bool]$EnableAutoLogon} -CreateNew
|
||||||
$exe="$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe"
|
$exe="$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe"
|
||||||
|
|||||||
@@ -48,6 +48,13 @@ Prerequisites and trust
|
|||||||
task/autologon drift or a busy task, before copying anything. Requires Valid
|
task/autologon drift or a busy task, before copying anything. Requires Valid
|
||||||
trusted signatures for all six replacement files; stages all as .new, checks
|
trusted signatures for all six replacement files; stages all as .new, checks
|
||||||
their hashes, then uses atomic per-file replacement preserving existing ACLs.
|
their hashes, then uses atomic per-file replacement preserving existing ACLs.
|
||||||
|
ISO ReadOnly attributes are removed only from owned installed/staged copies,
|
||||||
|
never from the source media; other attribute bits and ACLs are preserved. Updates
|
||||||
|
clear a legacy target's ReadOnly bit only after all staged files pass validation,
|
||||||
|
restoring original target attributes if replacement fails. A stale .new is reused
|
||||||
|
only if it is a regular, non-reparse file whose hash matches the signed bundle;
|
||||||
|
unrecognized staging files are left untouched for inspection. Cleanup failures
|
||||||
|
are warnings when another failure is already pending, preserving its real cause.
|
||||||
No task, account, registry, autologon secret or directory ACL is changed. The JSON
|
No task, account, registry, autologon secret or directory ACL is changed. The JSON
|
||||||
output is the NEW Get-OtcheBaseline, not qualification. Do not dispatch during
|
output is the NEW Get-OtcheBaseline, not qualification. Do not dispatch during
|
||||||
maintenance. Replacement is atomic per file, not a six-file transaction: if an
|
maintenance. Replacement is atomic per file, not a six-file transaction: if an
|
||||||
|
|||||||
Reference in new issue
Block a user