Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 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
10 changes: 8 additions & 2 deletions lib/nerves_hub/accounts/permissions.ex
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,14 @@ 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 (also needs Create, edit and approve releases)"},
{:"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
161 changes: 130 additions & 31 deletions lib/nerves_hub/managed_deployments.ex
Original file line number Diff line number Diff line change
Expand Up @@ -345,17 +345,24 @@ 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
_ =
queue_deltas_after_commit(deployment_group, changeset, fn ->
recalculate_release_delta_statuses(deployment_group)
end)

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 +409,28 @@ 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
release =
deployment_group
|> queue_deltas_after_commit(release, fn -> recalculate_release_delta_status(release) end)
|> case do
{:ok, recalculated} -> recalculated
_ -> release
end

if Keyword.get(opts, :broadcast, true) do
:ok = broadcast(deployment_group, "deployments/update")
end
Expand All @@ -424,7 +442,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 +502,30 @@ 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`.

A release changed in the last minute is left for the next tick. It may be
one whose deltas are being queued right now, and settling it before they are
would find nothing to wait for and send its devices whole firmware.
"""
@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)
|> where([r], r.updated_at < ago(1, "minute"))
|> 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 @@ -719,6 +761,34 @@ defmodule NervesHub.ManagedDeployments do

defp maybe_trigger_delta_generation(_deployment_group, _changeset), do: {:ok, :no_deltas_started}

# Queues the deltas a change asks for, then records what they did with
# `recalculate`, once the change has committed. Both run outside the
# transaction, so a failure in either can't undo the change, and it mustn't
# stop the caller either: the broadcast after this is what tells the group's
# orchestrator about the change, and without it the orchestrator keeps
# working from the group as it was. So a raise is logged and reported, and
# `:error` returned. A release left `:preparing` by it is settled on the
# orchestrator's next tick (`settle_delta_statuses/1`), and devices with no
# delta are sent the whole firmware.
defp queue_deltas_after_commit(deployment_group, subject, recalculate) do
_ = maybe_trigger_delta_generation(deployment_group, subject)
recalculate.()
rescue
exception ->
Logger.error("Could not queue a deployment group's deltas: " <> Exception.message(exception),
deployment_id: deployment_group.id
)

_ =
Sentry.capture_exception(exception,
stacktrace: __STACKTRACE__,
tags: %{deployment_id: deployment_group.id},
result: :none
)

:error
end

@spec trigger_delta_generation_for_deployment_group(DeploymentGroup.t()) ::
{:ok, :deltas_started | :deltas_already_generated | :some_deltas_started | :no_delta_support}
| {:error, :deltas_not_enabled | :delta_generation_failed}
Expand Down Expand Up @@ -971,47 +1041,55 @@ 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
_ =
queue_deltas_after_commit(deployment_group, release, fn ->
recalculate_release_delta_statuses(deployment_group)
end)

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

{:ok, release}

{:error, _} = error ->
Expand All @@ -1024,13 +1102,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
59 changes: 56 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,32 @@ defmodule NervesHub.ManagedDeployments.DeploymentRelease do
end)
end

@doc """
Sets `delta_status` to `:preparing` when saving `changeset` will queue deltas.

That is a new release, or one just marked required, in a group that's on with
delta updates on. Any other changeset is returned unchanged.

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. 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 +162,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
Loading
Loading