Skip to content

Commit

Permalink
registry: add heartbeat call for running builds
Browse files Browse the repository at this point in the history
When a build is running, we send periodic heartbeats to HCP Packer's
API.

This will be used on the service side to detect if a build is stalled on
the core side because of a crash or any other malfunction that caused
Packer not to send an update on the status of a build.
  • Loading branch information
lbajolet-hashicorp committed Jun 10, 2022
1 parent 1e316c9 commit 311b88a
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions packer/registry_builder.go
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log"
"time"

"github.com/hashicorp/hcp-sdk-go/clients/cloud-packer-service/stable/2021-04-30/models"
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
Expand All @@ -12,6 +13,10 @@ import (
"github.com/mitchellh/mapstructure"
)

// HeartbeatPeriod dictates how often a heartbeat is sent to HCP to signal a
// build is still alive.
const HeartbeatPeriod = 2 * time.Minute

type RegistryBuilder struct {
Name string
ArtifactMetadataPublisher *packerregistry.Bucket
Expand Down Expand Up @@ -50,6 +55,31 @@ func (b *RegistryBuilder) Run(ctx context.Context, ui packersdk.Ui, hook packers
log.Printf("[TRACE] failed to update HCP Packer registry status for %q: %s", b.Name, err)
}

go func() {
log.Printf("[TRACE] starting heartbeats for %q", b.Name)

tick := time.NewTicker(HeartbeatPeriod)

for {
select {
case <-ctx.Done():
tick.Stop()
return
case <-tick.C:
err := b.ArtifactMetadataPublisher.UpdateBuildStatus(
ctx,
b.Name,
models.HashicorpCloudPackerBuildStatusRUNNING,
)
if err != nil {
log.Printf("[ERROR] failed to send heartbeat for build %q: %s", b.Name, err)
} else {
log.Printf("[TRACE] sent heartbeat for %q", b.Name)
}
}
}
}()

ui.Say(fmt.Sprintf("Publishing build details for %s to the HCP Packer registry", b.Name))
artifact, err := b.Builder.Run(ctx, ui, hook)
if err != nil {
Expand Down

0 comments on commit 311b88a

Please sign in to comment.