Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 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
12 changes: 12 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,18 @@ when adding or removing one.
`deployment_group:toggle_delta_updates`, as it does in the API, and saving
drops the field for a member without it). There's no Devices tab: the header's device count links to the
devices list, filtered to the group.
Anything done to a release (creating or editing one, approving, skipping or
retrying its workflow step, retrying or deleting its deltas), on these pages,
the firmware and archive pages, Slack or the API, needs
`deployment_group:release:manage`, and so does creating a group, which starts
with a release. `deployment_group:update` is the group's own settings.
Queueing a release's deltas runs a transaction of its own, so it happens after
the release's commits: a failed nested `Repo.transact` rolls back the outer
Comment thread
joshk marked this conversation as resolved.
Resolved
one too, even when its result is ignored. So a release that will queue deltas
starts `:preparing` (`DeploymentRelease.hold_for_deltas/2`) until the
recalculation after the queueing settles it, and the group's orchestrator
settles any left behind on its two-minute tick
(`ManagedDeployments.settle_delta_statuses/1`).
A product's settings are three LiveViews, General (`live/product/settings.ex`),
Device health (`live/product/health_profiles.ex`) and API keys
(`live/product/api_keys.ex`), sharing their title and tabs from
Expand Down
9 changes: 7 additions & 2 deletions lib/nerves_hub/accounts/permissions.ex
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,13 @@ defmodule NervesHub.Accounts.Permissions do
]},
{"Deployment groups",
[
{:"deployment_group:create", :manage, :optional, "Create deployment groups"},
{:"deployment_group:update", :manage, :optional, "Edit deployment groups and their releases"},
# A group starts with a release, so creating one takes
# `deployment_group:release:manage` as well.
{:"deployment_group:create", :manage, :optional, "Create deployment groups, along with managing releases"},
Comment thread
joshk marked this conversation as resolved.
Resolved
{:"deployment_group:update", :manage, :optional, "Edit deployment group settings"},
# A release is what sends firmware to the group's devices, so making and
# moving one on is kept apart from changing how the group is set up.
{:"deployment_group:release:manage", :manage, :optional, "Create, edit and approve releases"},
{:"deployment_group:toggle", :manage, :optional, "Turn deployment groups on or off"},
{:"deployment_group:toggle_delta_updates", :manage, :optional, "Turn delta updates on or off"},
{:"deployment_group:delete", :manage, :optional, "Delete deployment groups"}
Expand Down
117 changes: 86 additions & 31 deletions lib/nerves_hub/managed_deployments.ex
Original file line number Diff line number Diff line change
Expand Up @@ -345,17 +345,21 @@ defmodule NervesHub.ManagedDeployments do
Repo.transact(fn ->
with {:ok, deployment_group} <- Repo.update(changeset),
:ok <- create_audit_logs!(deployment_group, changeset) do
{:ok, _} = maybe_trigger_delta_generation(deployment_group, changeset)

deployment_group = load_current_release(deployment_group, force: true)

{:ok, _releases} = recalculate_release_delta_statuses(deployment_group)

{:ok, deployment_group}
end
end)
|> case do
{:ok, deployment_group} ->
# After the commit, as in `create_deployment_release/6`: queueing a
# delta runs a transaction of its own, and one that fails would undo
# the change, turning delta updates on included. A delta that can't be
# queued says so in the log and in Sentry, and its devices are sent
# the whole firmware. Before the broadcast, so the orchestrator sees
# the releases waiting on the deltas that were queued.
Comment thread
joshk marked this conversation as resolved.
Resolved
_ = maybe_trigger_delta_generation(deployment_group, changeset)
{:ok, _releases} = recalculate_release_delta_statuses(deployment_group)
deployment_group = load_current_release(deployment_group, force: true)

:ok = broadcast(deployment_group, "deployments/update")

if Map.has_key?(changeset.changes, :is_active) do
Expand Down Expand Up @@ -402,17 +406,23 @@ defmodule NervesHub.ManagedDeployments do
:ok <- WorkflowEvents.release_replaced(previous_release_id, release),
{:ok, deployment_group} = recalculate_current_release(deployment_group),
deployment_group = load_current_release(deployment_group, force: true),
:ok <- maybe_audit_new_deployment_release(actor, deployment_group, opts),
{:ok, _} <- maybe_trigger_delta_generation(deployment_group, release),
{:ok, release} <- recalculate_release_delta_status(release) do
:ok <- maybe_audit_new_deployment_release(actor, deployment_group, opts) do
{:ok, {release, deployment_group}}
else
{:error, _} = error -> error
{:update_deployment, _} -> {:error, "could not update deployment group current release information"}
end
end)
|> case do
{:ok, {_release, deployment_group}} = result ->
{:ok, {release, deployment_group}} ->
# After the commit, because queueing a delta runs a transaction of its
# own, and one that fails would take the release down with it. A delta
# that can't be queued says so in the log and in Sentry, and its devices
# are sent the whole firmware. Before the broadcast, so the orchestrator
# sees the release waiting on the deltas that were queued.
Comment thread
joshk marked this conversation as resolved.
Resolved
_ = maybe_trigger_delta_generation(deployment_group, release)
{:ok, release} = recalculate_release_delta_status(release)
Comment thread
joshk marked this conversation as resolved.
Resolved

if Keyword.get(opts, :broadcast, true) do
:ok = broadcast(deployment_group, "deployments/update")
end
Expand All @@ -424,7 +434,7 @@ defmodule NervesHub.ManagedDeployments do
broadcast(deployment_group, "archives/updated", %{archive_id: archive.id})
end

result
{:ok, {release, deployment_group}}

error ->
error
Expand Down Expand Up @@ -484,6 +494,25 @@ defmodule NervesHub.ManagedDeployments do
|> recalculate_delta_statuses()
end

@doc """
Recalculate every release of a deployment group that reads `:preparing`.

A release starts `:preparing` when saving it queues deltas
(`DeploymentRelease.hold_for_deltas/2`), and the recalculation after the
queueing settles it. One whose recalculation never ran, because the node
went down between the two, would hold its devices back for good, so the
group's orchestrator calls this on its two-minute tick. A release whose
deltas are still building stays `:preparing`, and one no device is headed
for becomes `:ready`.
"""
@spec settle_delta_statuses(DeploymentGroup.t()) :: {:ok, [DeploymentRelease.t()]}
def settle_delta_statuses(%DeploymentGroup{id: deployment_group_id}) do
DeploymentRelease
|> where([r], r.deployment_group_id == ^deployment_group_id and r.delta_status == :preparing)
|> Repo.all()
|> recalculate_delta_statuses()
end
Comment thread
joshk marked this conversation as resolved.
Resolved

@doc """
The firmware a deployment group's devices are headed for.

Expand Down Expand Up @@ -971,47 +1000,52 @@ defmodule NervesHub.ManagedDeployments do
next, so the deltas those devices need are queued, the group's status is
recalculated against them, and the orchestrator is told to look again. A new
connecting code reaches devices the next time they connect.

`actor` is who made the change, a user or a product API key, and is who the
audit log names.
"""
@spec update_deployment_release(DeploymentRelease.t(), map(), User.t()) ::
@spec update_deployment_release(DeploymentRelease.t(), map(), AuditLogs.actor()) ::
{:ok, DeploymentRelease.t()} | {:error, Changeset.t() | :not_found}
def update_deployment_release(%DeploymentRelease{} = release, params, %User{} = user) do
def update_deployment_release(%DeploymentRelease{} = release, params, actor)
when is_struct(actor, User) or is_struct(actor, ApiKey) do
release
|> DeploymentRelease.edit_changeset(params)
|> save_release_changes(user)
|> save_release_changes(actor)
end

defp save_release_changes(%Changeset{} = changeset, user) do
defp save_release_changes(%Changeset{} = changeset, actor) do
required_changed? = Changeset.changed?(changeset, :required)

code_changed? =
Changeset.changed?(changeset, :connecting_code) or Changeset.changed?(changeset, :connecting_code_mode)

Repo.transact(fn ->
with {:ok, release} <- Repo.update(changeset),
{:ok, deployment_group} <- get_deployment_group(release.deployment_group_id) do
with {:ok, deployment_group} <- get_deployment_group(changeset.data.deployment_group_id),
{:ok, release} <- changeset |> DeploymentRelease.hold_for_deltas(deployment_group) |> Repo.update() do
if required_changed? do
:ok = DeploymentGroupTemplates.audit_release_required_changed(user, deployment_group, release)

# Queueing the deltas can fail on its own, and says so in the log and in
# Sentry. The release is still required either way, devices that have no
# delta are sent the whole firmware, and the group's status below reports
# whatever the deltas did.
_ = maybe_trigger_delta_generation(deployment_group, release)

{:ok, _releases} = recalculate_release_delta_statuses(deployment_group)
:ok
:ok = DeploymentGroupTemplates.audit_release_required_changed(actor, deployment_group, release)
end

if code_changed? do
:ok = DeploymentGroupTemplates.audit_release_connecting_code_changed(user, deployment_group, release)
:ok = DeploymentGroupTemplates.audit_release_connecting_code_changed(actor, deployment_group, release)
end

{:ok, {release, deployment_group}}
end
end)
|> case do
{:ok, {release, deployment_group}} ->
if required_changed?, do: :ok = broadcast(deployment_group, "deployments/update")
if required_changed? do
# After the commit, as in `create_deployment_release/6`: queueing a
# delta runs a transaction of its own, and one that fails would undo
# the change. The release is required either way, devices with no
# delta are sent the whole firmware, and the statuses report whatever
# the deltas did.
Comment thread
joshk marked this conversation as resolved.
Resolved
_ = maybe_trigger_delta_generation(deployment_group, release)
{:ok, _releases} = recalculate_release_delta_statuses(deployment_group)
:ok = broadcast(deployment_group, "deployments/update")
end

{:ok, release}

{:error, _} = error ->
Expand All @@ -1024,13 +1058,34 @@ defmodule NervesHub.ManagedDeployments do
"""
@spec list_deployment_releases(DeploymentGroup.t()) :: [DeploymentRelease.t()]
def list_deployment_releases(%DeploymentGroup{id: deployment_group_id}) do
deployment_group_id
|> releases_query()
|> order_by([r], desc: r.inserted_at, desc: r.id)
|> Repo.all()
end

@doc """
Fetches a deployment group's release by its number, which counts up from 1
within the group.

Preloads the authors, the archive, and the firmware with who deleted it, the
same as `list_deployment_releases/1`.
"""
Comment thread
joshk marked this conversation as resolved.
Resolved
@spec get_deployment_release_by_number(DeploymentGroup.t(), integer()) ::
{:ok, DeploymentRelease.t()} | {:error, :not_found}
def get_deployment_release_by_number(%DeploymentGroup{id: deployment_group_id}, number) when is_integer(number) do
deployment_group_id
|> releases_query()
|> where([r], r.number == ^number)
|> Repo.fetch()
end

defp releases_query(deployment_group_id) do
DeploymentRelease
|> where([r], r.deployment_group_id == ^deployment_group_id)
|> order_by([r], desc: r.inserted_at, desc: r.id)
# `deleted_by` because release history outlives the firmware it names: a
# deleted release firmware is badged with who retired it.
|> preload([:created_by, :created_by_api_key, :archive, firmware: :deleted_by])
|> Repo.all()
end

@spec broadcast(DeploymentGroup.t() | atom(), String.t(), map()) :: :ok | {:error, term()}
Expand Down
58 changes: 55 additions & 3 deletions lib/nerves_hub/managed_deployments/deployment_release.ex
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,35 @@ defmodule NervesHub.ManagedDeployments.DeploymentRelease do
timestamps()
end

# What a release takes from params when it's made. Its firmware and archive
# are given to `new_changeset/5` already found, and with the description and
# notes they're fixed from then on.
@create_fields [:description, :notes, :required, :connecting_code, :connecting_code_mode]

# What can still change once it's made, through `edit_changeset/2`.
@edit_fields [:required, :connecting_code, :connecting_code_mode]

@doc """
A changeset for a new release of `deployment_group`, numbered after its last.

`firmware` and `archive` come already loaded. From `params` it takes the
description, notes, whether it's required, and the connecting code and where
that runs, and ignores anything else there. It's refused if the firmware and
archive are the same as the current release's.

Inserting it doesn't make it the group's current release:
`NervesHub.ManagedDeployments.create_deployment_release/6` does that. The
Releases tab also builds one only to check a form's input.

In a group that's on with delta updates on, it starts `:preparing`, as
`hold_for_deltas/2` says.
"""
Comment thread
joshk marked this conversation as resolved.
Resolved
@spec new_changeset(DeploymentGroup.t(), Firmware.t() | nil, Archive.t() | nil, map(), User.t() | ApiKey.t() | nil) ::
Ecto.Changeset.t()
def new_changeset(deployment_group, firmware \\ nil, archive \\ nil, params \\ %{}, created_by \\ nil) do
change(%__MODULE__{})
|> cast(params, [:description, :notes, :required, :connecting_code, :connecting_code_mode])
|> cast(params, @create_fields)
|> hold_for_deltas(deployment_group)
|> put_assoc(:deployment_group, deployment_group)
|> put_assoc(:firmware, firmware)
|> put_assoc(:archive, archive)
Expand All @@ -63,7 +89,8 @@ defmodule NervesHub.ManagedDeployments.DeploymentRelease do
|> put_change(:number, 1)
|> validate_length(:description, max: 100)
|> validate_length(:notes, max: 1_000)
|> validate_required([:firmware])
# A `null` in a request is cast over the defaults, and the columns refuse it.
|> validate_required([:firmware, :required, :connecting_code_mode])
|> validate_firmware(deployment_group)
|> validate_differs_from_current_release(deployment_group)
|> validate_created_by_api_key(deployment_group.product_id)
Expand All @@ -89,6 +116,31 @@ defmodule NervesHub.ManagedDeployments.DeploymentRelease do
end)
end

@doc """
Holds a release's devices back until its deltas are queued, when saving
`changeset` will queue some: a new release, or one just marked required, in a
group that's on with delta updates on.

The deltas are queued after the release commits, since queueing runs a
transaction of its own. Until then nothing has been queued for the release to
wait on, and a release reading `:ready` would be sent as whole firmware. So it
reads `:preparing`, and the recalculation that follows the queueing settles
it. If that never runs, the deployment group's orchestrator settles it on its
next tick (`NervesHub.ManagedDeployments.settle_delta_statuses/1`).
"""
Comment thread
joshk marked this conversation as resolved.
Resolved
@spec hold_for_deltas(Ecto.Changeset.t(), DeploymentGroup.t()) :: Ecto.Changeset.t()
def hold_for_deltas(changeset, %DeploymentGroup{is_active: true, delta_updatable: true}) do
new? = is_nil(changeset.data.id)

if new? or get_change(changeset, :required) == true do
put_change(changeset, :delta_status, :preparing)
else
changeset
end
end

def hold_for_deltas(changeset, _deployment_group), do: changeset

@doc """
Record whether the deltas this release's devices need are ready.
"""
Expand All @@ -109,7 +161,7 @@ defmodule NervesHub.ManagedDeployments.DeploymentRelease do
@spec edit_changeset(t(), map()) :: Ecto.Changeset.t()
def edit_changeset(%__MODULE__{} = release, params) do
release
|> cast(params, [:required, :connecting_code, :connecting_code_mode])
|> cast(params, @edit_fields)
|> validate_required([:required, :connecting_code_mode])
end

Expand Down
10 changes: 10 additions & 0 deletions lib/nerves_hub/managed_deployments/orchestrator.ex
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,14 @@ defmodule NervesHub.ManagedDeployments.Orchestrator do
{:ok, state}
end

# A release left reading `:preparing` holds its devices back, so the backup
# tick settles any whose recalculation never ran. One that changes is
# broadcast as `release/delta_status`, which triggers an update here.
defp settle_delta_statuses(state) do
{:ok, _releases} = ManagedDeployments.settle_delta_statuses(state.deployment_group)
:ok
end
Comment thread
joshk marked this conversation as resolved.
Resolved

def terminate(reason, state) do
Logger.info("Orchestrator terminated",
deployment_id: state.deployment_group.id,
Expand Down Expand Up @@ -153,13 +161,15 @@ defmodule NervesHub.ManagedDeployments.Orchestrator do

# if we don't have a `timer_ref` we can run `trigger_update`
def handle_info(:trigger_interval, %State{timer_ref: nil} = state) do
:ok = settle_delta_statuses(state)
deployment_group = trigger_update(state)

{:noreply, %{state | deployment_group: deployment_group}}
end

# we can ignore `trigger_interval` since we have a `timer_ref`
def handle_info(:trigger_interval, state) do
:ok = settle_delta_statuses(state)
{:noreply, state}
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ defmodule NervesHubWeb.Components.DeploymentGroupPage.Overview do
<DeploymentGroups.held_sentence entry={@entry} />
</p>
</div>
<.button :if={authorized?(:"deployment_group:update", @current_scope)} style="primary" size="sm" phx-click="approve" class="shrink-0">
<.button :if={authorized?(:"deployment_group:release:manage", @current_scope)} style="primary" size="sm" phx-click="approve" class="shrink-0">
<span class="lucide-check" aria-hidden="true"></span> Approve and continue
</.button>
</div>
Expand All @@ -86,7 +86,7 @@ defmodule NervesHubWeb.Components.DeploymentGroupPage.Overview do
<DeploymentGroups.held_sentence entry={@entry} />
</p>
</div>
<div :if={authorized?(:"deployment_group:update", @current_scope)} class="flex shrink-0 gap-2 max-sm:*:flex-1 max-sm:*:justify-center">
<div :if={authorized?(:"deployment_group:release:manage", @current_scope)} class="flex shrink-0 gap-2 max-sm:*:flex-1 max-sm:*:justify-center">
<.button size="sm" phx-click="skip">Skip step</.button>
<.button style="primary" size="sm" phx-click="retry">
<span class="lucide-rotate-ccw" aria-hidden="true"></span> Retry step
Expand Down
Loading
Loading