bonny icon indicating copy to clipboard operation
bonny copied to clipboard

Automatically inject ownerReferences

Open coryodaniel opened this issue 5 years ago • 3 comments

Inject metadata.ownerReferences into resources.

I'm not positive the original idea below will work. Middleware is per cluster and it would need a per resource data to inject ownerReference.

Definitely worth looking into, but a simple solution for now could be to add an add_owner_references/2 function to the Controller behavior.

def added(todo = %{}) do
  %K8s.Operation{} # make an operation
  |> add_owner_references(todo) # attached `todo` crd references
  |> K8s.run(conn)
end
apiVersion: v1
kind: Pod
metadata:
  ...
  ownerReferences:
  - apiVersion: apps/v1
    controller: true
    blockOwnerDeletion: true
    kind: ReplicaSet
    name: my-repset
    uid: d9607e19-f88f-11e6-a518-42010a800195
  ...

original idea

This will require

  • [x] K8s.Middleware to modify all JSON paylaods during a lifecycle event
  • [ ] Ensure lifecycle events are dispatched in their own process
  • [ ] Store custom resource's information by process ID so that it can be fetched by middleware
  • [ ] default implementation to make the delete lifecycle a no-op as deletion should happen via k8s/ownerReferences garbage collection

Related #79

coryodaniel avatar Apr 24 '19 14:04 coryodaniel

I actually implemented something like that:

    K8s.Resource.build("v1", "ServiceAccount", namespace, name)
    |> MyProject.Resource.add_owner_references(added_resource)
    |> K8s.Client.create()
    |> K8s.Client.run(cluster_name)

with

defmodule MyProject.Resource do

  def add_owner_references(resource, owner) do
    put_in(resource, ["metadata", "ownerReferences"], [owner_reference(owner)])
  end

  def owner_reference(resource) do
    %{
      "apiVersion" => get_in(resource, ["apiVersion"]),
      "kind"       => get_in(resource, ["kind"]),
      "name"       => get_in(resource, ["metadata", "name"]),
      "uid"        => get_in(resource, ["metadata", "uid"]),
      # foreground deletion => true
      # background deletion => false
      "blockOwnerDeletion" => false,
      # seems to work without too, but internet says we should add it ...
      "controller" => true,
    }
  end

end

(in case someone comes across this issue and is looking for inspiration)

@coryodaniel does this look like what you had in mind?

jlgeering avatar Apr 05 '20 04:04 jlgeering

Yeah! I think two similar controller methods would be good and accept a map (instead of a K8s.Operation.t).

I think that the added event map might have the uid of the Custom Resource.

coryodaniel avatar Apr 05 '20 17:04 coryodaniel

Maybe accept optional params to toggle foreground/background and block owner deletion

coryodaniel avatar Apr 05 '20 17:04 coryodaniel