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
2 changes: 1 addition & 1 deletion backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ require (
github.com/hashicorp/hcl/v2 v2.25.0
github.com/jackc/pgx/v5 v5.10.0
github.com/michielvha/logger v0.0.5
github.com/michielvha/stackweaver/core v0.631.9
github.com/michielvha/stackweaver/core v0.631.11
github.com/redis/go-redis/v9 v9.23.0
github.com/robfig/cron/v3 v3.0.1
github.com/zclconf/go-cty v1.19.0
Expand Down
4 changes: 2 additions & 2 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/michielvha/logger v0.0.5 h1:zcepKGWRMgo32j6nU++RBWtzzz2Q5txVquGDbaSlCro=
github.com/michielvha/logger v0.0.5/go.mod h1:YJjpbm0AlPmmLBFO8tPyBAruWMJisu2sPo/DX9qxKJk=
github.com/michielvha/stackweaver/core v0.631.9 h1:hmtEVOfDOVfRWzUAITlzyfkEUmznvNTQxqQVKcjqCKo=
github.com/michielvha/stackweaver/core v0.631.9/go.mod h1:Bt8/peil8riL5pzhiLbkoT5b9d30PH+GYKQVpfeqKKI=
github.com/michielvha/stackweaver/core v0.631.11 h1:i9HP6hY034Md3iWJ92+PHprqOg08wBCAkAIxEUkwZrk=
github.com/michielvha/stackweaver/core v0.631.11/go.mod h1:Bt8/peil8riL5pzhiLbkoT5b9d30PH+GYKQVpfeqKKI=
github.com/microsoft/go-mssqldb v1.7.2 h1:CHkFJiObW7ItKTJfHo1QX7QBBD1iV+mn1eOyRP3b/PA=
github.com/microsoft/go-mssqldb v1.7.2/go.mod h1:kOvZKUdrhhFQmxLZqbwUV0rHkNkZpthMITIb2Ko1IoA=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
Expand Down
12 changes: 11 additions & 1 deletion backend/internal/api/v2/handlers/hosted_capacity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ import (
"encoding/json"
"net/http"
"testing"
"time"

"github.com/google/uuid"
"github.com/michielvha/stackweaver/backend/internal/services/rbac"
"github.com/michielvha/stackweaver/backend/internal/services/runner"
"github.com/michielvha/stackweaver/core/models"
"github.com/michielvha/stackweaver/core/repository"
)
Expand All @@ -31,7 +33,10 @@ func TestHostedCapacity_ReadByMembers(t *testing.T) {
pool.PlacementGroup, pool.MaxConcurrentJobs = group, &capV
proj := &models.Project{ID: uuid.New(), OrganizationID: f.orgA.ID, Name: "hostedcap-" + f.sfx}
ws := &models.Workspace{ProjectID: proj.ID, Name: "hostedcap-ws-" + f.sfx, ExecutionMode: "remote"}
launcher := &models.Runner{ID: uuid.New(), Kind: models.RunnerKindHosted, HostedGroup: group, Name: "hostedcap-l-" + f.sfx, Status: models.RunnerStatusOnline}
// An online launcher has a fresh heartbeat. Without one, the runner monitor's sweep marks it
// offline, and other packages' tests run that sweep over the same database at any time.
heartbeat := time.Now()
launcher := &models.Runner{ID: uuid.New(), Kind: models.RunnerKindHosted, HostedGroup: group, Name: "hostedcap-l-" + f.sfx, Status: models.RunnerStatusOnline, LastHeartbeatAt: &heartbeat}
for _, obj := range []any{pool, proj, ws, launcher} {
if err := f.db.Create(obj).Error; err != nil {
t.Fatal(err)
Expand All @@ -56,6 +61,11 @@ func TestHostedCapacity_ReadByMembers(t *testing.T) {
f.db.Where("id = ?", pool.ID).Delete(&models.AgentPool{})
})

// The sweep another package's test may run meanwhile leaves the launcher online.
if _, err := repository.NewRunnerRepository(f.db).MarkOfflineIfStale(runner.OfflineAfter); err != nil {
t.Fatalf("sweeping stale runners: %v", err)
}

h := NewHostedCapacityHandler(repository.NewOrganizationRepository(f.db), repository.NewAgentPoolRepository(f.db), repository.NewRunRepository(f.db), f.authSvc,
rbac.NewServiceWithTeams(repository.NewOrganizationRepository(f.db), repository.NewTeamRepository(f.db), repository.NewProjectRepository(f.db)))
r := platformAdminRouter()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@ func TestInventorySyncSource_WebhookForAnEditedSourceQueuesNothing(t *testing.T)
}
})
})
h.requestInventorySync(inv)
if h.requestInventorySync(inv) {
t.Error("the delivery counted an inventory whose source changed")
}
if status, syncErr, n := f.webhookState(t, inv.ID); status != "completed" || syncErr != "" || n != 0 {
t.Errorf("a webhook for the former source: status %q error %q, %d active; want nothing queued or written", status, syncErr, n)
}
Expand Down Expand Up @@ -171,3 +173,23 @@ func TestInventorySyncSource_EditTakesTheSyncLockFirst(t *testing.T) {
holder.Rollback()
<-done
}

// A source edit that commits while an artifacts request waits for its clone token leaves that request
// without clone inputs or credential.
func TestInventorySyncSource_EditWhileTheTokenIsFetched(t *testing.T) {
f := setupWorkItemRunner(t)
g, conn := f.githubApp(t)
inv, item := f.syncOnPoolA(t, conn.ID, "srcedit-token")
g.beforeAnswer = func() {
g.beforeAnswer = nil
f.editSource(t, inv.ID, "acme/replaced-"+uuid.NewString()[:6])
}
rec, art := f.artifacts(t, "srcedit-token", item.ID)
if len(g.requests()) != 1 {
t.Fatalf("GitHub received %d token requests, want the one the edit interrupted", len(g.requests()))
}
if rec.Code == http.StatusOK || art.Clone != nil || strings.Contains(rec.Body.String(), "ghs_narrowed") {
t.Errorf("artifacts of a sync canceled while its token was fetched = %d %s, want no clone inputs and no credential", rec.Code, rec.Body.String())
}
f.wantCanceledBySourceEdit(t, item.ID)
}
30 changes: 22 additions & 8 deletions backend/internal/api/v2/handlers/runner_agent_work_items.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,19 @@ func (h *RunnerAgentHandler) getWorkItemArtifacts(c *gin.Context, id string) {
c.JSON(http.StatusOK, art)
}

// stillRunning reads the work item again and refuses one that finished meanwhile, as a cancellation
// finishes it, with ansible.ErrInvalidInput and its reason.
func (h *RunnerAgentHandler) stillRunning(ctx context.Context, id string) error {
current, err := h.workItems.WithContext(ctx).Items().GetByID(id)
if err != nil {
return fmt.Errorf("reading work item %s: %w", id, err)
}
if current.Finished() {
return fmt.Errorf("%s: %w", current.ErrorMessage, ansible.ErrInvalidInput)
}
return nil
}

// workItemArtifacts builds what the sync executor needs for a work item.
func (h *RunnerAgentHandler) workItemArtifacts(ctx context.Context, item *models.WorkItem) (*runnercontract.WorkItemArtifacts, error) {
art := &runnercontract.WorkItemArtifacts{
Expand Down Expand Up @@ -159,19 +172,20 @@ func (h *RunnerAgentHandler) workItemArtifacts(ctx context.Context, item *models
if err := validatedInventoryScope(item, &inventory); err != nil {
return nil, err
}
// An edit of the inventory's source cancels its syncs: one canceled before the row above was
// read gets none of the new source's inputs.
current, err := h.workItems.WithContext(ctx).Items().GetByID(item.ID)
if err != nil {
return nil, fmt.Errorf("reading work item %s: %w", item.ID, err)
}
if current.Finished() {
return nil, fmt.Errorf("%s: %w", current.ErrorMessage, ansible.ErrInvalidInput)
// An edit of the inventory's source cancels its syncs. The work item is read again after the
// row above, so a sync canceled before that read gets none of the new source's inputs, and once
// more after the token is fetched, with no lock held meanwhile, so one canceled while the token
// was fetched gets no credential either.
if err := h.stillRunning(ctx, item.ID); err != nil {
return nil, err
}
clone, err := h.fileSyncCloneSource(ctx, item, &inventory)
if err != nil {
return nil, err
}
if err := h.stillRunning(ctx, item.ID); err != nil {
return nil, err
}
art.Clone, art.InventoryPath = clone, inventory.InventoryPath
art.AzureSubscriptionID, err = h.orgAzureSubscription(item.OrganizationID)
if err != nil {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ type fakeTokenGitHub struct {
// the account acme, and "absent" leaves the list out.
repositories string
bodies []map[string]any
// beforeAnswer, when set, runs while a token request waits for its answer.
beforeAnswer func()
}

func (g *fakeTokenGitHub) serve(w http.ResponseWriter, r *http.Request) {
Expand All @@ -53,8 +55,11 @@ func (g *fakeTokenGitHub) serve(w http.ResponseWriter, r *http.Request) {
_ = json.Unmarshal(raw, &body)
g.mu.Lock()
g.bodies = append(g.bodies, body)
status, list, minted := g.status, g.repositories, len(g.bodies)
status, list, minted, hook := g.status, g.repositories, len(g.bodies), g.beforeAnswer
g.mu.Unlock()
if hook != nil {
hook()
}
if status == 0 {
status = http.StatusCreated
}
Expand Down
24 changes: 16 additions & 8 deletions backend/internal/api/v2/handlers/vcs_app_installation.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,21 +168,24 @@ var webhookSyncTimeout = 30 * time.Second
// refused or failed file sync request is recorded on the inventory unless a file sync of it is
// waiting or running; a request whose wait timed out writes nothing (#1113, D2). The request is for the
// source the delivery matched inv by: an inventory whose source changed since gets no sync and no
// record.
func (h *VCSAppInstallationHandlerV2) requestInventorySync(inv *models.AnsibleInventory) {
// record, and requestInventorySync reports false so the delivery does not count it.
func (h *VCSAppInstallationHandlerV2) requestInventorySync(inv *models.AnsibleInventory) bool {
if h.workItems == nil {
return
return true
}
ctx, cancel := context.WithTimeout(context.Background(), webhookSyncTimeout)
defer cancel()
source := coreansible.SourceOf(inv)
_, err := h.workItems.RequestInventorySyncOf(ctx, inv, "webhook", source)
if err == nil || errors.Is(err, coreansible.ErrSyncSourceChanged) {
return
if errors.Is(err, coreansible.ErrSyncSourceChanged) {
return false
}
if err == nil {
return true
}
logger.Errorf("Error requesting a sync of inventory %s: %v", inv.ID, err)
if inv.Type == models.InventoryTypeConstructed || ctx.Err() != nil {
return
return true
}
reason, refused := coreansible.FileSyncRefusal(err)
if !refused {
Expand All @@ -193,6 +196,7 @@ func (h *VCSAppInstallationHandlerV2) requestInventorySync(inv *models.AnsibleIn
if recErr := h.workItems.RecordFileSyncFailure(recordCtx, inv.ID, reason, coreansible.WebhookSyncFailure, source); recErr != nil {
logger.Errorf("Error recording the refused sync of inventory %s: %v", inv.ID, recErr)
}
return true
}

// requestPlaybookSync requests the webhook-triggered snapshot of a playbook as a work item.
Expand Down Expand Up @@ -502,9 +506,11 @@ func (h *VCSAppInstallationHandlerV2) handleAzureDevOpsPushEvent(c *gin.Context,
continue
}
inv := inventory
if !h.requestInventorySync(&inv) {
continue
}
syncedInventories++
attribution.tally(reached, inv.VCSConnectionID).inventories++
h.requestInventorySync(&inv)
}
if h.playbookRepo != nil {
playbooks, _ := h.playbookRepo.ListByVCSRepositoryAndBranch(wp.Repository, branchName)
Expand Down Expand Up @@ -1368,9 +1374,11 @@ func (h *VCSAppInstallationHandlerV2) syncAnsibleOnGitHubPush(repositoryFullName
continue
}
logger.Infof("Triggering sync for inventory: %s (ID: %s)", inventory.Name, inventory.ID)
if !h.requestInventorySync(&inventory) {
continue
}
syncedInventories++
attribution.tally(reached, inventory.VCSConnectionID).inventories++
h.requestInventorySync(&inventory)
}

if h.playbookRepo == nil {
Expand Down
Loading