### Install Reflector Chart from Helm Repository Source: https://github.com/emberstack/kubernetes-reflector/blob/main/README.md Add the Helm repository, update it, and then upgrade or install the Reflector chart. ```shell helm repo add emberstack https://emberstack.github.io/helm-charts helm repo update helm upgrade --install reflector emberstack/reflector ``` -------------------------------- ### ConfigMap Mirroring Example Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/configmap-mirror.md An example showing how text and binary data are mirrored from a source ConfigMap to a target namespace. ```yaml Source ConfigMap in 'default' namespace: data: config.yaml: | key: value binaryData: cert.pem: Mirror in 'team-a' namespace: data: config.yaml: | key: value binaryData: cert.pem: (identical) ``` -------------------------------- ### Complete Mirroring Workflow Example Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/mirroring-properties.md Demonstrates extracting configuration, checking reflection eligibility, and validating label selectors. ```csharp using ES.Kubernetes.Reflector.Mirroring.Core; using k8s; using k8s.Models; // Extract mirroring configuration from a source resource var sourceSecret = await k8s.CoreV1.ReadNamespacedSecretAsync("app-secrets", "default"); var sourceProps = sourceSecret.GetMirroringProperties(); // Check reflection eligibility if (!sourceProps.Allowed) { Console.WriteLine("Reflection not enabled on source"); return; } // Get all namespaces var namespaces = await k8s.CoreV1.ListNamespaceAsync(); // Find eligible reflection targets foreach (var ns in namespaces.Items) { // Check basic pattern match if (sourceProps.CanBeReflectedToNamespace(ns)) { Console.WriteLine($"Can reflect to {ns.Name()}"); // Check auto-reflection eligibility if (sourceProps.CanBeAutoReflectedToNamespace(ns)) { Console.WriteLine($" - Will auto-create mirror in {ns.Name()}"); } } } // Validate selectors var selectorErrors = sourceProps.GetLabelSelectorErrors(); if (selectorErrors.Count > 0) { foreach (var error in selectorErrors) { Console.WriteLine($"Selector validation error: {error}"); } } ``` -------------------------------- ### Configure ReflectorOptions via appsettings.json Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Example configuration for ReflectorOptions using the standard JSON appsettings format. ```json { "ES": { "Kubernetes": { "Reflector": { "Watcher": { "Timeout": 1800, "ExcludedNamespaces": "kube-system,kube-public,ephemeral-*" } } } } } ``` -------------------------------- ### Configure ReflectorOptions via Environment Variables Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Example configuration for ReflectorOptions using shell environment variables. ```bash export ES_KUBERNETES.REFLECTOR__WATCHER__TIMEOUT=1800 export ES_KUBERNETES.REFLECTOR__WATCHER__EXCLUDEDNAMESPACES="kube-system,kube-public,ephemeral-*" ``` -------------------------------- ### Install Latest Reflector Chart with Helm Source: https://github.com/emberstack/kubernetes-reflector/blob/main/README.md Use this command to upgrade or install the latest released Reflector chart from the OCI registry. ```shell helm upgrade --install reflector oci://ghcr.io/emberstack/helm-charts/reflector ``` -------------------------------- ### Implement Namespace Exclusion Logic Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Example of how to parse and apply namespace exclusion patterns using GlobMatcher. ```csharp // Patterns are parsed into regex at startup var patterns = GlobMatcher.ParseGlobPatterns( options.CurrentValue.Watcher?.ExcludedNamespaces?.ToLowerInvariant()); // Namespaces are checked during event processing if (GlobMatcher.IsNamespaceExcluded(item.Metadata?.NamespaceProperty, patterns)) { continue; // Skip this resource } ``` -------------------------------- ### Configure Reflector via Docker Environment Variables Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Example of passing configuration settings directly to the container using the -e flag. ```bash docker run \ -e "Logging__LogLevel__ES_Kubernetes_Reflector=Information" \ -e "ES_KUBERNETES.REFLECTOR__WATCHER__TIMEOUT=1800" \ -e "ES_KUBERNETES.REFLECTOR__WATCHER__EXCLUDEDNAMESPACES=kube-system,kube-public" \ embedstack/kubernetes-reflector:latest ``` -------------------------------- ### Configure ExcludedNamespaces via Multiple Formats Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Configuration examples for ExcludedNamespaces using JSON, environment variables, and Helm values. ```json { "ES": { "Kubernetes": { "Reflector": { "Watcher": { "ExcludedNamespaces": "kube-system,kube-public,ephemeral-*" } } } } } ``` ```bash export ES_KUBERNETES.REFLECTOR__WATCHER__EXCLUDEDNAMESPACES="kube-system,kube-public,ephemeral-*" ``` ```yaml configuration: watcher: excludedNamespaces: "kube-system,kube-public,ephemeral-*" ``` -------------------------------- ### Handle WatcherEvent Usage Example Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/resource-mirror.md Internal framework usage for routing a modified resource event to the mirror handler. ```csharp var secretMirror = new SecretMirror(logger, kubernetesClient); var watcherEvent = new WatcherEvent { EventType = WatchEventType.Modified, Item = updatedSecret }; await secretMirror.Handle(watcherEvent, cancellationToken); ``` -------------------------------- ### Handle WatcherClosed Usage Example Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/resource-mirror.md Internal framework usage for clearing caches upon watcher closure. ```csharp var closedEvent = new WatcherClosed { ResourceType = typeof(V1Secret), Faulted = false }; await secretMirror.Handle(closedEvent, cancellationToken); ``` -------------------------------- ### Configure Reflector in Kubernetes Deployment Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Example of defining configuration settings within the environment section of a Kubernetes Deployment manifest. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: reflector spec: template: spec: containers: - name: reflector image: emberstack/kubernetes-reflector:latest env: - name: Logging__LogLevel__ES_Kubernetes_Reflector value: "Information" - name: ES_KUBERNETES.REFLECTOR__WATCHER__TIMEOUT value: "1800" - name: ES_KUBERNETES.REFLECTOR__WATCHER__EXCLUDEDNAMESPACES value: "kube-system,kube-public,ephemeral-*" ``` -------------------------------- ### Get a single ConfigMap by namespace and name Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/configmap-mirror.md Fetches a specific ConfigMap resource from the cluster. Throws an HttpOperationException with a 404 status if the resource is not found. ```csharp protected override async Task OnResourceGet( NamespacedName refId, CancellationToken cancellationToken) => await Kubernetes.CoreV1.ReadNamespacedConfigMapAsync( refId.Name, refId.Namespace, cancellationToken: cancellationToken); ``` -------------------------------- ### ExcludedNamespaces Pattern Examples Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Various string patterns for excluding namespaces. ```text "kube-system,kube-public,kube-node-lease" ``` ```text "kube-*,*-temp,*-ephemeral" ``` ```text "*.internal,*.testing,*.local" ``` -------------------------------- ### Annotate Mirror ConfigMap with Source Reference Source: https://github.com/emberstack/kubernetes-reflector/blob/main/README.md Example of a mirror ConfigMap resource. The 'reflector.v1.k8s.emberstack.com/reflects' annotation links it to the source ConfigMap. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: mirror-config-map annotations: reflector.v1.k8s.emberstack.com/reflects: "default/source-config-map" data: ... ``` -------------------------------- ### Register ConfigMapMirror in DI Container Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/configmap-mirror.md Example of registering the ConfigMapMirror as a singleton and as an event handler within a .NET dependency injection container. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton(); // Register as event handlers builder.Services.AddSingleton( sp => sp.GetRequiredService()); builder.Services.AddSingleton( sp => sp.GetRequiredService()); ``` -------------------------------- ### Access Watcher Timeout Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Example of accessing the configured timeout value in code. ```json { "ES": { "Kubernetes": { "Reflector": { "Watcher": { "Timeout": 1800 } } } } } ``` ```csharp var timeout = options.CurrentValue.Watcher?.Timeout ?? 3600; ``` -------------------------------- ### Register SecretMirror in DI Container Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/secret-mirror.md Example of registering SecretMirror as a singleton and event handler in a .NET dependency injection container. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton(); // Register as event handlers builder.Services.AddSingleton( sp => sp.GetRequiredService()); builder.Services.AddSingleton( sp => sp.GetRequiredService()); ``` -------------------------------- ### Annotate Source ConfigMap for Reflection Source: https://github.com/emberstack/kubernetes-reflector/blob/main/README.md Example of a source ConfigMap resource with annotations to enable and control reflection. Similar to Secrets, specify allowed namespaces or selectors. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: source-config-map annotations: reflector.v1.k8s.emberstack.com/reflection-allowed: "true" reflector.v1.k8s.emberstack.com/reflection-allowed-namespaces: "namespace-1,namespace-2,namespace-[0-9]*" reflector.v1.k8s.emberstack.com/reflection-allowed-namespaces-selector: "env=production" data: ... ``` -------------------------------- ### Annotate Source Secret for Reflection Source: https://github.com/emberstack/kubernetes-reflector/blob/main/README.md Example of a source Secret resource with annotations to enable and control reflection. Ensure reflection-allowed is true and specify allowed namespaces or selectors. ```yaml apiVersion: v1 kind: Secret metadata: name: source-secret annotations: reflector.v1.k8s.emberstack.com/reflection-allowed: "true" reflector.v1.k8s.emberstack.com/reflection-allowed-namespaces: "namespace-1,namespace-2,namespace-[0-9]*" reflector.v1.k8s.emberstack.com/reflection-allowed-namespaces-selector: "env=production" data: ... ``` -------------------------------- ### Annotate Mirror Secret with Source Reference Source: https://github.com/emberstack/kubernetes-reflector/blob/main/README.md Example of a mirror Secret resource. The 'reflector.v1.k8s.emberstack.com/reflects' annotation specifies the source Secret in 'namespace/name' format. ```yaml apiVersion: v1 kind: Secret metadata: name: mirror-secret annotations: reflector.v1.k8s.emberstack.com/reflects: "default/source-secret" data: ... ``` -------------------------------- ### Configure Application Entry Point Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/entry-points.md Initializes the host, configures logging and Kubernetes client, and registers watchers and mirrors as hosted services. ```csharp return await ProgramEntry.CreateBuilder(args) .UseSerilog() .Build() .RunAsync(async _ => { var builder = WebApplication.CreateBuilder(args); // Load environment-specific configuration builder.Configuration.AddEnvironmentVariables("ES_"); // Setup logging builder.Logging.ClearProviders(); builder.Ignite(); builder.IgniteSerilog(config => config.Destructure.ByTransforming( v => v.NamespacedName())); builder.IgniteSeqOpenTelemetryExporter(); // Setup Kubernetes client builder.IgniteKubernetesClient(); // Configure reflector options builder.Services.Configure( builder.Configuration.GetSection( nameof(ES.Kubernetes.Reflector))); // Register watchers as hosted services builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); // Register mirrors as singletons and event handlers builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton( sp => sp.GetRequiredService()); builder.Services.AddSingleton( sp => sp.GetRequiredService()); builder.Services.AddSingleton( sp => sp.GetRequiredService()); builder.Services.AddSingleton( sp => sp.GetRequiredService()); var app = builder.Build(); app.Ignite(); await app.RunAsync(); return 0; }); public partial class Program; ``` -------------------------------- ### Use NamespacedName utility Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/types.md Demonstrates instantiation, extension method usage, string conversion, and application in Kubernetes client operations. ```csharp // Create a namespaced name var resourceId = new NamespacedName { Namespace = "default", Name = "my-secret" }; // Alternative with extension method var id = "default".ToNamespacedName("my-secret"); // String representation var str = resourceId.ToString(); // "default/my-secret" // Use in resource operations await k8s.CoreV1.ReadNamespacedSecretAsync(resourceId.Name, resourceId.Namespace); ``` -------------------------------- ### Initialize ConfigMapMirror Constructor Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/configmap-mirror.md Constructor signature for the ConfigMapMirror class requiring logger and Kubernetes client dependencies. ```csharp public ConfigMapMirror( ILogger logger, IKubernetes kubernetes) ``` -------------------------------- ### Invoke Handle Method for WatcherEvent Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/secret-mirror.md Example of manually invoking the Handle method to process a secret modification event. ```csharp var secretMirror = sp.GetRequiredService(); var event = new WatcherEvent { EventType = WatchEventType.Modified, Item = modifiedSecret }; await secretMirror.Handle(@event, cancellationToken); ``` -------------------------------- ### Configure Reflector via appsettings.Production.json Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Production-specific configuration file with stricter logging levels and adjusted watcher timeouts. ```json { "Logging": { "LogLevel": { "Default": "Warning" } }, "Serilog": { "MinimumLevel": "Warning", "WriteTo": [ { "Name": "Console" } ] }, "ES": { "Kubernetes": { "Reflector": { "Watcher": { "Timeout": 3600, "ExcludedNamespaces": "kube-*,*-temp" } } } } } ``` -------------------------------- ### Configure Reflector via appsettings.json Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Standard configuration file for defining logging levels and watcher settings in a development or general environment. ```json { "Logging": { "LogLevel": { "Default": "Information", "System": "Warning", "Microsoft": "Warning", "ES": "Information" } }, "Serilog": { "MinimumLevel": "Information", "WriteTo": [ { "Name": "Console", "Args": { "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}" } } ] }, "ES": { "Kubernetes": { "Reflector": { "Watcher": { "Timeout": 1800, "ExcludedNamespaces": "kube-system,kube-public,kube-node-lease,ephemeral-*" } } } } } ``` -------------------------------- ### Initialize MirroringProperties Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/mirroring-properties.md Creates a new instance of the configuration class with default values. ```csharp public MirroringProperties() ``` -------------------------------- ### ConfigMapWatcher Constructor Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/watchers.md Initializes the ConfigMapWatcher with required Kubernetes client and event handler dependencies. ```csharp public ConfigMapWatcher( ILogger logger, IKubernetes kubernetes, IOptionsMonitor options, IEnumerable watcherEventHandlers, IEnumerable watcherClosedHandlers) : WatcherBackgroundService( logger, options, watcherEventHandlers, watcherClosedHandlers) ``` -------------------------------- ### Implement OnResourceClone Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/resource-mirror.md Defines the method signature and a SecretMirror implementation for creating a shallow clone of a resource without metadata. ```csharp protected abstract Task OnResourceClone(TResource sourceResource) ``` ```csharp protected override Task OnResourceClone(V1Secret sourceResource) => Task.FromResult(new V1Secret { ApiVersion = sourceResource.ApiVersion, Kind = sourceResource.Kind, Type = sourceResource.Type, Data = sourceResource.Data }); ``` -------------------------------- ### Registering Services and Hosted Services Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/entry-points.md Registers watchers as hosted services and mirrors as singletons, including event handler registration. ```csharp // Watchers registered as hosted services builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); // Mirrors registered as singletons builder.Services.AddSingleton(); builder.Services.AddSingleton(); // And as event handlers builder.Services.AddSingleton( sp => sp.GetRequiredService()); builder.Services.AddSingleton( sp => sp.GetRequiredService()); ``` -------------------------------- ### Implement Custom Resource Mirror in C# Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/resource-mirror.md Extends the ResourceMirror base class to define custom logic for mirroring Kubernetes ConfigMaps. Requires implementation of lifecycle methods for resource cloning, patching, and CRUD operations. ```csharp // Custom mirror for Kubernetes ConfigMaps (already built-in) public class ConfigMapMirror( ILogger logger, IKubernetes kubernetes) : ResourceMirror(logger, kubernetes) { protected override async Task OnResourceWithNameList( string itemRefName, CancellationToken cancellationToken) => [ .. (await Kubernetes.CoreV1.ListConfigMapForAllNamespacesAsync( fieldSelector: $"metadata.name={itemRefName}", cancellationToken: cancellationToken)) .Items ]; protected override async Task OnResourceApplyPatch( V1Patch patch, NamespacedName refId) { await Kubernetes.CoreV1.PatchNamespacedConfigMapAsync( patch, refId.Name, refId.Namespace); } protected override Task OnResourceConfigurePatch( V1ConfigMap source, JsonPatchDocument patchDoc) { patchDoc.Replace(e => e.Data, source.Data); patchDoc.Replace(e => e.BinaryData, source.BinaryData); return Task.CompletedTask; } protected override async Task OnResourceCreate(V1ConfigMap item, string ns) { await Kubernetes.CoreV1.CreateNamespacedConfigMapAsync(item, ns); } protected override Task OnResourceClone(V1ConfigMap sourceResource) => Task.FromResult(new V1ConfigMap { ApiVersion = sourceResource.ApiVersion, Kind = sourceResource.Kind, Data = sourceResource.Data, BinaryData = sourceResource.BinaryData }); protected override async Task OnResourceDelete(NamespacedName resourceId) { await Kubernetes.CoreV1.DeleteNamespacedConfigMapAsync( resourceId.Name, resourceId.Namespace); } protected override async Task OnResourceGet( NamespacedName refId, CancellationToken cancellationToken) => await Kubernetes.CoreV1.ReadNamespacedConfigMapAsync( refId.Name, refId.Namespace, cancellationToken: cancellationToken); } ``` -------------------------------- ### Implement Generic Resource Mirroring Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/types.md Use the IKubernetesObject interface to create generic handlers for various Kubernetes resource types. ```csharp public abstract class ResourceMirror( ILogger logger, IKubernetes kubernetes) where TResource : class, IKubernetesObject { // Generic implementation works with any resource type var metadata = resource.Metadata; var properties = resource.GetMirroringProperties(); } ``` -------------------------------- ### Configure reflection annotations in C# Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/annotations.md Use the Annotations class to retrieve keys for configuring source resource reflection and tracking mirrors. ```csharp using ES.Kubernetes.Reflector.Mirroring.Core; // Configure a source secret to allow reflection var allowedAnnotation = Annotations.Reflection.Allowed; // "reflector.v1.k8s.emberstack.com/reflection-allowed" // Mark a mirror to track its source var reflectsAnnotation = Annotations.Reflection.Reflects; // "reflector.v1.k8s.emberstack.com/reflects" // Apply to Kubernetes metadata metadata.Annotations[allowedAnnotation] = "true"; metadata.Annotations[reflectsAnnotation] = "default/source-secret"; ``` -------------------------------- ### Get Single Secret by Namespaced Name Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/secret-mirror.md Retrieves a specific secret using its namespace and name. Throws an HttpOperationException with status 404 if the resource is missing. ```csharp protected override async Task OnResourceGet( NamespacedName refId, CancellationToken cancellationToken) => await Kubernetes.CoreV1.ReadNamespacedSecretAsync( refId.Name, refId.Namespace, cancellationToken: cancellationToken); ``` -------------------------------- ### Helm Deployment Configuration Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Use the values.yaml file to customize deployment parameters, including image tags, watcher settings, and resource limits. ```yaml image: repository: emberstack/kubernetes-reflector tag: "1.0.0" pullPolicy: IfNotPresent configuration: logging: minimumLevel: Information watcher: timeout: 1800 excludedNamespaces: "kube-system,kube-public,*-temp" kubernetes: skipTlsVerify: false rbac: enabled: true serviceAccount: create: true name: reflector resources: limits: cpu: 100m memory: 128Mi requests: cpu: 50m memory: 64Mi nodeSelector: {} tolerations: [] affinity: {} ``` -------------------------------- ### Implement OnResourceConfigurePatch Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/resource-mirror.md Defines the method signature and implementations for SecretMirror and ConfigMapMirror to configure patch documents with source data. ```csharp protected abstract Task OnResourceConfigurePatch( TResource source, JsonPatchDocument patchDoc) ``` ```csharp protected override Task OnResourceConfigurePatch( V1Secret source, JsonPatchDocument patchDoc) { patchDoc.Replace(e => e.Data, source.Data); return Task.CompletedTask; } ``` ```csharp protected override Task OnResourceConfigurePatch( V1ConfigMap source, JsonPatchDocument patchDoc) { patchDoc.Replace(e => e.Data, source.Data); patchDoc.Replace(e => e.BinaryData, source.BinaryData); return Task.CompletedTask; } ``` -------------------------------- ### Implement OnResourceCreate Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/resource-mirror.md Defines the method signature and a SecretMirror implementation for creating new mirror resources in a target namespace. ```csharp protected abstract Task OnResourceCreate(TResource item, string ns) ``` ```csharp protected override async Task OnResourceCreate(V1Secret item, string ns) { await Kubernetes.CoreV1.CreateNamespacedSecretAsync(item, ns); } ``` -------------------------------- ### Define OnResourceGet Method Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/resource-mirror.md Abstract method signature for retrieving a single resource by its namespace and name. ```csharp protected abstract Task OnResourceGet( NamespacedName refId, CancellationToken cancellationToken) ``` -------------------------------- ### Create Mirror ConfigMap Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/configmap-mirror.md Creates a new mirror ConfigMap in the target namespace with pre-populated data and reflection annotations. ```csharp protected override async Task OnResourceCreate(V1ConfigMap item, string ns) { await Kubernetes.CoreV1.CreateNamespacedConfigMapAsync(item, ns); } ``` -------------------------------- ### Configure Reflection via Annotations Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/types.md Apply annotation constants to resource metadata to enable or configure reflection behavior. ```csharp metadata.Annotations[Annotations.Reflection.Allowed] = "true"; metadata.Annotations[Annotations.Reflection.Reflects] = "default/source"; ``` -------------------------------- ### Define OnResourceWithNameList Method Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/resource-mirror.md Abstract method signature for retrieving all resources with a specific name across all namespaces. ```csharp protected abstract Task OnResourceWithNameList( string itemRefName, CancellationToken cancellationToken) ``` -------------------------------- ### Manual Direct Reflection Configuration Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/README.md Define a mirror resource that explicitly points to a source resource using the reflects annotation. ```yaml apiVersion: v1 kind: Secret metadata: name: app-secrets namespace: team-a annotations: reflector.v1.k8s.emberstack.com/reflects: "default/app-secrets" ``` -------------------------------- ### Initialize SecretMirror Constructor Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/secret-mirror.md Constructor signature for the SecretMirror class. ```csharp public SecretMirror( ILogger logger, IKubernetes kubernetesClient) ``` -------------------------------- ### Initialize SecretWatcher Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/watchers.md Constructor for the SecretWatcher class, requiring dependency injection for logging, Kubernetes client, and event handlers. ```csharp public SecretWatcher( ILogger logger, IKubernetes kubernetes, IOptionsMonitor options, IEnumerable watcherEventHandlers, IEnumerable watcherClosedHandlers) : WatcherBackgroundService( logger, options, watcherEventHandlers, watcherClosedHandlers) ``` -------------------------------- ### NamespaceWatcher OnGetWatcher Implementation Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/watchers.md Returns the Kubernetes watch stream for all Namespaces. ```csharp protected override IAsyncEnumerable<(WatchEventType, V1Namespace)> OnGetWatcher( CancellationToken cancellationToken) => kubernetes.CoreV1.WatchListNamespaceAsync( timeoutSeconds: WatcherTimeout, cancellationToken: cancellationToken); ``` -------------------------------- ### Apply Reflector Deployment Source: https://github.com/emberstack/kubernetes-reflector/blob/main/README.md Apply the reflector.yaml file to deploy the reflector to your Kubernetes cluster. This command should be run with appropriate permissions. ```shell $ kubectl -n kube-system apply -f https://github.com/emberstack/kubernetes-reflector/releases/latest/download/reflector.yaml ``` -------------------------------- ### ConfigMapWatcher OnGetWatcher Implementation Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/watchers.md Returns the Kubernetes watch stream for all ConfigMaps across the cluster. ```csharp protected override IAsyncEnumerable<(WatchEventType, V1ConfigMap)> OnGetWatcher( CancellationToken cancellationToken) => kubernetes.CoreV1.WatchListConfigMapForAllNamespacesAsync( timeoutSeconds: WatcherTimeout, cancellationToken: cancellationToken); ``` -------------------------------- ### Implement OnGetWatcher for SecretWatcher Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/watchers.md Concrete implementation of the watch stream retrieval for secrets across all namespaces. ```csharp protected override IAsyncEnumerable<(WatchEventType, V1Secret)> OnGetWatcher( CancellationToken cancellationToken) => kubernetes.CoreV1.WatchListSecretForAllNamespacesAsync( timeoutSeconds: WatcherTimeout, cancellationToken: cancellationToken); ``` -------------------------------- ### Injecting SecretMirror for Monitoring Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/secret-mirror.md Shows how to inject SecretMirror into custom classes for testing or diagnostic purposes. ```csharp public class ReflectionMonitor(SecretMirror secretMirror) { // Access protected logger through reflection if needed for monitoring // (Not recommended - for testing/diagnostics only) } ``` -------------------------------- ### Define WatcherBackgroundService Constructor Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/watchers.md The constructor for the abstract base class used to initialize resource watchers as hosted services. ```csharp public abstract class WatcherBackgroundService( ILogger logger, IOptionsMonitor options, IEnumerable watcherEventHandlers, IEnumerable watcherClosedHandlers) : BackgroundService ``` -------------------------------- ### Implement OnResourceDelete Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/resource-mirror.md Defines the method signature and a SecretMirror implementation for deleting a mirror resource from the cluster. ```csharp protected abstract Task OnResourceDelete(NamespacedName resourceId) ``` ```csharp protected override async Task OnResourceDelete(NamespacedName resourceId) { await Kubernetes.CoreV1.DeleteNamespacedSecretAsync( resourceId.Name, resourceId.Namespace); } ``` -------------------------------- ### Configure Patch Document Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/configmap-mirror.md Configures the JSON patch to copy both data and binaryData fields from the source to the mirror. ```csharp protected override Task OnResourceConfigurePatch( V1ConfigMap source, JsonPatchDocument patchDoc) { patchDoc.Replace(e => e.Data, source.Data); patchDoc.Replace(e => e.BinaryData, source.BinaryData); return Task.CompletedTask; } ``` -------------------------------- ### Type Dependency Hierarchy Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/types.md Visual representation of the relationships between Watcher events, Kubernetes objects, and internal resource mirroring structures. ```text WatcherEvent └─ IKubernetesObject ├─ V1Secret ├─ V1ConfigMap └─ V1Namespace └─ V1ObjectMeta └─ Annotations (Dictionary) └─ MirroringProperties (extracted from) └─ NamespacedName (for Reflects) ReflectorOptions └─ WatcherOptions WatcherClosed └─ Type (ResourceType) ResourceMirror ├─ Caches: ConcurrentDictionary └─ Processes: WatcherEvent, WatcherClosed ``` -------------------------------- ### Implement OnResourceApplyPatch Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/resource-mirror.md Defines the method signature and a SecretMirror implementation for applying JSON patches to existing mirror resources. ```csharp protected abstract Task OnResourceApplyPatch(V1Patch source, NamespacedName refId) ``` ```csharp protected override async Task OnResourceApplyPatch(V1Patch patch, NamespacedName refId) { await Kubernetes.CoreV1.PatchNamespacedSecretWithHttpMessagesAsync( patch, refId.Name, refId.Namespace); } ``` -------------------------------- ### NamespaceWatcher Constructor Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/watchers.md Initializes the NamespaceWatcher with required Kubernetes client and event handler dependencies. ```csharp public NamespaceWatcher( ILogger logger, IKubernetes kubernetes, IOptionsMonitor options, IEnumerable watcherEventHandlers, IEnumerable watcherClosedHandlers) : WatcherBackgroundService( logger, options, watcherEventHandlers, watcherClosedHandlers) ``` -------------------------------- ### Watcher Event Handling Integration Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/configmap-mirror.md Demonstrates how the ConfigMapWatcher iterates through registered handlers to process events. ```csharp // ConfigMapWatcher passes events to all IWatcherEventHandler implementations foreach (var watcherEventHandler in watcherEventHandlers) await watcherEventHandler.Handle(watcherEvent, cancellationToken); ``` -------------------------------- ### Clone ConfigMap Resource Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/configmap-mirror.md Creates a shallow clone of the source ConfigMap, copying semantic fields like Data and BinaryData. ```csharp protected override Task OnResourceClone(V1ConfigMap sourceResource) => Task.FromResult(new V1ConfigMap { ApiVersion = sourceResource.ApiVersion, Kind = sourceResource.Kind, Data = sourceResource.Data, BinaryData = sourceResource.BinaryData }); ``` -------------------------------- ### Define and use ReflectedVersion property Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/mirroring-properties.md Tracks the source resourceVersion to optimize updates. Use this to compare against the current source version to skip redundant operations. ```csharp public string ReflectedVersion { get; set; } = string.Empty; ``` ```csharp var properties = metadata.GetMirroringProperties(); var sourceProperties = source.GetMirroringProperties(); if (properties.ReflectedVersion == sourceProperties.ResourceVersion) { // Mirror is already up-to-date with source } ``` -------------------------------- ### Configure Reflection via Annotations Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/README.md Use these annotations on a Kubernetes Secret to enable reflection and specify target namespaces for auto-creation of mirrors. ```yaml apiVersion: v1 kind: Secret metadata: name: app-secrets namespace: default annotations: # Allow reflection from this secret reflector.v1.k8s.emberstack.com/reflection-allowed: "true" # To these namespaces reflector.v1.k8s.emberstack.com/reflection-allowed-namespaces: "team-a,team-b" # And auto-create mirrors in matching namespaces reflector.v1.k8s.emberstack.com/reflection-auto-enabled: "true" ``` -------------------------------- ### List ConfigMaps by Name across all namespaces Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/configmap-mirror.md Retrieves all ConfigMaps matching a specific name using a field selector. Useful for discovering existing mirrors and validating reflection state. ```csharp protected override async Task OnResourceWithNameList( string itemRefName, CancellationToken cancellationToken) => [ .. (await Kubernetes.CoreV1.ListConfigMapForAllNamespacesAsync( fieldSelector: $"metadata.name={itemRefName}", cancellationToken: cancellationToken)) .Items ]; ``` -------------------------------- ### Configure Logging Levels in appsettings.json Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Set the logging verbosity for the application using the Logging.LogLevel section in your configuration file. ```json { "Logging": { "LogLevel": { "Default": "Information", "ES.Kubernetes.Reflector": "Debug" } } } ``` -------------------------------- ### Define Reflection.AutoEnabled constant Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/annotations.md Enables automatic creation of mirror resources in permitted namespaces when set to true. ```csharp public static string AutoEnabled => $"{Prefix}/reflection-auto-enabled" // Result: "reflector.v1.k8s.emberstack.com/reflection-auto-enabled" ``` -------------------------------- ### Configure Dependency Injection for ConfigMapMirror Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/configmap-mirror.md Registers ConfigMapMirror as a singleton and binds it to watcher event handlers in a .NET application. ```csharp // Program.cs var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton(); builder.Services.AddSingleton( sp => sp.GetRequiredService()); builder.Services.AddSingleton( sp => sp.GetRequiredService()); var app = builder.Build(); await app.RunAsync(); ``` -------------------------------- ### Register ReflectorOptions in C# Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Registering options in the dependency injection container and accessing them via IOptionsMonitor. ```csharp builder.Services.Configure( builder.Configuration.GetSection(nameof(ES.Kubernetes.Reflector))); // Inject IOptionsMonitor into services var options = optionsMonitor.CurrentValue.Watcher?.Timeout ?? 3600; ``` -------------------------------- ### Configure Serilog Structured Logging Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Define Serilog sinks and output templates within the Serilog configuration block. ```json { "Serilog": { "MinimumLevel": "Information", "WriteTo": [ { "Name": "Console", "Args": { "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}" } } ] } } ``` -------------------------------- ### Define Reflection.AutoNamespaces constant Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/annotations.md Specifies target namespace patterns for automatic mirror creation. ```csharp public static string AutoNamespaces => $"{Prefix}/reflection-auto-namespaces" // Result: "reflector.v1.k8s.emberstack.com/reflection-auto-namespaces" ``` -------------------------------- ### Resource Lifecycle Flow Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/README.md Visual representation of the lifecycle events for source and mirror secrets during creation, modification, and deletion. ```text Source Secret Created ├─ Annotations parsed into MirroringProperties ├─ Selectors validated └─ If direct mirrors exist: update them If auto-reflection: create mirrors in matching namespaces Source Secret Modified ├─ resourceVersion changes ├─ All mirrors updated with new data └─ Mirror reflected-version annotations updated Source Secret Deleted ├─ All auto-created mirrors deleted ├─ Direct mirrors not affected (remain but won't update) └─ Caches cleared Mirror Secret Created (Direct Reflection) ├─ Annotation `reflects` references source ├─ Source fetched and validated └─ Mirror populated with source data Mirror Secret Modified ├─ If annotation change breaks reflection: log warning └─ Otherwise: next source update will re-apply expected data Namespace Added/Modified ├─ Labels checked against all auto-reflection selectors ├─ Auto-mirrors created for matching sources └─ Mirrors deleted for sources that no longer permit reflection ``` -------------------------------- ### Handle WatcherEvent Usage Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/configmap-mirror.md Demonstrates how to manually trigger the Handle method for a modified ConfigMap event. ```csharp var configMapMirror = sp.GetRequiredService(); var @event = new WatcherEvent { EventType = WatchEventType.Modified, Item = modifiedConfigMap }; await configMapMirror.Handle(@event, cancellationToken); ``` -------------------------------- ### ResourceMirror Constructor Definition Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/resource-mirror.md Protected constructor for derived classes, requiring a logger and Kubernetes client. ```csharp public abstract class ResourceMirror( ILogger logger, IKubernetes kubernetes) where TResource : class, IKubernetesObject ``` -------------------------------- ### Auto-Reflection with Namespace Selectors Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/configmap-mirror.md Configures a source ConfigMap to automatically mirror into namespaces matching specific label selectors. ```yaml # Source ConfigMap with auto-reflection apiVersion: v1 kind: ConfigMap metadata: name: shared-config namespace: default annotations: reflector.v1.k8s.emberstack.com/reflection-allowed: "true" reflector.v1.k8s.emberstack.com/reflection-auto-enabled: "true" reflector.v1.k8s.emberstack.com/reflection-allowed-namespaces-selector: "env=production" reflector.v1.k8s.emberstack.com/reflection-auto-namespaces-selector: "tier in (api,web)" data: version: "1.2.3" settings: | timeout=30s retries=3 ``` -------------------------------- ### Define Reflection.AllowedNamespaces constant Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/annotations.md Specifies a comma-separated list of namespace patterns permitted to reflect from the source. ```csharp public static string AllowedNamespaces => $"{Prefix}/reflection-allowed-namespaces" // Result: "reflector.v1.k8s.emberstack.com/reflection-allowed-namespaces" ``` -------------------------------- ### Define Reflection.Reflects constant Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/annotations.md References the source resource on a mirror resource using the namespace/name format. ```csharp public static string Reflects => $"{Prefix}/reflects" // Result: "reflector.v1.k8s.emberstack.com/reflects" ``` -------------------------------- ### Access MetaReflectedVersion annotation key Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/annotations.md Tracks the Kubernetes resourceVersion of the source to optimize reflection updates. For internal use only. ```csharp public static string MetaReflectedVersion => $"{Prefix}/reflected-version" // Result: "reflector.v1.k8s.emberstack.com/reflected-version" ``` -------------------------------- ### GetMirroringProperties (from metadata) Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/mirroring-properties.md Extracts mirroring properties from a Kubernetes metadata object. ```APIDOC ## GetMirroringProperties (from metadata) ### Description Extracts mirroring properties from a Kubernetes metadata object's annotation dictionary. ### Signature public static MirroringProperties GetMirroringProperties(this V1ObjectMeta metadata) ### Parameters - **metadata** (V1ObjectMeta) - Required - Kubernetes metadata object. ### Returns - **MirroringProperties** - The properties extracted from the annotation dictionary. ``` -------------------------------- ### Access V1ObjectMeta properties Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/types.md Extract metadata, annotations, labels, and resource versions from Kubernetes resources. ```csharp var metadata = resource.Metadata; // Extract annotations var annotations = metadata.Annotations ?? new Dictionary(); var isAllowed = annotations.GetValueOrDefault( Annotations.Reflection.Allowed) == "true"; // Read labels var labels = metadata.Labels ?? new Dictionary(); // Track version for reflection var version = metadata.ResourceVersion; ``` -------------------------------- ### Implement SecretMirror OnResourceWithNameList Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/resource-mirror.md Concrete implementation for SecretMirror that lists secrets matching a specific name across all namespaces. ```csharp protected override async Task OnResourceWithNameList( string itemRefName, CancellationToken cancellationToken) => [ .. (await Kubernetes.CoreV1.ListSecretForAllNamespacesAsync( fieldSelector: $"metadata.name={itemRefName}", cancellationToken: cancellationToken)) .Items ]; ``` -------------------------------- ### Define NamespacedName struct Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/types.md Represents a Kubernetes resource identifier using a namespace and name. ```csharp public readonly struct NamespacedName { public string Namespace { get; init; } public string Name { get; init; } } ``` -------------------------------- ### Manual ConfigMap Reflection Configuration Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/configmap-mirror.md Defines a source ConfigMap with reflection enabled and a corresponding mirror ConfigMap that references the source. ```yaml # Source ConfigMap apiVersion: v1 kind: ConfigMap metadata: name: app-config namespace: default annotations: reflector.v1.k8s.emberstack.com/reflection-allowed: "true" data: app.conf: | debug=true port=8080 --- # Mirror ConfigMap (manually created) apiVersion: v1 kind: ConfigMap metadata: name: app-config namespace: team-a annotations: reflector.v1.k8s.emberstack.com/reflects: "default/app-config" data: {} # Automatically populated and kept in sync ``` -------------------------------- ### Implement OnResourceIgnoreCheck for SecretWatcher Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/watchers.md Filters out specific resources, such as Helm-managed secrets, to reduce event traffic. ```csharp protected override Task OnResourceIgnoreCheck(V1Secret item) { // Skip helm version secrets. This can cause a terrible amount of traffic. var ignore = item.Type.StartsWith("helm.sh"); return Task.FromResult(ignore); } ``` -------------------------------- ### Optimizing Updates via Resource Version Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/entry-points.md Compares the current resource version against the reflected version to prevent unnecessary update operations. ```csharp if (reflectionObj.GetMirroringProperties().ReflectedVersion == source.Metadata.ResourceVersion) { Logger.LogDebug("Skipping - Source matches reflected version"); return; // No update needed } ``` -------------------------------- ### CanBeAutoReflectedToNamespace (V1Namespace) Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/mirroring-properties.md Comprehensive auto-reflection check combining name patterns and label selectors. ```APIDOC ## public static bool CanBeAutoReflectedToNamespace(this MirroringProperties properties, V1Namespace ns) ### Description Comprehensive auto-reflection check combining name patterns and label selectors for AutoNamespaces and AutoNamespacesSelector, with OR logic for each. ### Parameters - **ns** (V1Namespace) - Required - Target namespace object ### Returns - **bool** - true if auto-reflection is permitted considering all selectors. ``` -------------------------------- ### Define Reflection.AutoNamespacesSelector constant Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/annotations.md Filters namespaces for automatic mirror creation using a label selector. ```csharp public static string AutoNamespacesSelector => $"{Prefix}/reflection-auto-namespaces-selector" // Result: "reflector.v1.k8s.emberstack.com/reflection-auto-namespaces-selector" ``` -------------------------------- ### Compare namespace labels with NamespaceLabelsEqual Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/resource-mirror.md Compares two V1Namespace objects to determine if their labels are identical, ignoring status, annotations, and resourceVersion. ```csharp internal static bool NamespaceLabelsEqual(V1Namespace a, V1Namespace b) ``` -------------------------------- ### CanBeAutoReflectedToNamespace (string) Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/mirroring-properties.md Checks if automatic mirror creation is permitted based on name patterns. ```APIDOC ## public static bool CanBeAutoReflectedToNamespace(this MirroringProperties properties, string ns) ### Description Checks if automatic mirror creation is permitted. Returns true only if Allowed, AutoEnabled, and AutoNamespaces patterns all permit it. ### Parameters - **ns** (string) - Required - Target namespace name ### Returns - **bool** - true if auto-reflection is permitted to this namespace. ``` -------------------------------- ### Set Logging Level via Environment Variable Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/configuration.md Override logging levels using standard .NET Core environment variable syntax. ```bash export Logging__LogLevel__ES_Kubernetes_Reflector=Debug ``` -------------------------------- ### Define Reflection.Allowed constant Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/annotations.md Permits a source resource to be reflected when set to true. ```csharp public static string Allowed => $"{Prefix}/reflection-allowed" // Result: "reflector.v1.k8s.emberstack.com/reflection-allowed" ``` -------------------------------- ### Define MirroringProperties class Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/types.md Encapsulates reflection configuration extracted from resource annotations. ```csharp public class MirroringProperties { public bool Allowed { get; set; } public string AllowedNamespaces { get; set; } = string.Empty; public string AllowedNamespacesSelector { get; set; } = string.Empty; public bool AutoEnabled { get; set; } public string AutoNamespaces { get; set; } = string.Empty; public string AutoNamespacesSelector { get; set; } = string.Empty; public NamespacedName? Reflects { get; set; } public string ResourceVersion { get; set; } = string.Empty; public bool IsAutoReflection { get; set; } public string ReflectedVersion { get; set; } = string.Empty; public DateTimeOffset? ReflectedAt { get; set; } public bool IsReflection => Reflects != null; } ``` -------------------------------- ### Handle WatcherEvent Method Signature Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/secret-mirror.md Method signature for processing secret watch events. ```csharp public Task Handle(WatcherEvent notification, CancellationToken cancellationToken) ``` -------------------------------- ### Implementing Caching and Invalidation Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/entry-points.md Manages resource state via local caches and clears them upon receiving a WatcherClosed notification to ensure consistency. ```csharp // Cache state _propertiesCache.TryGetValue(sourceName, out var properties); _autoReflectionCache.GetOrAdd(sourceName, []); // On watcher close, invalidate public Task Handle(WatcherClosed notification, CancellationToken cancellationToken) { if (notification.ResourceType == typeof(TResource)) { _autoSources.Clear(); // Clear caches _directReflectionCache.Clear(); } return Task.CompletedTask; } ``` -------------------------------- ### Defining Abstract Mirror Operations Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/entry-points.md Defines the template methods that concrete mirror implementations must provide for resource lifecycle management. ```csharp protected abstract Task OnResourceCreate(TResource item, string ns); protected abstract Task OnResourceApplyPatch(V1Patch patch, NamespacedName refId); protected abstract Task OnResourceClone(TResource source); protected abstract Task OnResourceDelete(NamespacedName resourceId); ``` -------------------------------- ### Access Auto-Reflection Namespace Patterns Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/mirroring-properties.md Retrieves the glob patterns used to filter namespaces for automatic mirror creation. ```csharp var properties = metadata.GetMirroringProperties(); // properties.AutoNamespaces == "prod-*,staging-*" ``` -------------------------------- ### Bind ReflectorOptions configuration Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/types.md Bind the configuration section to the ReflectorOptions class within the service container. ```csharp builder.Services.Configure( builder.Configuration.GetSection(nameof(ES.Kubernetes.Reflector))); ``` -------------------------------- ### Evaluating Namespace Label Selectors Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/entry-points.md Implements a fail-closed policy when namespace metadata is missing from the cache during reflection evaluation. ```csharp if (_namespaceCache.TryGetValue(ns, out var nsObj)) return properties.CanBeReflectedToNamespace(nsObj); // Label selector configured but namespace not in cache: deny if (!string.IsNullOrEmpty(properties.AllowedNamespacesSelector)) { Logger.LogDebug("Namespace not in cache; denying reflection"); return false; } return properties.CanBeReflectedToNamespace(ns); // Name patterns only ``` -------------------------------- ### Check reflection permission by namespace name Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/mirroring-properties.md Evaluates if reflection is permitted based on namespace name patterns, excluding label selector evaluation. ```csharp var properties = metadata.GetMirroringProperties(); if (properties.CanBeReflectedToNamespace("team-a")) { // Source is allowed and namespace matches patterns } ``` -------------------------------- ### CanBeReflectedToNamespace (V1Namespace) Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/api-reference/mirroring-properties.md Comprehensive check that evaluates both name patterns and label selectors. ```APIDOC ## public static bool CanBeReflectedToNamespace(this MirroringProperties properties, V1Namespace ns) ### Description Comprehensive check that evaluates both AllowedNamespaces (name patterns) and AllowedNamespacesSelector (label selectors) with OR logic. ### Parameters - **ns** (V1Namespace) - Required - Target namespace object with labels ### Returns - **bool** - true if reflection is permitted considering both name patterns and label selectors. ``` -------------------------------- ### Define WatcherOptions class Source: https://github.com/emberstack/kubernetes-reflector/blob/main/_autodocs/types.md Configuration class for watcher-specific settings. ```csharp public class WatcherOptions { public int? Timeout { get; set; } public string? ExcludedNamespaces { get; set; } ```