package pxe import ( "context" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "edge-infra.dev/pkg/k8s/decoder" "edge-infra.dev/pkg/k8s/runtime/inventory" "edge-infra.dev/pkg/k8s/runtime/sap" "edge-infra.dev/pkg/k8s/unstructured" "edge-infra.dev/pkg/lib/fog" v1pxe "edge-infra.dev/pkg/sds/ien/k8s/controllers/pxe/apis/v1" "edge-infra.dev/pkg/sds/ien/k8s/controllers/pxe/common" ) type pxeManager struct { resourceManager *sap.ResourceManager pxe *v1pxe.PXE } // newPXEManager returns a pxeManager configured with the provided resource // manager to manage the provided pxe resource func newPXEManager(mgr *sap.ResourceManager, pxe *v1pxe.PXE) pxeManager { return pxeManager{ mgr, pxe, } } // apply will use server-side apply to apply the provided manifests to the API // server using the resource manager. When the resources have been applied, the // changeset is compared to the previous inventory for the PXE resource. Any // resources that are found in the inventory that are not in the changeset are // pruned func (m *pxeManager) apply(ctx context.Context, manifests ...[]byte) error { var toApply []*unstructured.Unstructured for _, m := range manifests { uobjs, err := decoder.DecodeYAML(m) if err != nil { return err } toApply = append(toApply, uobjs...) } changeSet, err := m.resourceManager.ApplyAll(ctx, toApply, sap.ApplyOptions{}) if err != nil { return err } fog.FromContext(ctx).Info("applied objects", "changeset", changeSet.ToMap()) // create new inventory and use this to prune the old one inv := inventory.New(inventory.FromSapChangeSet(changeSet)) return m.prune(ctx, inv) } // prune will use server-side apply to delete resources that were in the old PXE // inventory but do not appear in the provided new inventory. The inventory // is updated to reflect the new set of resources managed by the PXE instance func (m *pxeManager) prune(ctx context.Context, newInv *inventory.ResourceInventory) (err error) { defer func() { if err == nil { m.pxe.SetInventory(newInv) } }() if m.pxe.GetInventory() == nil { return nil } // find resources that don't exist in new inventory diff, err := inventory.Diff(m.pxe.GetInventory(), newInv) if err != nil { return err } if len(diff) <= 0 { return nil } opts := sap.DeleteOptions{ PropagationPolicy: metav1.DeletePropagationBackground, // only include resources that were created and are managed by PXE controller Inclusions: managedByPXEController(), Exclusions: nil, } changeSet, err := m.resourceManager.DeleteAll(ctx, diff, opts) if err != nil { return err } fog.FromContext(ctx).Info("pruned objects", "changeset", changeSet.ToMap()) return nil } // managedByPXEController returns a label map for resources managed by the PXE // controller func managedByPXEController() map[string]string { return map[string]string{ common.KubernetesManagerByLabel: common.PXEControllerName, } }