Beispiel #1
0
 public V1AlphaController(IKubernetes kubernetes, IKeyManagement keyManagement)
 {
     this.mKubernetes    = kubernetes;
     this.mKeyManagement = keyManagement;
 }
Beispiel #2
0
 protected override Task <V1Secret> OnResourceGet(IKubernetes client, string name, string ns)
 {
     return(client.ReadNamespacedSecretAsync(name, ns));
 }
Beispiel #3
0
 public DecryptController(IKubernetes kubernetes, IKeyManagement keyManagement)
 {
     mKubernetes    = kubernetes;
     mKeyManagement = keyManagement;
 }
Beispiel #4
0
 public Mirror(ILogger <Mirror> logger, IKubernetes client,
               ManagedWatcher <V1Secret, V1SecretList> secretWatcher,
               ManagedWatcher <V1Namespace, V1NamespaceList> namespaceWatcher)
     : base(logger, client, secretWatcher, namespaceWatcher)
 {
 }
Beispiel #5
0
 protected override Task OnResourceDelete(IKubernetes client, string name, string ns)
 {
     return(client.DeleteNamespacedSecretAsync(name, ns));
 }
Beispiel #6
0
 public ConfigMapMirror(ILogger <ConfigMapMirror> logger, IKubernetes client,
                        ManagedWatcher <V1ConfigMap, V1ConfigMapList> configMapWatcher,
                        ManagedWatcher <V1Namespace, V1NamespaceList> namespaceWatcher)
     : base(logger, client, configMapWatcher, namespaceWatcher)
 {
 }
    public static async Task <K8SConfiguration> CreateClusterConfigAsync(this IKubernetes kubernetes, V1ServiceAccount serviceAccount)
    {
        if (kubernetes is null)
        {
            throw new ArgumentNullException(nameof(kubernetes));
        }

        if (serviceAccount is null)
        {
            throw new ArgumentNullException(nameof(serviceAccount));
        }

        var serviceAccountSecret = await serviceAccount.Secrets
                                   .ToAsyncEnumerable()
                                   .SelectAwait(s => new ValueTask <V1Secret>(kubernetes.ReadNamespacedSecretAsync(s.Name, serviceAccount.Namespace())))
                                   .FirstAsync(s => s.Type.Equals("kubernetes.io/service-account-token"))
                                   .ConfigureAwait(false);

        var clusterName    = kubernetes.BaseUri.GetComponents(UriComponents.Host, UriFormat.Unescaped);
        var clusterUser    = serviceAccount.Name();
        var clusterContext = Guid.NewGuid().ToString();

        return(new K8SConfiguration()
        {
            ApiVersion = "v1",
            Kind = "Config",
            Clusters = new Cluster[]
            {
                new Cluster()
                {
                    Name = clusterName,
                    ClusterEndpoint = new ClusterEndpoint()
                    {
                        CertificateAuthorityData = Convert.ToBase64String(serviceAccountSecret.Data["ca.crt"]),
                        Server = kubernetes.BaseUri.ToString().TrimEnd('/')
                    }
                }
            },
            Users = new User[]
            {
                new User()
                {
                    Name = clusterUser,
                    UserCredentials = new UserCredentials()
                    {
                        ClientKeyData = Convert.ToBase64String(serviceAccountSecret.Data["ca.crt"]),
                        Token = Encoding.UTF8.GetString(serviceAccountSecret.Data["token"])
                    }
                }
            },
            Contexts = new Context[]
            {
                new Context()
                {
                    Name = clusterContext,
                    ContextDetails = new ContextDetails()
                    {
                        Cluster = clusterName,
                        Namespace = serviceAccount.Name(),
                        User = clusterUser
                    }
                }
            },
            CurrentContext = clusterContext
        });
    }
Beispiel #8
0
 /// <summary>
 /// Initializes a new <see cref="KubernetesProcess"/>
 /// </summary>
 /// <param name="pod">The managed <see cref="V1Pod"/></param>
 /// <param name="kubernetes">The service used to interact with the Kubernetes API</param>
 public KubernetesProcess(V1Pod pod, IKubernetes kubernetes)
 {
     this.Pod        = pod;
     this.Kubernetes = kubernetes;
 }
Beispiel #9
0
 public AnyResourceKind(IKubernetes kubernetes)
 {
     Client = (k8s.Kubernetes)kubernetes;
 }
Beispiel #10
0
 public ExampleOperator(IKubernetes client, ILogger <Operator <ExampleResource> > logger) : base(client, logger)
 {
 }
Beispiel #11
0
 public AwsAuthConfigMapRepository(IKubernetes client)
 {
     _client = client;
 }
 public SecretWatcher(ILogger <SecretWatcher> logger, IMediator mediator, IKubernetes client,
                      IOptionsMonitor <ReflectorOptions> options) :
     base(logger, mediator, client, options)
 {
 }
 /// <summary>
 /// Initializes a new <see cref="ICustomResourceEventWatcher{TResource}"/>.
 /// </summary>
 /// <param name="logger">The service used to perform logging</param>
 /// <param name="kubernetesClient">The service used to communicate with Kubernetes.</param>
 /// <param name="resourceDefinition">The <see cref="ICustomResourceDefinition"/> of the <see cref="ICustomResource"/> type to to listen the Kubernetes events for.</param>
 /// <param name="namespaceProperty">The namespace in which to listen for Kubernetes events for the specified <see cref="ICustomResource"/> type. If null or empty, the controller will listen for cluster-wide events instead.</param>
 /// <param name="eventHandler">The <see cref="CustomResourceEventDelegate{TResource}"/> to invoke whenever a Kubernetes event for the specified <see cref="ICustomResource"/> type is received.</param>
 public CustomResourceEventWatcher(ILogger <CustomResourceEventWatcher <TResource> > logger, IKubernetes kubernetesClient, ICustomResourceDefinition resourceDefinition, string namespaceProperty, CustomResourceEventDelegate <TResource> eventHandler)
 {
     this.Logger             = logger;
     this.KubernetesClient   = kubernetesClient;
     this.ResourceDefinition = resourceDefinition;
     this.Namespace          = namespaceProperty;
     this.EventHandler       = eventHandler;
 }
 public HomeController(IKubernetes k8sClient, ILogger <HomeController> logger)
 {
     _logger    = logger;
     _k8sClient = k8sClient;
 }
Beispiel #15
0
 internal static async Task <V1ServiceList> GetServicesAsync(this IKubernetes client, string label, List <string> k8sNamespaces, CancellationToken cancellationToken)
 {
     if (k8sNamespaces is null || !k8sNamespaces.Any())
     {
         return(await client.ListServiceForAllNamespacesAsync(labelSelector : label, cancellationToken : cancellationToken));
     }
Beispiel #16
0
 protected override Task <V1Endpoints> ReplaceMetaObjectAsync(IKubernetes client, V1Endpoints obj, string name, string namespaceParameter,
                                                              CancellationToken cancellationToken)
 {
     return(client.ReplaceNamespacedEndpointsAsync(obj, name, namespaceParameter, cancellationToken: cancellationToken));
 }
 public SecretHandler(IKubernetes client, ILogger <K8sOperator> logger)
 {
     _client = client ?? throw new ArgumentNullException(nameof(client));;
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Beispiel #18
0
 public EndpointsLock(IKubernetes client, string @namespace, string name, string identity)
     : base(client, @namespace, name, identity)
 {
 }
Beispiel #19
0
 protected override Task <V1ConfigMap> OnResourceGet(IKubernetes client, string name, string ns)
 {
     return(client.ReadNamespacedConfigMapAsync(name, ns));
 }
Beispiel #20
0
        public static async Task <List <Extensionsv1beta1Ingress> > ListAllIngressAsync(IKubernetes client, string ns, CancellationToken cancellationToken = default)
        {
            var    results           = new List <Extensionsv1beta1Ingress>();
            string continueParameter = null;

            do
            {
                var resp = await client.ListNamespacedIngressAsync(ns, continueParameter : continueParameter, limit : 100, cancellationToken : cancellationToken);

                continueParameter = resp.Metadata.ContinueProperty;
                results.AddRange(resp.Items);
            } while (continueParameter != null);
            return(results);
        }
 public KubeController(IKubernetes client)
 {
     kubeClient = client;
 }
Beispiel #22
0
        /// <summary>
        /// Starts the controller.
        /// </summary>
        /// <param name="k8s">The <see cref="IKubernetes"/> client to use.</param>
        /// <returns>The tracking <see cref="Task"/>.</returns>
        public static async Task StartAsync(IKubernetes k8s)
        {
            Covenant.Requires <ArgumentNullException>(k8s != null, nameof(k8s));

            if (NeonHelper.IsLinux)
            {
                // Ensure that the [/var/run/neonkube/container-registries] folder exists on the node.

                var scriptPath = Path.Combine(Node.HostMount, $"tmp/node-agent-folder-{NeonHelper.CreateBase36Uuid()}.sh");
                var script     =
                    $@"#!/bin/bash

set -euo pipefail

# Ensure that the nodetask runtime folders exist and have the correct permissions.

if [ ! -d {hostNeonRunFolder} ]; then

mkdir -p {hostNeonRunFolder}
chmod 700 {hostNeonRunFolder}
fi

if [ ! -d {hostContainerRegistriesFolder} ]; then

mkdir -p {hostContainerRegistriesFolder}
chmod 700 {hostContainerRegistriesFolder}
fi

# Remove this script.

rm $0
";
                File.WriteAllText(scriptPath, NeonHelper.ToLinuxLineEndings(script));
                try
                {
                    (await Node.BashExecuteCaptureAsync(scriptPath)).EnsureSuccess();
                }
                finally
                {
                    NeonHelper.DeleteFile(scriptPath);
                }
            }

            // Load the configuration settings.

            reloginInterval          = Program.Service.Environment.Get("CONTAINERREGISTRY_RELOGIN_INTERVAL", TimeSpan.FromHours(24));
            reloginMaxRandomInterval = reloginInterval.Divide(4);

            var leaderConfig =
                new LeaderElectionConfig(
                    k8s,
                    @namespace:       KubeNamespace.NeonSystem,
                    leaseName:        $"{Program.Service.Name}.containerregistry-{Node.Name}",
                    identity:         Pod.Name,
                    promotionCounter: Metrics.CreateCounter($"{Program.Service.MetricsPrefix}containerregistry_promoted", "Leader promotions"),
                    demotionCounter:  Metrics.CreateCounter($"{Program.Service.MetricsPrefix}containerregistry_demoted", "Leader demotions"),
                    newLeaderCounter: Metrics.CreateCounter($"{Program.Service.MetricsPrefix}containerregistry_newLeader", "Leadership changes"));

            var options = new ResourceManagerOptions()
            {
                IdleInterval             = Program.Service.Environment.Get("CONTAINERREGISTRY_IDLE_INTERVAL", TimeSpan.FromMinutes(5)),
                ErrorMinRequeueInterval  = Program.Service.Environment.Get("CONTAINERREGISTRY_ERROR_MIN_REQUEUE_INTERVAL", TimeSpan.FromSeconds(15)),
                ErrorMaxRetryInterval    = Program.Service.Environment.Get("CONTAINERREGISTRY_ERROR_MAX_REQUEUE_INTERVAL", TimeSpan.FromSeconds(60)),
                IdleCounter              = Metrics.CreateCounter($"{Program.Service.MetricsPrefix}containerregistry_idle", "IDLE events processed."),
                ReconcileCounter         = Metrics.CreateCounter($"{Program.Service.MetricsPrefix}containerregistry_reconcile", "RECONCILE events processed."),
                DeleteCounter            = Metrics.CreateCounter($"{Program.Service.MetricsPrefix}containerregistry_delete", "DELETED events processed."),
                IdleErrorCounter         = Metrics.CreateCounter($"{Program.Service.MetricsPrefix}containerregistry_idle_error", "Failed NodeTask IDLE event processing."),
                ReconcileErrorCounter    = Metrics.CreateCounter($"{Program.Service.MetricsPrefix}containerregistry_reconcile_error", "Failed NodeTask RECONCILE event processing."),
                DeleteErrorCounter       = Metrics.CreateCounter($"{Program.Service.MetricsPrefix}containerregistry_delete_error", "Failed NodeTask DELETE event processing."),
                StatusModifyErrorCounter = Metrics.CreateCounter($"{Program.Service.MetricsPrefix}containerregistry_statusmodify_error", "Failed NodeTask STATUS-MODIFY events processing.")
            };

            resourceManager = new ResourceManager <V1NeonContainerRegistry, ContainerRegistryController>(
                k8s,
                options:      options,
                leaderConfig: leaderConfig);

            await resourceManager.StartAsync();
        }
Beispiel #23
0
 protected override async Task <HttpOperationResponse <V1SecretList> > OnResourceWatcher(IKubernetes client)
 {
     return(await client.ListSecretForAllNamespacesWithHttpMessagesAsync(watch : true,
                                                                         timeoutSeconds : Requests.DefaultTimeout));
 }
Beispiel #24
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public ContainerRegistryController(IKubernetes k8s)
        {
            Covenant.Requires(k8s != null, nameof(k8s));

            this.k8s = k8s;
        }
Beispiel #25
0
 protected override async Task <IList <V1Secret> > OnResourceList(IKubernetes client, string labelSelector = null,
                                                                  string fieldSelector = null)
 {
     return((await client.ListSecretForAllNamespacesAsync(fieldSelector: fieldSelector,
                                                          labelSelector: labelSelector)).Items);
 }
Beispiel #26
0
 public NotificationHandler(IKubernetes client, IHttpClientFactory httpClientFactory, ILogger <K8sOperator> logger)
 {
     _client            = client ?? throw new ArgumentNullException(nameof(client));
     _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
     _logger            = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Beispiel #27
0
 private static HttpOperationResponse <V1PodList> ExecuteListPods(IKubernetes client)
 {
     return(client.ListNamespacedPodWithHttpMessagesAsync("default").Result);
 }
Beispiel #28
0
 public PodController(IKubernetes k8s)
 {
     this._k8s = k8s;
 }
Beispiel #29
0
 protected MetaObjectAnnotationLock(IKubernetes client, string @namespace, string name, string identity)
     : base(client, @namespace, name, identity)
 {
 }
Beispiel #30
0
 public void Configure(IKubernetes k8s, ILogger logger)
 {
     _k8s    = k8s;
     _logger = logger;
 }