diff --git a/packages/shipa/charts/Chart.lock b/packages/shipa/charts/Chart.lock new file mode 100644 index 000000000..5cb0707d7 --- /dev/null +++ b/packages/shipa/charts/Chart.lock @@ -0,0 +1,9 @@ +dependencies: +- name: mongodb-replicaset + repository: https://charts.helm.sh/stable + version: 3.11.3 +- name: mongodb + repository: https://charts.bitnami.com/bitnami + version: 11.0.5 +digest: sha256:ef0bdb8d615ae2d8929c6533a4c87361bbefd9be924d5ed6464fc18def59d5a4 +generated: "2022-05-23T14:34:19.477817402Z" diff --git a/packages/shipa/charts/Chart.yaml b/packages/shipa/charts/Chart.yaml new file mode 100644 index 000000000..40ec3701c --- /dev/null +++ b/packages/shipa/charts/Chart.yaml @@ -0,0 +1,33 @@ +apiVersion: v2 +appVersion: 1.7.1 +dependencies: +- name: mongodb + repository: file://./charts/mongodb + tags: + - defaultDB +- name: mongodb-replicaset + repository: file://./charts/mongodb-replicaset + tags: + - legacyMongoReplicaset +description: A Helm chart for Kubernetes to install the Shipa Control Plane +kubeVersion: '>= 1.16.0-0' +annotations: + catalog.cattle.io/release-name: shipa + catalog.cattle.io/display-name: Shipa + catalog.cattle.io/namespace: shipa-system + catalog.cattle.io/certified: partner +name: shipa +type: application +home: https://www.shipa.io +icon: https://www.shipa.io/wp-content/uploads/2020/11/Shipa-banner-768x307.png +maintainers: +- email: rlachhman@shipa.io + name: ravi +version: 1.7.1 +keywords: +- shipa +- deployment +- aac +sources: +- https://github.com/shipa-corp +- https://github.com/shipa-corp/helm-chart \ No newline at end of file diff --git a/packages/shipa/charts/LICENSE b/packages/shipa/charts/LICENSE new file mode 100644 index 000000000..dda518917 --- /dev/null +++ b/packages/shipa/charts/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2020, shipa authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + * Neither the name of the Globo.com nor the names of its contributors +may be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/shipa/charts/README.md b/packages/shipa/charts/README.md new file mode 100644 index 000000000..973ece10f --- /dev/null +++ b/packages/shipa/charts/README.md @@ -0,0 +1,136 @@ + +**Note:** The master branch is the main development branch. Please use releases instead of the master branch in order to get stable versions. + +# Documentation + +Documentation for Shipa can be found at + +# Installation Requirements + +1. Kubernetes 1.18 - 1.22. Check out the actual [documentation](https://learn.shipa.io/docs/installation-requirements#kubernetes-clusters) +2. Helm v3 + +# Defaults + +We create LoadBalancer service to expose Shipa to the internet: + +1. 8080 -> shipa api over http +1. 8081 -> shipa api over https + +By default we use dynamic public IP set by a cloud-provider but there is a parameter to use static ip (if you have it): + +```bash +--set shipaCluster.ingress.ip=35.192.15.168 +``` + +# Installation + +Users can install Shipa on any existing Kubernetes cluster, and Shipa leverages Helm charts for the install. + +> ⚠️ NOTE: Installing or upgrading Shipa may require downtime in order to perform database migrations. + +Below are the steps required to have Shipa installed in your existing Kubernetes cluster: + +Create a namespace where the Shipa services should be installed + +```bash +NAMESPACE=shipa-system +kubectl create namespace $NAMESPACE +``` + +Create the values.override.yaml with the Admin user and password that will be used for Shipa + +```bash +cat > values.override.yaml << EOF +auth: + adminUser: + adminPassword: +EOF +``` + +Add Shipa helm repo + +```bash +helm repo add shipa-charts https://shipa-charts.storage.googleapis.com +``` + +Install Shipa + +```bash +helm install shipa shipa-charts/shipa -n $NAMESPACE --create-namespace --timeout=15m -f values.override.yaml +``` + +## Upgrading Shipa Helm chart from 1.6.3 or prior to 1.6.4 or later + +In order to handle migrating the MongoDB database off of the deprecated `stable/mongodb-replicaset` chart, there are extra steps to take in order to upgrade. See the [Upgrading MongoDB notes](./UpgradingMongoDB.md) or look at . + +## Upgrading shipa helm chart + +```bash +helm upgrade shipa . --timeout=15m --namespace=$NAMESPACE -f values.override.yaml +``` + +## Upgrading shipa helm chart if you have Pro license + +We have two general ways how to execute helm upgrade if you have Pro license: + +* Pass a license file to helm upgrade + +```bash +helm upgrade shipa . --timeout=15m --namespace=$NAMESPACE -f values.override.yaml -f license.yaml +``` + +* Merge license key from a license file to values.override.yaml and execute helm upgrade as usual + +```bash +cat license.yaml | grep "license:" >> values.override.yaml +``` + +# CI/CD + +Packaging and signing helm charts is automated using Github Actions + +Charts are uploaded to multiple buckets based on condition: + +1. `shipa-charts-dev`, `push` to `master`, `push` to PR opened against `master` +2. `shipa-charts-cloud`, `tag` containing `cloud` +3. `shipa-charts`, `tag` not containing `cloud` + +Chart name is composed of: +`{last_tag}-{commit_hash}` + +For on-prem releases, if tag is not pre-release, meaning it has semantic versioning without RC suffix (ex. 1.3.0, not 1.3.0-rc1), chart name is only `{last_tag}`, as otherwise it is seen by helm chart as development version + +# Usage + +```bash +# only first time +helm repo add shipa-dev https://shipa-charts-dev.storage.googleapis.com +helm repo add shipa-cloud https://shipa-charts-cloud.storage.googleapis.com +helm repo add shipa-onprem https://shipa-charts.storage.googleapis.com + +# refresh available charts +helm repo update + +# check available versions +helm search repo shipa --versions + +# check available versions with development versions +helm search repo shipa --versions --devel + +# check per repo +helm search repo shipa-dev --versions --devel +helm search repo shipa-cloud --versions --devel +helm search repo shipa-onprem --versions --devel + +# helm install +helm install shipa shipa-dev/shipa --version 1.x.x -n shipa-system --create-namespace --timeout=15m -f values.override.yaml +``` + +# Shipa client + +If you are looking to operate Shipa from your local machine, we have binaries of shipa client: + +# Collaboration/Contributing + +We welcome all feedback or pull requests. If you have any questions feel free to reach us at info@shipa.io diff --git a/packages/shipa/charts/UpgradingMongoDB.md b/packages/shipa/charts/UpgradingMongoDB.md new file mode 100644 index 000000000..4a3c890ff --- /dev/null +++ b/packages/shipa/charts/UpgradingMongoDB.md @@ -0,0 +1,71 @@ +# Upgrade Notes for Upgrading MongoDB Chart + +Notes on upgrading Shipa can also be found at . + +By default, Shipa installs a MongoDB instance within the cluster for demonstration purposes. Ideally, an externally managed MongoDB should be used, but for those who are just trying out Shipa, this is a quick way to get up and running. Older versions of the Shipa Helm Chart installed MongoDB using the stable/mongodb-replicaset dependent chart, however this chart has been deprecated and now the officially recommended chart to use is the one maintained by Bitnami. By default, Shipa will now install MongoDB based on the Bitnami chart, but in an upgrade scenario there may be configuration required in order to proceed. + +## Fresh install + +For a fresh install, using the default values provided in this chart, a MongoDB instance will be created using the Bitnami mongodb chart. + +## Upgrading when previously running MongoDB from stable/mongodb-replicaset chart + +If Shipa was initially installed using Shipa chart version 1.6.3 or prior, there are a few options. + +### Auto-upgrading MongoDB + +The Shipa chart can attempt to automatically upgrade the MongoDB chart if the number of replicas for the MongoDB statefulset is 1 and the name of the persistent volume claim is provided to Shipa. + +### Manual upgrade + +To manually upgrade + +```bash +export MONGO_NAMESPACE="$(kubectl get po -A -l app=mongodb-replicaset -o jsonpath='{.items[0].metadata.namespace}')" +export MONGO_POD="$(kubectl get po -A -l app=mongodb-replicaset -o jsonpath='{.items[0].metadata.name}')" +export MONGO_PVC="$(kubectl get pvc -n ${MONGO_NAMESPACE} -l app=mongodb-replicaset -o jsonpath='{.items[0].metadata.name}')" +export SHIPA_DEPLOYMENT="$(kubectl get deployments.apps -n ${MONGO_NAMESPACE} -l app.kubernetes.io/instance=shipa -o name | grep -e '.*-api$')" +export SHIPA_RELEASE="$(kubectl get deployments.apps -n ${MONGO_NAMESPACE} -l app.kubernetes.io/instance=shipa -o jsonpath='{.items[0].metadata.annotations.meta\.helm\.sh\/release-name}')" + +if [[ -z "${MONGO_NAMESPACE}" || -z "${MONGO_POD}" || -z "${MONGO_PVC}" || -z "${SHIPA_DEPLOYMENT}" || -z "${SHIPA_RELEASE}" ]]; then + echo "[ERROR] Could not pull required cluster information." + exit 1 +fi + +# Stop Shipa API +kubectl scale ${SHIPA_DEPLOYMENT} --replicas=0 -n ${SHIPA_SYSTEM_NAMESPACE} +sleep 15 + +# Export data +kubectl exec -it -n ${MONGO_NAMESPACE} ${MONGO_POD} -c mongodb-replicaset -- mongodump -d shipa --gzip --archive=/tmp/mongobackup.gzip +kubectl cp -n ${MONGO_NAMESPACE} ${MONGO_POD}:/tmp/mongobackup.gzip /tmp/mongobackup.gzip -c mongodb-replicaset +if [[ ! -s /tmp/mongobackup.gzip ]]; then + echo "[ERROR] Backup is missing or empty. Expected locally at /tmp/mongobackup.gzip" + exit 1 +fi +if ! gunzip --test /tmp/mongobackup.gzip; then + echo "[ERROR] Backup appears to be corrupt." + exit 1 +fi + +# Delete mongo components +kubectl delete svc -n ${MONGO_NAMESPACE} -l app=mongodb-replicaset +kubectl delete statefulsets.apps -n ${MONGO_NAMESPACE} -l app=mongodb-replicaset +kubectl delete configmaps -n ${MONGO_NAMESPACE} -l app=mongodb-replicaset +kubectl delete persistentvolumeclaims -n ${MONGO_NAMESPACE} -l app=mongodb-replicaset +sleep 15 + +# Helm upgrade (provide all your override values here) +helm upgrade ${SHIPA_RELEASE} -n ${MONGO_NAMESPACE} --timeout=15m ... + +# Wait for MongoDB to be ready +kubectl wait --for=condition=ready --timeout=5m po -l app.kubernetes.io/name=mongodb -n ${MONGO_NAMESPACE} + +# Import data +export MONGO_POD="$( kubectl get po -n ${MONGO_NAMESPACE} -l app.kubernetes.io/name=mongodb -o jsonpath='{.items[0].metadata.name}')" +kubectl cp -n ${MONGO_NAMESPACE} /tmp/mongobackup.gzip ${MONGO_POD}:/tmp/mongobackup.gzip -c mongodb +kubectl exec -it -n ${SHIPA_SYSTEM_NAMESPACE} ${MONGO_POD} -c mongodb -- mongorestore -d shipa --gzip --archive=/tmp/mongobackup.gzip + +# Restart the Shipa API +kubectl scale ${SHIPA_DEPLOYMENT} --replicas=1 -n ${MONGO_NAMESPACE} +``` diff --git a/packages/shipa/charts/app-readme.md b/packages/shipa/charts/app-readme.md new file mode 100644 index 000000000..700df754a --- /dev/null +++ b/packages/shipa/charts/app-readme.md @@ -0,0 +1,39 @@ +# Shipa + +[Shipa](http://www.shipa.io/) is an Application-as-Code [AaC] provider that is designed for having a cleaner developer experience and allowing for guardrails to be easily created. The "platform engineering dilemma" is how do you allow for innovation yet have control. Shipa is application focused so allowing developers who are not experienced in Kubernetes run through several critical tasks such as deploying, managing, and iterating on their applications without detailed Kubernetes knowledge. From the operator or admin standpoint, easily enforcing rules/convention without building multiple abstraction layers. + +## Install Shipa - Helm Chart + +The [Installation Requirements](https://learn.shipa.io/docs/installation-requirements) specify up to date cluster and ingress requirements. Installing the chart is pretty straight forward. + +Intially will need to set an intial Admin User and Admin Password/Secret to first access Shipa. + +``` +helm repo add shipa-charts https://shipa-charts.storage.googleapis.com + +helm repo update + +helm upgrade --install shipa shipa-charts/shipa \ + +--set auth.adminUser=admin@acme.com --set auth.adminPassword=admin1234 \ + +--namespace shipa-system --create-namespace --timeout=1000s --wait +``` + +## Install Shipa - ClusterIP +Shipa by default will install Traefik as the loadbalencer. +Though if this creates a conflict or there is a cluster limitation, you can also leverage ClusterIP for routing which is the +second set of optional prompts in the Rancher UI. +[Installing Shipa with ClusterIP on K3](https://shipa.io/2021/10/k3d-and-shipa-deploymnet/) + +``` +helm install shipa shipa-charts/shipa -n shipa-system --create-namespace \ +--timeout=15m \ +--set=metrics.image=gcr.io/shipa-1000/metrics:30m \ +--set=auth.adminUser=admin@acme.com \ +--set=auth.adminPassword=admin1234 \ +--set=shipaCluster.serviceType=ClusterIP \ +--set=shipaCluster.ip=10.43.10.20 \ +--set=service.nginx.serviceType=ClusterIP \ +--set=service.nginx.clusterIP=10.43.10.10 +``` \ No newline at end of file diff --git a/packages/shipa/charts/charts/mongodb-replicaset/.helmignore b/packages/shipa/charts/charts/mongodb-replicaset/.helmignore new file mode 100755 index 000000000..28b828e89 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/.helmignore @@ -0,0 +1,22 @@ +# Patterns to ignore when building packages. +# This supports shell glob matching, relative path matching, and +# negation (prefixed with !). Only one pattern per line. +.DS_Store +# Common VCS dirs +.git/ +.gitignore +.bzr/ +.bzrignore +.hg/ +.hgignore +.svn/ +# Common backup files +*.swp +*.bak +*.tmp +*~ +# Various IDEs +.project +.idea/ +*.tmproj +install diff --git a/packages/shipa/charts/charts/mongodb-replicaset/Chart.yaml b/packages/shipa/charts/charts/mongodb-replicaset/Chart.yaml new file mode 100755 index 000000000..9620d643f --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/Chart.yaml @@ -0,0 +1,16 @@ +apiVersion: v1 +appVersion: "3.6" +description: NoSQL document-oriented database that stores JSON-like documents with + dynamic schemas, simplifying the integration of data in content-driven applications. +home: https://github.com/mongodb/mongo +icon: https://webassets.mongodb.com/_com_assets/cms/mongodb-logo-rgb-j6w271g1xn.jpg +maintainers: +- email: unguiculus@gmail.com + name: unguiculus +- email: ssheehy@firescope.com + name: steven-sheehy +name: mongodb-replicaset +sources: +- https://github.com/mongodb/mongo +- https://github.com/percona/mongodb_exporter +version: 3.11.3 diff --git a/packages/shipa/charts/charts/mongodb-replicaset/OWNERS b/packages/shipa/charts/charts/mongodb-replicaset/OWNERS new file mode 100755 index 000000000..1e6a85097 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/OWNERS @@ -0,0 +1,6 @@ +approvers: + - unguiculus + - steven-sheehy +reviewers: + - unguiculus + - steven-sheehy diff --git a/packages/shipa/charts/charts/mongodb-replicaset/README.md b/packages/shipa/charts/charts/mongodb-replicaset/README.md new file mode 100755 index 000000000..c9729c059 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/README.md @@ -0,0 +1,434 @@ +# MongoDB Helm Chart + +## Prerequisites Details + +* Kubernetes 1.9+ +* Kubernetes beta APIs enabled only if `podDisruptionBudget` is enabled +* PV support on the underlying infrastructure + +## StatefulSet Details + +* https://kubernetes.io/docs/concepts/abstractions/controllers/statefulsets/ + +## StatefulSet Caveats + +* https://kubernetes.io/docs/concepts/abstractions/controllers/statefulsets/#limitations + +## Chart Details + +This chart implements a dynamically scalable [MongoDB replica set](https://docs.mongodb.com/manual/tutorial/deploy-replica-set/) +using Kubernetes StatefulSets and Init Containers. + +## Installing the Chart + +To install the chart with the release name `my-release`: + +``` console +helm repo add stable https://kubernetes-charts.storage.googleapis.com/ +helm install --name my-release stable/mongodb-replicaset +``` + +## Configuration + +The following table lists the configurable parameters of the mongodb chart and their default values. + +| Parameter | Description | Default | +| ----------------------------------- | ------------------------------------------------------------------------- | --------------------------------------------------- | +| `replicas` | Number of replicas in the replica set | `3` | +| `replicaSetName` | The name of the replica set | `rs0` | +| `skipInitialization` | If `true` skip replica set initialization during bootstrapping | `false` +| `podDisruptionBudget` | Pod disruption budget | `{}` | +| `port` | MongoDB port | `27017` | +| `imagePullSecrets` | Image pull secrets | `[]` | +| `installImage.repository` | Image name for the install container | `unguiculus/mongodb-install` | +| `installImage.tag` | Image tag for the install container | `0.7` | +| `installImage.pullPolicy` | Image pull policy for the init container that establishes the replica set | `IfNotPresent` | +| `copyConfigImage.repository` | Image name for the copy config init container | `busybox` | +| `copyConfigImage.tag` | Image tag for the copy config init container | `1.29.3` | +| `copyConfigImage.pullPolicy` | Image pull policy for the copy config init container | `IfNotPresent` | +| `image.repository` | MongoDB image name | `mongo` | +| `image.tag` | MongoDB image tag | `3.6` | +| `image.pullPolicy` | MongoDB image pull policy | `IfNotPresent` | +| `podAnnotations` | Annotations to be added to MongoDB pods | `{}` | +| `securityContext.enabled` | Enable security context | `true` | +| `securityContext.fsGroup` | Group ID for the container | `999` | +| `securityContext.runAsUser` | User ID for the container | `999` | +| `securityContext.runAsNonRoot` | | `true` | +| `resources` | Pod resource requests and limits | `{}` | +| `persistentVolume.enabled` | If `true`, persistent volume claims are created | `true` | +| `persistentVolume.storageClass` | Persistent volume storage class | `` | +| `persistentVolume.accessModes` | Persistent volume access modes | `[ReadWriteOnce]` | +| `persistentVolume.size` | Persistent volume size | `10Gi` | +| `persistentVolume.annotations` | Persistent volume annotations | `{}` | +| `terminationGracePeriodSeconds` | Duration in seconds the pod needs to terminate gracefully | `30` | +| `tls.enabled` | Enable MongoDB TLS support including authentication | `false` | +| `tls.mode` | Set the SSL operation mode (disabled, allowSSL, preferSSL, requireSSL) | `requireSSL` | +| `tls.cacert` | The CA certificate used for the members | Our self signed CA certificate | +| `tls.cakey` | The CA key used for the members | Our key for the self signed CA certificate | +| `init.resources` | Pod resource requests and limits (for init containers) | `{}` | +| `init.timeout` | The amount of time in seconds to wait for bootstrap to finish | `900` | +| `metrics.enabled` | Enable Prometheus compatible metrics for pods and replicasets | `false` | +| `metrics.image.repository` | Image name for metrics exporter | `bitnami/mongodb-exporter` | +| `metrics.image.tag` | Image tag for metrics exporter | `0.9.0-debian-9-r2` | +| `metrics.image.pullPolicy` | Image pull policy for metrics exporter | `IfNotPresent` | +| `metrics.port` | Port for metrics exporter | `9216` | +| `metrics.path` | URL Path to expose metics | `/metrics` | +| `metrics.resources` | Metrics pod resource requests and limits | `{}` | +| `metrics.securityContext.enabled` | Enable security context | `true` | +| `metrics.securityContext.fsGroup` | Group ID for the metrics container | `1001` | +| `metrics.securityContext.runAsUser` | User ID for the metrics container | `1001` | +| `metrics.socketTimeout` | Time to wait for a non-responding socket | `3s` | +| `metrics.syncTimeout` | Time an operation with this session will wait before returning an error | `1m` | +| `metrics.prometheusServiceDiscovery`| Adds annotations for Prometheus ServiceDiscovery | `true` | +| `auth.enabled` | If `true`, keyfile access control is enabled | `false` | +| `auth.key` | Key for internal authentication | `` | +| `auth.existingKeySecret` | If set, an existing secret with this name for the key is used | `` | +| `auth.adminUser` | MongoDB admin user | `` | +| `auth.adminPassword` | MongoDB admin password | `` | +| `auth.metricsUser` | MongoDB clusterMonitor user | `` | +| `auth.metricsPassword` | MongoDB clusterMonitor password | `` | +| `auth.existingMetricsSecret` | If set, and existing secret with this name is used for the metrics user | `` | +| `auth.existingAdminSecret` | If set, and existing secret with this name is used for the admin user | `` | +| `serviceAnnotations` | Annotations to be added to the service | `{}` | +| `configmap` | Content of the MongoDB config file | `` | +| `initMongodStandalone` | If set, initContainer executes script in standalone mode | `` | +| `nodeSelector` | Node labels for pod assignment | `{}` | +| `affinity` | Node/pod affinities | `{}` | +| `tolerations` | List of node taints to tolerate | `[]` | +| `priorityClassName` | Pod priority class name | `` | +| `livenessProbe.failureThreshold` | Liveness probe failure threshold | `3` | +| `livenessProbe.initialDelaySeconds` | Liveness probe initial delay seconds | `30` | +| `livenessProbe.periodSeconds` | Liveness probe period seconds | `10` | +| `livenessProbe.successThreshold` | Liveness probe success threshold | `1` | +| `livenessProbe.timeoutSeconds` | Liveness probe timeout seconds | `5` | +| `readinessProbe.failureThreshold` | Readiness probe failure threshold | `3` | +| `readinessProbe.initialDelaySeconds`| Readiness probe initial delay seconds | `5` | +| `readinessProbe.periodSeconds` | Readiness probe period seconds | `10` | +| `readinessProbe.successThreshold` | Readiness probe success threshold | `1` | +| `readinessProbe.timeoutSeconds` | Readiness probe timeout seconds | `1` | +| `extraVars` | Set environment variables for the main container | `{}` | +| `extraLabels` | Additional labels to add to resources | `{}` | + +*MongoDB config file* + +All options that depended on the chart configuration are supplied as command-line arguments to `mongod`. By default, the chart creates an empty config file. Entries may be added via the `configmap` configuration value. + +Specify each parameter using the `--set key=value[,key=value]` argument to `helm install`. + +Alternatively, a YAML file that specifies the values for the parameters can be provided while installing the chart. For example, + +``` console +helm install --name my-release -f values.yaml stable/mongodb-replicaset +``` + +> **Tip**: You can use the default [values.yaml](values.yaml) + +Once you have all 3 nodes in running, you can run the "test.sh" script in this directory, which will insert a key into the primary and check the secondaries for output. This script requires that the `$RELEASE_NAME` environment variable be set, in order to access the pods. + +## Authentication + +By default, this chart creates a MongoDB replica set without authentication. Authentication can be +enabled using the parameter `auth.enabled`. Once enabled, keyfile access control is set up and an +admin user with root privileges is created. User credentials and keyfile may be specified directly. +Alternatively, existing secrets may be provided. The secret for the admin user must contain the +keys `user` and `password`, that for the key file must contain `key.txt`. The user is created with +full `root` permissions but is restricted to the `admin` database for security purposes. It can be +used to create additional users with more specific permissions. + +To connect to the mongo shell with authentication enabled, use a command similar to the following (substituting values as appropriate): + +```shell +kubectl exec -it mongodb-replicaset-0 -- mongo mydb -u admin -p password --authenticationDatabase admin +``` + +## TLS support + +To enable full TLS encryption set `tls.enabled` to `true`. It is recommended to create your own CA by executing: + +```console +openssl genrsa -out ca.key 2048 +openssl req -x509 -new -nodes -key ca.key -days 10000 -out ca.crt -subj "/CN=mydomain.com" +``` + +After that paste the base64 encoded (`cat ca.key | base64 -w0`) cert and key into the fields `tls.cacert` and +`tls.cakey`. Adapt the configmap for the replicaset as follows: + +```yml +configmap: + storage: + dbPath: /data/db + net: + port: 27017 + ssl: + mode: requireSSL + CAFile: /data/configdb/tls.crt + PEMKeyFile: /work-dir/mongo.pem + # Set to false to require mutual TLS encryption + allowConnectionsWithoutCertificates: true + replication: + replSetName: rs0 + security: + authorization: enabled + # # Uncomment to enable mutual TLS encryption + # clusterAuthMode: x509 + keyFile: /keydir/key.txt +``` + +To access the cluster you need one of the certificates generated during cluster setup in `/work-dir/mongo.pem` of the +certain container or you generate your own one via: + +```console +$ cat >openssl.cnf < mongo.pem +$ rm mongo.key mongo.crt +``` + +Please ensure that you exchange the `$HOSTNAME` with your actual hostname and the `$HOSTNAME1`, `$HOSTNAME2`, etc. with +alternative hostnames you want to allow access to the MongoDB replicaset. You should now be able to authenticate to the +mongodb with your `mongo.pem` certificate: + +```console +mongo --ssl --sslCAFile=ca.crt --sslPEMKeyFile=mongo.pem --eval "db.adminCommand('ping')" +``` + +## Promethus metrics + +Enabling the metrics as follows will allow for each replicaset pod to export Prometheus compatible metrics +on server status, individual replicaset information, replication oplogs, and storage engine. + +```yaml +metrics: + enabled: true + image: + repository: ssalaues/mongodb-exporter + tag: 0.6.1 + pullPolicy: IfNotPresent + port: 9216 + path: "/metrics" + socketTimeout: 3s + syncTimeout: 1m + prometheusServiceDiscovery: true + resources: {} +``` + +More information on [MongoDB Exporter](https://github.com/percona/mongodb_exporter) metrics available. + +## Deep dive + +Because the pod names are dependent on the name chosen for it, the following examples use the +environment variable `RELEASENAME`. For example, if the helm release name is `messy-hydra`, one would need to set the following before proceeding. The example scripts below assume 3 pods only. + +```console +export RELEASE_NAME=messy-hydra +``` + +### Cluster Health + +```console +for i in 0 1 2; do kubectl exec $RELEASE_NAME-mongodb-replicaset-$i -- sh -c 'mongo --eval="printjson(db.serverStatus())"'; done +``` + +### Failover + +One can check the roles being played by each node by using the following: + +```console +$ for i in 0 1 2; do kubectl exec $RELEASE_NAME-mongodb-replicaset-$i -- sh -c 'mongo --eval="printjson(rs.isMaster())"'; done + +MongoDB shell version: 3.6.3 +connecting to: mongodb://127.0.0.1:27017 +MongoDB server version: 3.6.3 +{ + "hosts" : [ + "messy-hydra-mongodb-0.messy-hydra-mongodb.default.svc.cluster.local:27017", + "messy-hydra-mongodb-1.messy-hydra-mongodb.default.svc.cluster.local:27017", + "messy-hydra-mongodb-2.messy-hydra-mongodb.default.svc.cluster.local:27017" + ], + "setName" : "rs0", + "setVersion" : 3, + "ismaster" : true, + "secondary" : false, + "primary" : "messy-hydra-mongodb-0.messy-hydra-mongodb.default.svc.cluster.local:27017", + "me" : "messy-hydra-mongodb-0.messy-hydra-mongodb.default.svc.cluster.local:27017", + "electionId" : ObjectId("7fffffff0000000000000001"), + "maxBsonObjectSize" : 16777216, + "maxMessageSizeBytes" : 48000000, + "maxWriteBatchSize" : 1000, + "localTime" : ISODate("2016-09-13T01:10:12.680Z"), + "maxWireVersion" : 4, + "minWireVersion" : 0, + "ok" : 1 +} +``` + +This lets us see which member is primary. + +Let us now test persistence and failover. First, we insert a key (in the below example, we assume pod 0 is the master): + +```console +$ kubectl exec $RELEASE_NAME-mongodb-replicaset-0 -- mongo --eval="printjson(db.test.insert({key1: 'value1'}))" + +MongoDB shell version: 3.6.3 +connecting to: mongodb://127.0.0.1:27017 +{ "nInserted" : 1 } +``` + +Watch existing members: + +```console +$ kubectl run --attach bbox --image=mongo:3.6 --restart=Never --env="RELEASE_NAME=$RELEASE_NAME" -- sh -c 'while true; do for i in 0 1 2; do echo $RELEASE_NAME-mongodb-replicaset-$i $(mongo --host=$RELEASE_NAME-mongodb-replicaset-$i.$RELEASE_NAME-mongodb-replicaset --eval="printjson(rs.isMaster())" | grep primary); sleep 1; done; done'; + +Waiting for pod default/bbox2 to be running, status is Pending, pod ready: false +If you don't see a command prompt, try pressing enter. +messy-hydra-mongodb-2 "primary" : "messy-hydra-mongodb-0.messy-hydra-mongodb.default.svc.cluster.local:27017", +messy-hydra-mongodb-0 "primary" : "messy-hydra-mongodb-0.messy-hydra-mongodb.default.svc.cluster.local:27017", +messy-hydra-mongodb-1 "primary" : "messy-hydra-mongodb-0.messy-hydra-mongodb.default.svc.cluster.local:27017", +messy-hydra-mongodb-2 "primary" : "messy-hydra-mongodb-0.messy-hydra-mongodb.default.svc.cluster.local:27017", +messy-hydra-mongodb-0 "primary" : "messy-hydra-mongodb-0.messy-hydra-mongodb.default.svc.cluster.local:27017", + +``` + +Kill the primary and watch as a new master getting elected. + +```console +$ kubectl delete pod $RELEASE_NAME-mongodb-replicaset-0 + +pod "messy-hydra-mongodb-0" deleted +``` + +Delete all pods and let the statefulset controller bring it up. + +```console +$ kubectl delete po -l "app=mongodb-replicaset,release=$RELEASE_NAME" +$ kubectl get po --watch-only +NAME READY STATUS RESTARTS AGE +messy-hydra-mongodb-0 0/1 Pending 0 0s +messy-hydra-mongodb-0 0/1 Pending 0 0s +messy-hydra-mongodb-0 0/1 Pending 0 7s +messy-hydra-mongodb-0 0/1 Init:0/2 0 7s +messy-hydra-mongodb-0 0/1 Init:1/2 0 27s +messy-hydra-mongodb-0 0/1 Init:1/2 0 28s +messy-hydra-mongodb-0 0/1 PodInitializing 0 31s +messy-hydra-mongodb-0 0/1 Running 0 32s +messy-hydra-mongodb-0 1/1 Running 0 37s +messy-hydra-mongodb-1 0/1 Pending 0 0s +messy-hydra-mongodb-1 0/1 Pending 0 0s +messy-hydra-mongodb-1 0/1 Init:0/2 0 0s +messy-hydra-mongodb-1 0/1 Init:1/2 0 20s +messy-hydra-mongodb-1 0/1 Init:1/2 0 21s +messy-hydra-mongodb-1 0/1 PodInitializing 0 24s +messy-hydra-mongodb-1 0/1 Running 0 25s +messy-hydra-mongodb-1 1/1 Running 0 30s +messy-hydra-mongodb-2 0/1 Pending 0 0s +messy-hydra-mongodb-2 0/1 Pending 0 0s +messy-hydra-mongodb-2 0/1 Init:0/2 0 0s +messy-hydra-mongodb-2 0/1 Init:1/2 0 21s +messy-hydra-mongodb-2 0/1 Init:1/2 0 22s +messy-hydra-mongodb-2 0/1 PodInitializing 0 25s +messy-hydra-mongodb-2 0/1 Running 0 26s +messy-hydra-mongodb-2 1/1 Running 0 30s + + +... +messy-hydra-mongodb-0 "primary" : "messy-hydra-mongodb-0.messy-hydra-mongodb.default.svc.cluster.local:27017", +messy-hydra-mongodb-1 "primary" : "messy-hydra-mongodb-0.messy-hydra-mongodb.default.svc.cluster.local:27017", +messy-hydra-mongodb-2 "primary" : "messy-hydra-mongodb-0.messy-hydra-mongodb.default.svc.cluster.local:27017", +``` + +Check the previously inserted key: + +```console +$ kubectl exec $RELEASE_NAME-mongodb-replicaset-1 -- mongo --eval="rs.slaveOk(); db.test.find({key1:{\$exists:true}}).forEach(printjson)" + +MongoDB shell version: 3.6.3 +connecting to: mongodb://127.0.0.1:27017 +{ "_id" : ObjectId("57b180b1a7311d08f2bfb617"), "key1" : "value1" } +``` + +### Scaling + +Scaling should be managed by `helm upgrade`, which is the recommended way. + +### Indexes and Maintenance + +You can run Mongo in standalone mode and execute Javascript code on each replica at initContainer time using `initMongodStandalone`. +This allows you to create indexes on replicasets following [best practices](https://docs.mongodb.com/manual/tutorial/build-indexes-on-replica-sets/). + +#### Example: Creating Indexes + +```js +initMongodStandalone: |+ + db = db.getSiblingDB("mydb") + db.my_users.createIndex({email: 1}) +``` + +Tail the logs to debug running indexes or to follow their progress + +```sh +kubectl exec -it $RELEASE-mongodb-replicaset-0 -c bootstrap -- tail -f /work-dir/log.txt +``` + +### Migrate existing ReplicaSets into Kubernetes +If you have an existing ReplicaSet that currently is deployed outside of Kubernetes and want to move it into a cluster you can do so by using the `skipInitialization` flag. + +First set the `skipInitialization` variable to `true` in values.yaml and install the Helm chart. That way you end up with uninitialized MongoDB pods that can be added to the existing ReplicaSet. + +Now take care of realizing the DNS correct resolution of all ReplicaSet members. In Kubernetes you can for example use an `ExternalName`. + +``` +apiVersion: v1 +kind: Service +metadata: + name: mongodb01 + namespace: mongo +spec: + type: ExternalName + externalName: mongodb01.mydomain.com +``` + +If you also put each StatefulSet member behind a loadbalancer the ReplicaSet members outside of the cluster will also be able to reach the pods inside the cluster. + +``` +apiVersion: v1 +kind: Service +metadata: + name: mongodb-0 + namespace: mongo +spec: + selector: + statefulset.kubernetes.io/pod-name: mongodb-0 + ports: + - port: 27017 + targetPort: 27017 + type: LoadBalancer +``` + +Now all that is left to do is to put the LoadBalancer IP into the `/etc/hosts` file (or realize the DNS resolution through another way) +``` +1.2.3.4 mongodb-0 +5.6.7.8 mongodb-1 +``` + +With a setup like this each replicaset member can resolve the DNS entry of each other and you can just add the new pods to your existing MongoDB cluster as if they where just normal nodes. + +Of course you need to make sure to get your security settings right. Enforced TLS is a good idea in a setup like this. Also make sure that you activate auth and get the firewall settings right. + +Once you fully migrated remove the old nodes from the replicaset. diff --git a/packages/shipa/charts/charts/mongodb-replicaset/ci/default-values.yaml b/packages/shipa/charts/charts/mongodb-replicaset/ci/default-values.yaml new file mode 100755 index 000000000..a8bad27cd --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/ci/default-values.yaml @@ -0,0 +1 @@ +# No config change. Just use defaults. diff --git a/packages/shipa/charts/charts/mongodb-replicaset/ci/metrics-values.yaml b/packages/shipa/charts/charts/mongodb-replicaset/ci/metrics-values.yaml new file mode 100755 index 000000000..df64aca1e --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/ci/metrics-values.yaml @@ -0,0 +1,10 @@ +auth: + enabled: true + adminUser: username + adminPassword: password + metricsUser: metrics + metricsPassword: password + key: keycontent + +metrics: + enabled: true diff --git a/packages/shipa/charts/charts/mongodb-replicaset/ci/tls-values.yaml b/packages/shipa/charts/charts/mongodb-replicaset/ci/tls-values.yaml new file mode 100755 index 000000000..043d7ac0c --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/ci/tls-values.yaml @@ -0,0 +1,10 @@ +tls: + # Enable or disable MongoDB TLS support + enabled: true + # Please generate your own TLS CA by generating it via: + # $ openssl genrsa -out ca.key 2048 + # $ openssl req -x509 -new -nodes -key ca.key -days 10000 -out ca.crt -subj "/CN=mydomain.com" + # After that you can base64 encode it and paste it here: + # $ cat ca.key | base64 -w0 + cacert: "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUNxakNDQVpJQ0NRQ1I1aXNNQlRmQzdUQU5CZ2txaGtpRzl3MEJBUXNGQURBWE1SVXdFd1lEVlFRRERBeHQKZVdSdmJXRnBiaTVqYjIwd0hoY05NVGt4TVRFeU1EZ3hOakUwV2hjTk5EY3dNek13TURneE5qRTBXakFYTVJVdwpFd1lEVlFRRERBeHRlV1J2YldGcGJpNWpiMjB3Z2dFaU1BMEdDU3FHU0liM0RRRUJBUVVBQTRJQkR3QXdnZ0VLCkFvSUJBUUNwM0UrdVpWanhaY3BYNUFCbEtRa2crZjFmSnJzR1JJNVQrMzcyMkIvYnRyTVo4M3FyRTg2RFdEYXEKN0k1YTdlOGFVTGt2ZVpsaW02aWxsUW5CTHJPVUtVZ3R1OWZINlZydlBuMTl3UDFibEMvU0NWZHoxemNSUWlJWQpOMVVWN2VGaWUzdjhiNXVRM2RFcVBPV2FMM0w2N0Q1T0lDb043Z21QL2QwVVBaWjNHdDJLNTZsNXBzY1h4OGYwCkd3ZWdSRGpiVnZmc2dUSW50dEJ6SGh6c0JENUxON054aDd5RWVacW5admtuTDg5S2JZUEFPUk82N3NKUlBhWHMKUDhuVDhqalFJaGlRSUZDNTVXN3JrZ1hid1Znajdwb0kyby9XSDM4WXZ6TG1OVnMyOThYUDZmUXhCQ0NwMmFjRgpkOTVQRjZmbFVJeW9RNGRuOUF5UlpRa0owdlpMQWdNQkFBRXdEUVlKS29aSWh2Y05BUUVMQlFBRGdnRUJBS21XCjY2SlB4V0E4MVlYTEZtclFrdmM2NE9ycFJXTHJtNHFqaFREREtvVzY1V291MzNyOEVVQktzQ2FQOHNWWXhobFQKaWhGcDhIemNqTXpWRjFqU3ZiT0c5UnhrSG16ZEIvL3FwMDdTVFp0S2R1cThad2RVdnh1Z1FXSFNzOHA4YVNHUAowNDlkSDBqUnpEZklyVGp4Z3ZNOUJlWmorTkdqT1FyUGRvQVBKeTl2THowZmYya1gzVjJadTFDWnNnbDNWUXFsCjRsNzB3azFuVk5tTXY4Nnl5cUZXaWFRTWhuSXFjKzBwYUJaRjJFSGNpSExuZWcweVVTZVN4REsrUkk4SE9mT3oKNVFpUHpqSGs1b3czd252NDhQWVJMODdLTWJtRzF0eThyRHMxUlVGWkZueGxHd0t4UmRmckt3aHJJbVRBT2N4Vwo5bVhCU3ZzY3RjM2tIZTRIVFdRPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==" + cakey: "LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFb3dJQkFBS0NBUUVBcWR4UHJtVlk4V1hLVitRQVpTa0pJUG45WHlhN0JrU09VL3QrOXRnZjI3YXpHZk42CnF4UE9nMWcycXV5T1d1M3ZHbEM1TDNtWllwdW9wWlVKd1M2emxDbElMYnZYeCtsYTd6NTlmY0Q5VzVRdjBnbFgKYzljM0VVSWlHRGRWRmUzaFludDcvRytia04zUktqemxtaTl5K3V3K1RpQXFEZTRKai8zZEZEMldkeHJkaXVlcAplYWJIRjhmSDlCc0hvRVE0MjFiMzdJRXlKN2JRY3g0YzdBUStTemV6Y1llOGhIbWFwMmI1SnkvUFNtMkR3RGtUCnV1N0NVVDJsN0QvSjAvSTQwQ0lZa0NCUXVlVnU2NUlGMjhGWUkrNmFDTnFQMWg5L0dMOHk1alZiTnZmRnorbjAKTVFRZ3FkbW5CWGZlVHhlbjVWQ01xRU9IWi9RTWtXVUpDZEwyU3dJREFRQUJBb0lCQVFDVWM3eWNBVzFMaEpmawpXcHRSemh4eFdxcnJSeEU3ZUIwZ0h2UW16bHFCanRwVyt1bWhyT3pXOC9qTFIzVmUyUVlZYktaOGJIejJwbTR0ClVPVTJsaGRTalFYTkdwZUsyMUtqTjIwN3c3aHFHa2YwL0Q4WE9lZWh5TGU5akZacmxQeGZNdWI0aDU1aGJNdUsKYTdDTElaOE8xL3ZZRWRwUFZGTzlLYlRYSk1CbEZJUERUaFJvR2RCTEFkREZNbzcrUnZYSFRUcXdyWmxDbWRDbgp5eld3WkhIQUZhdEdGWU9ybXcxdlZZY3h0OXk5c0FVZDBrVTQza05jVHVHR0MwMGh1QlZMcW9JZU9mMG12TDB0Ckg0S0d6LzBicGp4NFpoWlNKazd3ZkFsQ0xGL1N5YzVJOEJXWWNCb05Jc0RSbDdDUmpDVUoxYVNBNVNYNzZ2SVoKSlhnRWEyV3hBb0dCQU50M0pDRGtycjNXRmJ3cW1SZ2ZhUVV0UE1FVnZlVnJvQmRqZTBZVFFNbENlNTV2QU1uNQpadEFKQTVKTmxKN2VZRkVEa0JrVURJSDFDM3hlZHVWbEREWXpESzRpR0V1Wk8wVDNERFN3aks2cExsZ3JBN0QyCmZnS29ubVdGck5JdTI4UW1MNHhmcjUrWW9SNUo0L05QdFdWOWwwZk1NOHEwSTd5SVRNODlsZWlqQW9HQkFNWWoKTHk3VER1MWVJVWkrQXJFNTJFMEkwTVJPNWNLS2hxdGxJMnpCZkZlWm5LYWdwbnhCMTMxbi9wcGg0Wm1IYnMzZQpxOXBSb0RJT0h4cm5NOWFCa1JBTHJHNjBMeXF3eU5NNW1JemkvQytJK2RVOG55ZXIvZVNNRTNtdlFzbmpVcEhtClRtTjRrM0l4RWtqRnhCazVndFNlNlA5U0UyOFd6eVZoOGlkZHRjNDVBb0dBYzcwWFBvbWJaZDM3UkdxcXBrQWEKWUhLRThjY0hpSEFEMDVIUk54bDhOeWRxamhrNEwwdnAzcGlDVzZ1eVR6NHpTVVk1dmlBR29KcWNYaEJyWDNxMAp2L2lZSFZVNXZ0U21ueTR5TDY5VDRlQ3k0aWg5SDl3K2hDUnN0Rm1VMUp1RnBxSUV2V0RRKzdmQWNIckRUbE9nCjlFOFJjdm5MN29DbHdBMlpoRW1VUDBVQ2dZQWFhdUtGbWJwcHg1MGtkOEVnSkJoRTNTSUlxb1JUMWVoeXZiOWwKWnI3UFp6bk50YW04ODRKcHhBM2NRNlN5dGEzK1lPd0U1ZEU0RzAzbVptRXcvb0Y2NURPUFp4TEszRnRLWG1tSwpqMUVVZld6aUUzMGM2ditsRTFBZGIxSzJYRXJNRFNyeWRFY2tlSXA1alhUQjhEc1RZa1NxbGlUbE1PTlpscCtVCnhCZlRjUUtCZ0RoZHo4VjU1TzdNc0dyRVlQeGhoK0U0bklLb3BRc0RlNi9QdWRRVlJMRlNwVGpLNWlKcTF2RnIKajFyNDFCNFp0cjBYNGd6MzhrSUpwZGNvNUFxU25zVENreHhnYXh3RTNzVmlqNGZZRWlteDc3TS84VkZVbDZwLwphNmdBbFh2WHFaYmFvTGU3ekM2RXVZWjFtUzJGMVd4UE9KRzZpakFiMVNIQjVPOGFWdFR3Ci0tLS0tRU5EIFJTQSBQUklWQVRFIEtFWS0tLS0tCg==" diff --git a/packages/shipa/charts/charts/mongodb-replicaset/init/on-start.sh b/packages/shipa/charts/charts/mongodb-replicaset/init/on-start.sh new file mode 100755 index 000000000..12ac89364 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/init/on-start.sh @@ -0,0 +1,226 @@ +#!/usr/bin/env bash + +# Copyright 2018 The Kubernetes Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -e pipefail + +port=27017 +replica_set="$REPLICA_SET" +script_name=${0##*/} +SECONDS=0 +timeout="${TIMEOUT:-900}" +tls_mode="${TLS_MODE}" + +if [[ "$AUTH" == "true" ]]; then + admin_user="$ADMIN_USER" + admin_password="$ADMIN_PASSWORD" + admin_creds=(-u "$admin_user" -p "$admin_password") + if [[ "$METRICS" == "true" ]]; then + metrics_user="$METRICS_USER" + metrics_password="$METRICS_PASSWORD" + fi + auth_args=("--auth" "--keyFile=/data/configdb/key.txt") +fi + +log() { + local msg="$1" + local timestamp + timestamp=$(date --iso-8601=ns) + echo "[$timestamp] [$script_name] $msg" 2>&1 | tee -a /work-dir/log.txt 1>&2 +} + +retry_until() { + local host="${1}" + local command="${2}" + local expected="${3}" + local creds=("${admin_creds[@]}") + + # Don't need credentials for admin user creation and pings that run on localhost + if [[ "${host}" =~ ^localhost ]]; then + creds=() + fi + + until [[ $(mongo admin --host "${host}" "${creds[@]}" "${ssl_args[@]}" --quiet --eval "${command}" | tail -n1) == "${expected}" ]]; do + sleep 1 + + if (! ps "${pid}" &>/dev/null); then + log "mongod shutdown unexpectedly" + exit 1 + fi + if [[ "${SECONDS}" -ge "${timeout}" ]]; then + log "Timed out after ${timeout}s attempting to bootstrap mongod" + exit 1 + fi + + log "Retrying ${command} on ${host}" + done +} + +shutdown_mongo() { + local host="${1:-localhost}" + local args='force: true' + log "Shutting down MongoDB ($args)..." + if (! mongo admin --host "${host}" "${admin_creds[@]}" "${ssl_args[@]}" --eval "db.shutdownServer({$args})"); then + log "db.shutdownServer() failed, sending the terminate signal" + kill -TERM "${pid}" + fi +} + +init_mongod_standalone() { + if [[ ! -f /init/initMongodStandalone.js ]]; then + log "Skipping init mongod standalone script" + return 0 + elif [[ -z "$(ls -1A /data/db)" ]]; then + log "mongod standalone script currently not supported on initial install" + return 0 + fi + + local port="27018" + log "Starting a MongoDB instance as standalone..." + mongod --config /data/configdb/mongod.conf --dbpath=/data/db "${auth_args[@]}" "${ssl_server_args[@]}" --port "${port}" --bind_ip=0.0.0.0 2>&1 | tee -a /work-dir/log.txt 1>&2 & + export pid=$! + trap shutdown_mongo EXIT + log "Waiting for MongoDB to be ready..." + retry_until "localhost:${port}" "db.adminCommand('ping').ok" "1" + log "Running init js script on standalone mongod" + mongo admin --port "${port}" "${admin_creds[@]}" "${ssl_args[@]}" /init/initMongodStandalone.js + shutdown_mongo "localhost:${port}" +} + +my_hostname=$(hostname) +log "Bootstrapping MongoDB replica set member: $my_hostname" + +log "Reading standard input..." +while read -ra line; do + if [[ "${line}" == *"${my_hostname}"* ]]; then + service_name="$line" + fi + peers=("${peers[@]}" "$line") +done + +# Generate the ca cert +ca_crt=/data/configdb/tls.crt +if [ -f "$ca_crt" ]; then + log "Generating certificate" + ca_key=/data/configdb/tls.key + pem=/work-dir/mongo.pem + ssl_args=(--ssl --sslCAFile "$ca_crt" --sslPEMKeyFile "$pem") + ssl_server_args=(--sslMode "$tls_mode" --sslCAFile "$ca_crt" --sslPEMKeyFile "$pem") + +# Move into /work-dir +pushd /work-dir + +cat >openssl.cnf < $pem + rm mongo.key mongo.crt +fi + +init_mongod_standalone + +if [[ "${SKIP_INIT}" == "true" ]]; then + log "Skipping initialization" + exit 0 +fi + +log "Peers: ${peers[*]}" +log "Starting a MongoDB replica" +mongod --config /data/configdb/mongod.conf --dbpath=/data/db --replSet="$replica_set" --port="${port}" "${auth_args[@]}" "${ssl_server_args[@]}" --bind_ip=0.0.0.0 2>&1 | tee -a /work-dir/log.txt 1>&2 & +pid=$! +trap shutdown_mongo EXIT + +log "Waiting for MongoDB to be ready..." +retry_until "localhost" "db.adminCommand('ping').ok" "1" +log "Initialized." + +# try to find a master +for peer in "${peers[@]}"; do + log "Checking if ${peer} is primary" + # Check rs.status() first since it could be in primary catch up mode which db.isMaster() doesn't show + if [[ $(mongo admin --host "${peer}" "${admin_creds[@]}" "${ssl_args[@]}" --quiet --eval "rs.status().myState") == "1" ]]; then + retry_until "${peer}" "db.isMaster().ismaster" "true" + log "Found primary: ${peer}" + primary="${peer}" + break + fi +done + +if [[ "${primary}" = "${service_name}" ]]; then + log "This replica is already PRIMARY" +elif [[ -n "${primary}" ]]; then + if [[ $(mongo admin --host "${primary}" "${admin_creds[@]}" "${ssl_args[@]}" --quiet --eval "rs.conf().members.findIndex(m => m.host == '${service_name}:${port}')") == "-1" ]]; then + log "Adding myself (${service_name}) to replica set..." + if (mongo admin --host "${primary}" "${admin_creds[@]}" "${ssl_args[@]}" --eval "rs.add('${service_name}')" | grep 'Quorum check failed'); then + log 'Quorum check failed, unable to join replicaset. Exiting prematurely.' + exit 1 + fi + fi + + sleep 3 + log 'Waiting for replica to reach SECONDARY state...' + retry_until "${service_name}" "rs.status().myState" "2" + log '✓ Replica reached SECONDARY state.' + +elif (mongo "${ssl_args[@]}" --eval "rs.status()" | grep "no replset config has been received"); then + log "Initiating a new replica set with myself ($service_name)..." + mongo "${ssl_args[@]}" --eval "rs.initiate({'_id': '$replica_set', 'members': [{'_id': 0, 'host': '$service_name'}]})" + + sleep 3 + log 'Waiting for replica to reach PRIMARY state...' + retry_until "localhost" "db.isMaster().ismaster" "true" + primary="${service_name}" + log '✓ Replica reached PRIMARY state.' + + if [[ "${AUTH}" == "true" ]]; then + log "Creating admin user..." + mongo admin "${ssl_args[@]}" --eval "db.createUser({user: '${admin_user}', pwd: '${admin_password}', roles: [{role: 'root', db: 'admin'}]})" + fi +fi + +# User creation +if [[ -n "${primary}" && "$AUTH" == "true" && "$METRICS" == "true" ]]; then + metric_user_count=$(mongo admin --host "${primary}" "${admin_creds[@]}" "${ssl_args[@]}" --eval "db.system.users.find({user: '${metrics_user}'}).count()" --quiet) + if [[ "${metric_user_count}" == "0" ]]; then + log "Creating clusterMonitor user..." + mongo admin --host "${primary}" "${admin_creds[@]}" "${ssl_args[@]}" --eval "db.createUser({user: '${metrics_user}', pwd: '${metrics_password}', roles: [{role: 'clusterMonitor', db: 'admin'}, {role: 'read', db: 'local'}]})" + fi +fi + +log "MongoDB bootstrap complete" +exit 0 + diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/NOTES.txt b/packages/shipa/charts/charts/mongodb-replicaset/templates/NOTES.txt new file mode 100755 index 000000000..2d942592e --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/NOTES.txt @@ -0,0 +1,14 @@ +1. After the statefulset is created completely, one can check which instance is primary by running: + + $ for ((i = 0; i < {{ .Values.replicas }}; ++i)); do kubectl exec --namespace {{ .Release.Namespace }} {{ template "mongodb-replicaset.fullname" . }}-$i -- sh -c 'mongo --eval="printjson(rs.isMaster())"'; done + +2. One can insert a key into the primary instance of the mongodb replica set by running the following: + MASTER_POD_NAME must be replaced with the name of the master found from the previous step. + + $ kubectl exec --namespace {{ .Release.Namespace }} MASTER_POD_NAME -- mongo --eval="printjson(db.test.insert({key1: 'value1'}))" + +3. One can fetch the keys stored in the primary or any of the slave nodes in the following manner. + POD_NAME must be replaced by the name of the pod being queried. + + $ kubectl exec --namespace {{ .Release.Namespace }} POD_NAME -- mongo --eval="rs.slaveOk(); db.test.find().forEach(printjson)" + diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/_helpers.tpl b/packages/shipa/charts/charts/mongodb-replicaset/templates/_helpers.tpl new file mode 100755 index 000000000..223ec6604 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/_helpers.tpl @@ -0,0 +1,78 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Expand the name of the chart. +*/}} +{{- define "mongodb-replicaset.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* +Create a default fully qualified app name. +We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). +If release name contains chart name it will be used as a full name. +*/}} +{{- define "mongodb-replicaset.fullname" -}} +{{- if .Values.fullnameOverride -}} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- $name := default .Chart.Name .Values.nameOverride -}} +{{- if contains $name .Release.Name -}} +{{- .Release.Name | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "mongodb-replicaset.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* +Create the name for the admin secret. +*/}} +{{- define "mongodb-replicaset.adminSecret" -}} + {{- if .Values.auth.existingAdminSecret -}} + {{- .Values.auth.existingAdminSecret -}} + {{- else -}} + {{- template "mongodb-replicaset.fullname" . -}}-admin + {{- end -}} +{{- end -}} + +{{- define "mongodb-replicaset.metricsSecret" -}} + {{- if .Values.auth.existingMetricsSecret -}} + {{- .Values.auth.existingMetricsSecret -}} + {{- else -}} + {{- template "mongodb-replicaset.fullname" . -}}-metrics + {{- end -}} +{{- end -}} + + +{{/* +Create the name for the key secret. +*/}} +{{- define "mongodb-replicaset.keySecret" -}} + {{- if .Values.auth.existingKeySecret -}} + {{- .Values.auth.existingKeySecret -}} + {{- else -}} + {{- template "mongodb-replicaset.fullname" . -}}-keyfile + {{- end -}} +{{- end -}} + +{{- define "mongodb-replicaset.connection-string" -}} + {{- $string := "" -}} + {{- if .Values.auth.enabled }} + {{- $string = printf "mongodb://$METRICS_USER:$METRICS_PASSWORD@localhost:%s" (.Values.port|toString) -}} + {{- else -}} + {{- $string = printf "mongodb://localhost:%s" (.Values.port|toString) -}} + {{- end -}} + + {{- if .Values.tls.enabled }} + {{- printf "%s?ssl=true&tlsCertificateKeyFile=/work-dir/mongo.pem&tlsCAFile=/ca/tls.crt" $string -}} + {{- else -}} + {{- printf $string -}} + {{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-admin-secret.yaml b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-admin-secret.yaml new file mode 100755 index 000000000..311f2e0e4 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-admin-secret.yaml @@ -0,0 +1,18 @@ +{{- if and (.Values.auth.enabled) (not .Values.auth.existingAdminSecret) -}} +apiVersion: v1 +kind: Secret +metadata: + labels: + app: {{ template "mongodb-replicaset.name" . }} + chart: {{ template "mongodb-replicaset.chart" . }} + heritage: {{ .Release.Service }} + release: {{ .Release.Name }} +{{- if .Values.extraLabels }} +{{ toYaml .Values.extraLabels | indent 4 }} +{{- end }} + name: {{ template "mongodb-replicaset.adminSecret" . }} +type: Opaque +data: + user: {{ .Values.auth.adminUser | b64enc }} + password: {{ .Values.auth.adminPassword | b64enc }} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-ca-secret.yaml b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-ca-secret.yaml new file mode 100755 index 000000000..03762529c --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-ca-secret.yaml @@ -0,0 +1,18 @@ +{{- if .Values.tls.enabled -}} +apiVersion: v1 +kind: Secret +type: kubernetes.io/tls +metadata: + labels: + app: {{ template "mongodb-replicaset.name" . }} + chart: {{ template "mongodb-replicaset.chart" . }} + heritage: {{ .Release.Service }} + release: {{ .Release.Name }} +{{- if .Values.extraLabels }} +{{ toYaml .Values.extraLabels | indent 4 }} +{{- end }} + name: {{ template "mongodb-replicaset.fullname" . }}-ca +data: + tls.key: {{ .Values.tls.cakey }} + tls.crt: {{ .Values.tls.cacert }} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-init-configmap.yaml b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-init-configmap.yaml new file mode 100755 index 000000000..8f5ba0db5 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-init-configmap.yaml @@ -0,0 +1,20 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + labels: + app: {{ template "mongodb-replicaset.name" . }} + chart: {{ template "mongodb-replicaset.chart" . }} + heritage: {{ .Release.Service }} + release: {{ .Release.Name }} +{{- if .Values.extraLabels }} +{{ toYaml .Values.extraLabels | indent 4 }} +{{- end }} + name: {{ template "mongodb-replicaset.fullname" . }}-init +data: + on-start.sh: | +{{ .Files.Get "init/on-start.sh" | indent 4 }} +{{- if .Values.initMongodStandalone }} + initMongodStandalone.js: | +{{ .Values.initMongodStandalone | indent 4 }} +{{- end }} + diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-keyfile-secret.yaml b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-keyfile-secret.yaml new file mode 100755 index 000000000..5e0513ebb --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-keyfile-secret.yaml @@ -0,0 +1,17 @@ +{{- if and (.Values.auth.enabled) (not .Values.auth.existingKeySecret) -}} +apiVersion: v1 +kind: Secret +metadata: + labels: + app: {{ template "mongodb-replicaset.name" . }} + chart: {{ template "mongodb-replicaset.chart" . }} + heritage: {{ .Release.Service }} + release: {{ .Release.Name }} +{{- if .Values.extraLabels }} +{{ toYaml .Values.extraLabels | indent 4 }} +{{- end }} + name: {{ template "mongodb-replicaset.keySecret" . }} +type: Opaque +data: + key.txt: {{ .Values.auth.key | b64enc }} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-metrics-secret.yaml b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-metrics-secret.yaml new file mode 100755 index 000000000..c1484481e --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-metrics-secret.yaml @@ -0,0 +1,18 @@ +{{- if and (.Values.auth.enabled) (not .Values.auth.existingMetricsSecret) (.Values.metrics.enabled) -}} +apiVersion: v1 +kind: Secret +metadata: + labels: + app: {{ template "mongodb-replicaset.name" . }} + chart: {{ template "mongodb-replicaset.chart" . }} + heritage: {{ .Release.Service }} + release: {{ .Release.Name }} +{{- if .Values.extraLabels }} +{{ toYaml .Values.extraLabels | indent 4 }} +{{- end }} + name: {{ template "mongodb-replicaset.metricsSecret" . }} +type: Opaque +data: + user: {{ .Values.auth.metricsUser | b64enc }} + password: {{ .Values.auth.metricsPassword | b64enc }} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-mongodb-configmap.yaml b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-mongodb-configmap.yaml new file mode 100755 index 000000000..eec20b991 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-mongodb-configmap.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + labels: + app: {{ template "mongodb-replicaset.name" . }} + chart: {{ template "mongodb-replicaset.chart" . }} + heritage: {{ .Release.Service }} + release: {{ .Release.Name }} +{{- if .Values.extraLabels }} +{{ toYaml .Values.extraLabels | indent 4 }} +{{- end }} + name: {{ template "mongodb-replicaset.fullname" . }}-mongodb +data: + mongod.conf: | +{{ toYaml .Values.configmap | indent 4 }} diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-poddisruptionbudget.yaml b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-poddisruptionbudget.yaml new file mode 100755 index 000000000..6768aa3b0 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-poddisruptionbudget.yaml @@ -0,0 +1,20 @@ +{{- if .Values.podDisruptionBudget -}} +apiVersion: policy/v1beta1 +kind: PodDisruptionBudget +metadata: + labels: + app: {{ template "mongodb-replicaset.name" . }} + chart: {{ template "mongodb-replicaset.chart" . }} + heritage: {{ .Release.Service }} + release: {{ .Release.Name }} +{{- if .Values.extraLabels }} +{{ toYaml .Values.extraLabels | indent 4 }} +{{- end }} + name: {{ template "mongodb-replicaset.fullname" . }} +spec: + selector: + matchLabels: + app: {{ template "mongodb-replicaset.name" . }} + release: {{ .Release.Name }} +{{ toYaml .Values.podDisruptionBudget | indent 2 }} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-service-client.yaml b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-service-client.yaml new file mode 100755 index 000000000..3982aae4c --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-service-client.yaml @@ -0,0 +1,32 @@ +# A headless service for client applications to use +apiVersion: v1 +kind: Service +metadata: + annotations: + {{- if .Values.serviceAnnotations }} +{{ toYaml .Values.serviceAnnotations | indent 4 }} + {{- end }} + labels: + app: {{ template "mongodb-replicaset.name" . }} + chart: {{ template "mongodb-replicaset.chart" . }} + heritage: {{ .Release.Service }} + release: {{ .Release.Name }} +{{- if .Values.extraLabels }} +{{ toYaml .Values.extraLabels | indent 4 }} +{{- end }} + name: {{ template "mongodb-replicaset.fullname" . }}-client +spec: + type: ClusterIP + clusterIP: None + ports: + - name: mongodb + port: {{ .Values.port }} +{{- if .Values.metrics.enabled }} + - name: metrics + port: {{ .Values.metrics.port }} + targetPort: metrics +{{- end }} + selector: + app: {{ template "mongodb-replicaset.name" . }} + release: {{ .Release.Name }} + diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-service.yaml b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-service.yaml new file mode 100755 index 000000000..99748a668 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-service.yaml @@ -0,0 +1,25 @@ +# A headless service to create DNS records for discovery purposes. Use the -client service to connect applications +apiVersion: v1 +kind: Service +metadata: + annotations: + service.alpha.kubernetes.io/tolerate-unready-endpoints: "true" + labels: + app: {{ template "mongodb-replicaset.name" . }} + chart: {{ template "mongodb-replicaset.chart" . }} + heritage: {{ .Release.Service }} + release: {{ .Release.Name }} +{{- if .Values.extraLabels }} +{{ toYaml .Values.extraLabels | indent 4 }} +{{- end }} + name: {{ template "mongodb-replicaset.fullname" . }} +spec: + type: ClusterIP + clusterIP: None + ports: + - name: mongodb + port: {{ .Values.port }} + publishNotReadyAddresses: true + selector: + app: {{ template "mongodb-replicaset.name" . }} + release: {{ .Release.Name }} diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-statefulset.yaml b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-statefulset.yaml new file mode 100755 index 000000000..60c043aa6 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/mongodb-statefulset.yaml @@ -0,0 +1,354 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + labels: + app: {{ template "mongodb-replicaset.name" . }} + chart: {{ template "mongodb-replicaset.chart" . }} + heritage: {{ .Release.Service }} + release: {{ .Release.Name }} +{{- if .Values.extraLabels }} +{{ toYaml .Values.extraLabels | indent 4 }} +{{- end }} + name: {{ template "mongodb-replicaset.fullname" . }} +spec: + selector: + matchLabels: + app: {{ template "mongodb-replicaset.name" . }} + release: {{ .Release.Name }} + serviceName: {{ template "mongodb-replicaset.fullname" . }} + replicas: {{ .Values.replicas }} + template: + metadata: + labels: + app: {{ template "mongodb-replicaset.name" . }} + release: {{ .Release.Name }} +{{- if .Values.extraLabels }} +{{ toYaml .Values.extraLabels | indent 8 }} +{{- end }} + annotations: + checksum/config: {{ include (print $.Template.BasePath "/mongodb-mongodb-configmap.yaml") . | sha256sum }} + {{- if and (.Values.metrics.prometheusServiceDiscovery) (.Values.metrics.enabled) }} + prometheus.io/scrape: "true" + prometheus.io/port: {{ .Values.metrics.port | quote }} + prometheus.io/path: {{ .Values.metrics.path | quote }} + {{- end }} + {{- if .Values.podAnnotations }} +{{ toYaml .Values.podAnnotations | indent 8 }} + {{- end }} + spec: + {{- if .Values.priorityClassName }} + priorityClassName: {{ .Values.priorityClassName }} + {{- end }} + {{- if .Values.imagePullSecrets }} + imagePullSecrets: + {{- range .Values.imagePullSecrets }} + - name: {{ . }} + {{- end}} + {{- end }} + {{- if .Values.securityContext.enabled }} + securityContext: + runAsUser: {{ .Values.securityContext.runAsUser }} + fsGroup: {{ .Values.securityContext.fsGroup }} + runAsNonRoot: {{ .Values.securityContext.runAsNonRoot }} + {{- end }} + terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }} + initContainers: + - name: copy-config + image: "{{ .Values.copyConfigImage.repository }}:{{ .Values.copyConfigImage.tag }}" + imagePullPolicy: {{ .Values.copyConfigImage.pullPolicy | quote }} + command: + - "sh" + args: + - "-c" + - | + set -e + set -x + + cp /configdb-readonly/mongod.conf /data/configdb/mongod.conf + + {{- if .Values.tls.enabled }} + cp /ca-readonly/tls.key /data/configdb/tls.key + cp /ca-readonly/tls.crt /data/configdb/tls.crt + {{- end }} + + {{- if .Values.auth.enabled }} + cp /keydir-readonly/key.txt /data/configdb/key.txt + chmod 600 /data/configdb/key.txt + {{- end }} + volumeMounts: + - name: workdir + mountPath: /work-dir + - name: config + mountPath: /configdb-readonly + - name: configdir + mountPath: /data/configdb + {{- if .Values.tls.enabled }} + - name: ca + mountPath: /ca-readonly + {{- end }} + {{- if .Values.auth.enabled }} + - name: keydir + mountPath: /keydir-readonly + {{- end }} + resources: +{{ toYaml .Values.init.resources | indent 12 }} + - name: install + image: "{{ .Values.installImage.repository }}:{{ .Values.installImage.tag }}" + args: + - --work-dir=/work-dir + imagePullPolicy: "{{ .Values.installImage.pullPolicy }}" + volumeMounts: + - name: workdir + mountPath: /work-dir + resources: +{{ toYaml .Values.init.resources | indent 12 }} + - name: bootstrap + image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" + command: + - /work-dir/peer-finder + args: + - -on-start=/init/on-start.sh + - "-service={{ template "mongodb-replicaset.fullname" . }}" + imagePullPolicy: "{{ .Values.image.pullPolicy }}" + env: + - name: POD_NAMESPACE + valueFrom: + fieldRef: + apiVersion: v1 + fieldPath: metadata.namespace + - name: REPLICA_SET + value: {{ .Values.replicaSetName }} + - name: TIMEOUT + value: "{{ .Values.init.timeout }}" + - name: SKIP_INIT + value: "{{ .Values.skipInitialization }}" + - name: TLS_MODE + value: {{ .Values.tls.mode }} + {{- if .Values.auth.enabled }} + - name: AUTH + value: "true" + - name: ADMIN_USER + valueFrom: + secretKeyRef: + name: "{{ template "mongodb-replicaset.adminSecret" . }}" + key: user + - name: ADMIN_PASSWORD + valueFrom: + secretKeyRef: + name: "{{ template "mongodb-replicaset.adminSecret" . }}" + key: password + {{- if .Values.metrics.enabled }} + - name: METRICS + value: "true" + - name: METRICS_USER + valueFrom: + secretKeyRef: + name: "{{ template "mongodb-replicaset.metricsSecret" . }}" + key: user + - name: METRICS_PASSWORD + valueFrom: + secretKeyRef: + name: "{{ template "mongodb-replicaset.metricsSecret" . }}" + key: password + {{- end }} + {{- end }} + volumeMounts: + - name: workdir + mountPath: /work-dir + - name: init + mountPath: /init + - name: configdir + mountPath: /data/configdb + - name: datadir + mountPath: /data/db + resources: +{{ toYaml .Values.init.resources | indent 12 }} + containers: + - name: {{ template "mongodb-replicaset.name" . }} + image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" + imagePullPolicy: "{{ .Values.image.pullPolicy }}" + {{- if .Values.extraVars }} + env: +{{ toYaml .Values.extraVars | indent 12 }} + {{- end }} + ports: + - name: mongodb + containerPort: 27017 + resources: +{{ toYaml .Values.resources | indent 12 }} + command: + - mongod + args: + - --config=/data/configdb/mongod.conf + - --dbpath=/data/db + - --replSet={{ .Values.replicaSetName }} + - --port=27017 + - --bind_ip=0.0.0.0 + {{- if .Values.auth.enabled }} + - --auth + - --keyFile=/data/configdb/key.txt + {{- end }} + {{- if .Values.tls.enabled }} + - --sslMode={{ .Values.tls.mode }} + - --sslCAFile=/data/configdb/tls.crt + - --sslPEMKeyFile=/work-dir/mongo.pem + {{- end }} + livenessProbe: + exec: + command: + - mongo + {{- if .Values.tls.enabled }} + - --ssl + - --sslCAFile=/data/configdb/tls.crt + - --sslPEMKeyFile=/work-dir/mongo.pem + {{- end }} + - --eval + - "db.adminCommand('ping')" + initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }} + timeoutSeconds: {{ .Values.livenessProbe.timeoutSeconds }} + failureThreshold: {{ .Values.livenessProbe.failureThreshold }} + periodSeconds: {{ .Values.livenessProbe.periodSeconds }} + successThreshold: {{ .Values.livenessProbe.successThreshold }} + readinessProbe: + exec: + command: + - mongo + {{- if .Values.tls.enabled }} + - --ssl + - --sslCAFile=/data/configdb/tls.crt + - --sslPEMKeyFile=/work-dir/mongo.pem + {{- end }} + - --eval + - "db.adminCommand('ping')" + initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }} + timeoutSeconds: {{ .Values.readinessProbe.timeoutSeconds }} + failureThreshold: {{ .Values.readinessProbe.failureThreshold }} + periodSeconds: {{ .Values.readinessProbe.periodSeconds }} + successThreshold: {{ .Values.readinessProbe.successThreshold }} + volumeMounts: + - name: datadir + mountPath: /data/db + - name: configdir + mountPath: /data/configdb + - name: workdir + mountPath: /work-dir +{{ if .Values.metrics.enabled }} + - name: metrics + image: "{{ .Values.metrics.image.repository }}:{{ .Values.metrics.image.tag }}" + imagePullPolicy: {{ .Values.metrics.image.pullPolicy | quote }} + command: + - sh + - -c + - >- + /bin/mongodb_exporter + --mongodb.uri {{ template "mongodb-replicaset.connection-string" . }} + --mongodb.socket-timeout={{ .Values.metrics.socketTimeout }} + --mongodb.sync-timeout={{ .Values.metrics.syncTimeout }} + --web.telemetry-path={{ .Values.metrics.path }} + --web.listen-address=:{{ .Values.metrics.port }} + volumeMounts: + {{- if and (.Values.tls.enabled) }} + - name: ca + mountPath: /ca + readOnly: true + {{- end }} + - name: workdir + mountPath: /work-dir + readOnly: true + env: + {{- if .Values.auth.enabled }} + - name: METRICS_USER + valueFrom: + secretKeyRef: + name: "{{ template "mongodb-replicaset.metricsSecret" . }}" + key: user + - name: METRICS_PASSWORD + valueFrom: + secretKeyRef: + name: "{{ template "mongodb-replicaset.metricsSecret" . }}" + key: password + {{- end }} + ports: + - name: metrics + containerPort: {{ .Values.metrics.port }} + resources: +{{ toYaml .Values.metrics.resources | indent 12 }} + {{- if .Values.metrics.securityContext.enabled }} + securityContext: + runAsUser: {{ .Values.metrics.securityContext.runAsUser }} + {{- end }} + livenessProbe: + exec: + command: + - sh + - -c + - >- + /bin/mongodb_exporter + --mongodb.uri {{ template "mongodb-replicaset.connection-string" . }} + --test + initialDelaySeconds: 30 + periodSeconds: 10 +{{ end }} + {{- with .Values.nodeSelector }} + nodeSelector: +{{ toYaml . | indent 8 }} + {{- end }} + {{- with .Values.affinity }} + affinity: +{{ toYaml . | indent 8 }} + {{- end }} + {{- with .Values.tolerations }} + tolerations: +{{ toYaml . | indent 8 }} + {{- end }} + volumes: + - name: config + configMap: + name: {{ template "mongodb-replicaset.fullname" . }}-mongodb + - name: init + configMap: + defaultMode: 0755 + name: {{ template "mongodb-replicaset.fullname" . }}-init + {{- if .Values.tls.enabled }} + - name: ca + secret: + defaultMode: 0400 + secretName: {{ template "mongodb-replicaset.fullname" . }}-ca + {{- end }} + {{- if .Values.auth.enabled }} + - name: keydir + secret: + defaultMode: 0400 + secretName: {{ template "mongodb-replicaset.keySecret" . }} + {{- end }} + - name: workdir + emptyDir: {} + - name: configdir + emptyDir: {} +{{- if .Values.persistentVolume.enabled }} + volumeClaimTemplates: + - metadata: + name: datadir + annotations: + {{- range $key, $value := .Values.persistentVolume.annotations }} + {{ $key }}: "{{ $value }}" + {{- end }} + spec: + accessModes: + {{- range .Values.persistentVolume.accessModes }} + - {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.persistentVolume.size | quote }} + {{- if .Values.persistentVolume.storageClass }} + {{- if (eq "-" .Values.persistentVolume.storageClass) }} + storageClassName: "" + {{- else }} + storageClassName: "{{ .Values.persistentVolume.storageClass }}" + {{- end }} + {{- end }} +{{- else }} + - name: datadir + emptyDir: {} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/tests/mongodb-up-test-configmap.yaml b/packages/shipa/charts/charts/mongodb-replicaset/templates/tests/mongodb-up-test-configmap.yaml new file mode 100755 index 000000000..45854201a --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/tests/mongodb-up-test-configmap.yaml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + labels: + app: {{ template "mongodb-replicaset.name" . }} + chart: {{ .Chart.Name }}-{{ .Chart.Version }} + heritage: {{ .Release.Service }} + release: {{ .Release.Name }} + name: {{ template "mongodb-replicaset.fullname" . }}-tests +data: + mongodb-up-test.sh: | +{{ .Files.Get "tests/mongodb-up-test.sh" | indent 4 }} diff --git a/packages/shipa/charts/charts/mongodb-replicaset/templates/tests/mongodb-up-test-pod.yaml b/packages/shipa/charts/charts/mongodb-replicaset/templates/tests/mongodb-up-test-pod.yaml new file mode 100755 index 000000000..3e213a680 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/templates/tests/mongodb-up-test-pod.yaml @@ -0,0 +1,79 @@ +apiVersion: v1 +kind: Pod +metadata: + labels: + app: {{ template "mongodb-replicaset.name" . }} + chart: {{ .Chart.Name }}-{{ .Chart.Version }} + heritage: {{ .Release.Service }} + release: {{ .Release.Name }} + name: {{ template "mongodb-replicaset.fullname" . }}-test + annotations: + "helm.sh/hook": test-success +spec: + initContainers: + - name: test-framework + image: dduportal/bats:0.4.0 + command: + - bash + - -c + - | + set -ex + # copy bats to tools dir + cp -R /usr/local/libexec/ /tools/bats/ + volumeMounts: + - name: tools + mountPath: /tools + containers: + - name: mongo + image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" + command: + - /tools/bats/bats + - -t + - /tests/mongodb-up-test.sh + env: + - name: FULL_NAME + value: {{ template "mongodb-replicaset.fullname" . }} + - name: NAMESPACE + value: {{ .Release.Namespace }} + - name: REPLICAS + value: "{{ .Values.replicas }}" + {{- if .Values.auth.enabled }} + - name: AUTH + value: "true" + - name: ADMIN_USER + valueFrom: + secretKeyRef: + name: "{{ template "mongodb-replicaset.adminSecret" . }}" + key: user + - name: ADMIN_PASSWORD + valueFrom: + secretKeyRef: + name: "{{ template "mongodb-replicaset.adminSecret" . }}" + key: password + {{- end }} + volumeMounts: + - name: tools + mountPath: /tools + - name: tests + mountPath: /tests + {{- if .Values.tls.enabled }} + - name: tls + mountPath: /tls + {{- end }} + volumes: + - name: tools + emptyDir: {} + - name: tests + configMap: + name: {{ template "mongodb-replicaset.fullname" . }}-tests + {{- if .Values.tls.enabled }} + - name: tls + secret: + secretName: {{ template "mongodb-replicaset.fullname" . }}-ca + items: + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key + {{- end }} + restartPolicy: Never diff --git a/packages/shipa/charts/charts/mongodb-replicaset/test.sh b/packages/shipa/charts/charts/mongodb-replicaset/test.sh new file mode 100755 index 000000000..0b7fd767b --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/test.sh @@ -0,0 +1,48 @@ +#! /bin/bash + +# Copyright 2016 The Kubernetes Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +NS="${RELEASE_NAMESPACE:-default}" +POD_NAME="${RELEASE_NAME:-mongo}-mongodb-replicaset" + +MONGOCACRT=/ca/tls.crt +MONGOPEM=/work-dir/mongo.pem +if [ -f $MONGOPEM ]; then + MONGOARGS="--ssl --sslCAFile $MONGOCACRT --sslPEMKeyFile $MONGOPEM" +fi + +for i in $(seq 0 2); do + pod="${POD_NAME}-$i" + kubectl exec --namespace $NS $pod -- sh -c 'mongo '"$MONGOARGS"' --eval="printjson(rs.isMaster())"' | grep '"ismaster" : true' + + if [ $? -eq 0 ]; then + echo "Found master: $pod" + MASTER=$pod + break + fi +done + +kubectl exec --namespace $NS $MASTER -- mongo "$MONGOARGS" --eval='printjson(db.test.insert({"status": "success"}))' + +# TODO: find maximum duration to wait for slaves to be up-to-date with master. +sleep 2 + +for i in $(seq 0 2); do + pod="${POD_NAME}-$i" + if [[ $pod != $MASTER ]]; then + echo "Reading from slave: $pod" + kubectl exec --namespace $NS $pod -- mongo "$MONGOARGS" --eval='rs.slaveOk(); db.test.find().forEach(printjson)' + fi +done diff --git a/packages/shipa/charts/charts/mongodb-replicaset/tests/mongodb-up-test.sh b/packages/shipa/charts/charts/mongodb-replicaset/tests/mongodb-up-test.sh new file mode 100755 index 000000000..9998719f4 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/tests/mongodb-up-test.sh @@ -0,0 +1,120 @@ +#!/usr/bin/env bash + +set -ex + +CACRT_FILE=/work-dir/tls.crt +CAKEY_FILE=/work-dir/tls.key +MONGOPEM=/work-dir/mongo.pem + +MONGOARGS="--quiet" + +if [ -e "/tls/tls.crt" ]; then + # log "Generating certificate" + mkdir -p /work-dir + cp /tls/tls.crt /work-dir/tls.crt + cp /tls/tls.key /work-dir/tls.key + + # Move into /work-dir + pushd /work-dir + +cat >openssl.cnf < $MONGOPEM + MONGOARGS="$MONGOARGS --ssl --sslCAFile $CACRT_FILE --sslPEMKeyFile $MONGOPEM" +fi + +if [[ "${AUTH}" == "true" ]]; then + MONGOARGS="$MONGOARGS --username $ADMIN_USER --password $ADMIN_PASSWORD --authenticationDatabase admin" +fi + +pod_name() { + local full_name="${FULL_NAME?Environment variable FULL_NAME not set}" + local namespace="${NAMESPACE?Environment variable NAMESPACE not set}" + local index="$1" + echo "$full_name-$index.$full_name.$namespace.svc.cluster.local" +} + +replicas() { + echo "${REPLICAS?Environment variable REPLICAS not set}" +} + +master_pod() { + for ((i = 0; i < $(replicas); ++i)); do + response=$(mongo $MONGOARGS "--host=$(pod_name "$i")" "--eval=rs.isMaster().ismaster") + if [[ "$response" == "true" ]]; then + pod_name "$i" + break + fi + done +} + +setup() { + local ready=0 + until [[ "$ready" -eq $(replicas) ]]; do + echo "Waiting for application to become ready" >&2 + sleep 1 + + for ((i = 0; i < $(replicas); ++i)); do + response=$(mongo $MONGOARGS "--host=$(pod_name "$i")" "--eval=rs.status().ok" || true) + if [[ "$response" -eq 1 ]]; then + ready=$((ready + 1)) + fi + done + done +} + +@test "Testing mongodb client is executable" { + mongo -h + [ "$?" -eq 0 ] +} + +@test "Connect mongodb client to mongodb pods" { + for ((i = 0; i < $(replicas); ++i)); do + response=$(mongo $MONGOARGS "--host=$(pod_name "$i")" "--eval=rs.status().ok") + if [[ ! "$response" -eq 1 ]]; then + exit 1 + fi + done +} + +@test "Write key to primary" { + response=$(mongo $MONGOARGS --host=$(master_pod) "--eval=db.test.insert({\"abc\": \"def\"}).nInserted") + if [[ ! "$response" -eq 1 ]]; then + exit 1 + fi +} + +@test "Read key from slaves" { + # wait for slaves to catch up + sleep 10 + + for ((i = 0; i < $(replicas); ++i)); do + response=$(mongo $MONGOARGS --host=$(pod_name "$i") "--eval=rs.slaveOk(); db.test.find({\"abc\":\"def\"})") + if [[ ! "$response" =~ .*def.* ]]; then + exit 1 + fi + done + + # Clean up a document after test + mongo $MONGOARGS --host=$(master_pod) "--eval=db.test.deleteMany({\"abc\": \"def\"})" +} diff --git a/packages/shipa/charts/charts/mongodb-replicaset/values.yaml b/packages/shipa/charts/charts/mongodb-replicaset/values.yaml new file mode 100755 index 000000000..7e750af0e --- /dev/null +++ b/packages/shipa/charts/charts/mongodb-replicaset/values.yaml @@ -0,0 +1,167 @@ +# Override the name of the chart, which in turn changes the name of the containers, services etc. +nameOverride: "" +fullnameOverride: "" + +replicas: 3 +port: 27017 + +## Setting this will skip the replicaset and user creation process during bootstrapping +skipInitialization: false + +replicaSetName: rs0 + +podDisruptionBudget: {} + # maxUnavailable: 1 + # minAvailable: 2 + +auth: + enabled: false + existingKeySecret: "" + existingAdminSecret: "" + existingMetricsSecret: "" + # adminUser: username + # adminPassword: password + # metricsUser: metrics + # metricsPassword: password + # key: keycontent + +## Optionally specify an array of imagePullSecrets. +## Secrets must be manually created in the namespace. +## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/ +## +imagePullSecrets: [] +# - myRegistrKeySecretName + +# Specs for the Docker image for the init container that establishes the replica set +installImage: + repository: unguiculus/mongodb-install + tag: 0.7 + pullPolicy: IfNotPresent + +# Specs for the Docker image for the copyConfig init container +copyConfigImage: + repository: busybox + tag: 1.29.3 + pullPolicy: IfNotPresent + +# Specs for the MongoDB image +image: + repository: mongo + tag: 3.6 + pullPolicy: IfNotPresent + +# Additional environment variables to be set in the container +extraVars: {} +# - name: TCMALLOC_AGGRESSIVE_DECOMMIT +# value: "true" + +# Prometheus Metrics Exporter +metrics: + enabled: false + image: + repository: bitnami/mongodb-exporter + tag: 0.10.0-debian-9-r71 + pullPolicy: IfNotPresent + port: 9216 + path: "/metrics" + socketTimeout: 3s + syncTimeout: 1m + prometheusServiceDiscovery: true + resources: {} + securityContext: + enabled: true + runAsUser: 1001 + +# Annotations to be added to MongoDB pods +podAnnotations: {} + +securityContext: + enabled: true + runAsUser: 999 + fsGroup: 999 + runAsNonRoot: true + +init: + resources: {} + timeout: 900 + +resources: {} +# limits: +# cpu: 500m +# memory: 512Mi +# requests: +# cpu: 100m +# memory: 256Mi + +## Node selector +## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodeselector +nodeSelector: {} + +affinity: {} + +tolerations: [] + +extraLabels: {} + +priorityClassName: "" + +persistentVolume: + enabled: true + ## mongodb-replicaset data Persistent Volume Storage Class + ## If defined, storageClassName: + ## If set to "-", storageClassName: "", which disables dynamic provisioning + ## If undefined (the default) or set to null, no storageClassName spec is + ## set, choosing the default provisioner. (gp2 on AWS, standard on + ## GKE, AWS & OpenStack) + ## + storageClass: "" + accessModes: + - ReadWriteOnce + size: 10Gi + annotations: {} + +# Annotations to be added to the service +serviceAnnotations: {} + +terminationGracePeriodSeconds: 30 + +tls: + # Enable or disable MongoDB TLS support + enabled: false + # Set the SSL operation mode (disabled|allowSSL|preferSSL|requireSSL) + mode: requireSSL + # Please generate your own TLS CA by generating it via: + # $ openssl genrsa -out ca.key 2048 + # $ openssl req -x509 -new -nodes -key ca.key -days 10000 -out ca.crt -subj "/CN=mydomain.com" + # After that you can base64 encode it and paste it here: + # $ cat ca.key | base64 -w0 + # cacert: + # cakey: + +# Entries for the MongoDB config file +configmap: {} + +# Javascript code to execute on each replica at initContainer time +# This is the recommended way to create indexes on replicasets. +# Below is an example that creates indexes in foreground on each replica in standalone mode. +# ref: https://docs.mongodb.com/manual/tutorial/build-indexes-on-replica-sets/ +# initMongodStandalone: |+ +# db = db.getSiblingDB("mydb") +# db.my_users.createIndex({email: 1}) +initMongodStandalone: "" + +# Readiness probe +readinessProbe: + initialDelaySeconds: 5 + timeoutSeconds: 1 + failureThreshold: 3 + periodSeconds: 10 + successThreshold: 1 + +# Liveness probe +livenessProbe: + initialDelaySeconds: 30 + timeoutSeconds: 5 + failureThreshold: 3 + periodSeconds: 10 + successThreshold: 1 diff --git a/packages/shipa/charts/charts/mongodb/.helmignore b/packages/shipa/charts/charts/mongodb/.helmignore new file mode 100644 index 000000000..f0c131944 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/.helmignore @@ -0,0 +1,21 @@ +# Patterns to ignore when building packages. +# This supports shell glob matching, relative path matching, and +# negation (prefixed with !). Only one pattern per line. +.DS_Store +# Common VCS dirs +.git/ +.gitignore +.bzr/ +.bzrignore +.hg/ +.hgignore +.svn/ +# Common backup files +*.swp +*.bak +*.tmp +*~ +# Various IDEs +.project +.idea/ +*.tmproj diff --git a/packages/shipa/charts/charts/mongodb/Chart.lock b/packages/shipa/charts/charts/mongodb/Chart.lock new file mode 100644 index 000000000..0d6f7a892 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/Chart.lock @@ -0,0 +1,6 @@ +dependencies: +- name: common + repository: https://charts.bitnami.com/bitnami + version: 1.11.1 +digest: sha256:a000bcd4d4cdd813c67d633b5523b4a4cd478fb95f1cae665d9b0ba5c45b40e2 +generated: "2022-02-27T04:47:19.688036252Z" diff --git a/packages/shipa/charts/charts/mongodb/Chart.yaml b/packages/shipa/charts/charts/mongodb/Chart.yaml new file mode 100644 index 000000000..e2c900829 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/Chart.yaml @@ -0,0 +1,30 @@ +annotations: + category: Database +apiVersion: v2 +appVersion: 4.4.12 +dependencies: +- name: common + repository: https://charts.bitnami.com/bitnami + tags: + - bitnami-common + version: 1.x.x +description: MongoDB(R) is a relational open source NoSQL database. Easy to use, it + stores data in JSON-like documents. Automated scalability and high-performance. + Ideal for developing cloud native applications. +home: https://github.com/bitnami/charts/tree/master/bitnami/mongodb +icon: https://bitnami.com/assets/stacks/mongodb/img/mongodb-stack-220x234.png +keywords: +- mongodb +- database +- nosql +- cluster +- replicaset +- replication +maintainers: +- email: containers@bitnami.com + name: Bitnami +name: mongodb +sources: +- https://github.com/bitnami/bitnami-docker-mongodb +- https://mongodb.org +version: 11.0.5 diff --git a/packages/shipa/charts/charts/mongodb/README.md b/packages/shipa/charts/charts/mongodb/README.md new file mode 100644 index 000000000..159aec54b --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/README.md @@ -0,0 +1,684 @@ + + +# MongoDB(R) packaged by Bitnami + +MongoDB(R) is a relational open source NoSQL database. Easy to use, it stores data in JSON-like documents. Automated scalability and high-performance. Ideal for developing cloud native applications. + +[Overview of MongoDB®](http://www.mongodb.org) + +Disclaimer: The respective trademarks mentioned in the offering are owned by the respective companies. We do not provide a commercial license for any of these products. This listing has an open-source license. MongoDB(R) is run and maintained by MongoDB, which is a completely separate project from Bitnami. + +## TL;DR + +```bash +$ helm repo add bitnami https://charts.bitnami.com/bitnami +$ helm install my-release bitnami/mongodb +``` + +## Introduction + +This chart bootstraps a [MongoDB(®)](https://github.com/bitnami/bitnami-docker-mongodb) deployment on a [Kubernetes](https://kubernetes.io) cluster using the [Helm](https://helm.sh) package manager. + +Bitnami charts can be used with [Kubeapps](https://kubeapps.com/) for deployment and management of Helm Charts in clusters. This chart has been tested to work with Fluentd and Prometheus on top of the [BKPR](https://kubeprod.io/). + +## Prerequisites + +- Kubernetes 1.19+ +- Helm 3.2.0+ +- PV provisioner support in the underlying infrastructure + +## Installing the Chart + +To install the chart with the release name `my-release`: + +```bash +$ helm install my-release bitnami/mongodb +``` + +The command deploys MongoDB(®) on the Kubernetes cluster in the default configuration. The [Parameters](#parameters) section lists the parameters that can be configured during installation. + +> **Tip**: List all releases using `helm list` + +## Uninstalling the Chart + +To uninstall/delete the `my-release` deployment: + +```bash +$ helm delete my-release +``` + +The command removes all the Kubernetes components associated with the chart and deletes the release. + +## Architecture + +This chart allows installing MongoDB(®) using two different architecture setups: `standalone` or `replicaset`. Use the `architecture` parameter to choose the one to use: + +```console +architecture="standalone" +architecture="replicaset" +``` + +Refer to the [chart documentation for more information on each of these architectures](https://docs.bitnami.com/kubernetes/infrastructure/mongodb/get-started/understand-architecture/). + +## Parameters + +### Global parameters + +| Name | Description | Value | +| -------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ----- | +| `global.imageRegistry` | Global Docker image registry | `""` | +| `global.imagePullSecrets` | Global Docker registry secret names as an array | `[]` | +| `global.storageClass` | Global StorageClass for Persistent Volume(s) | `""` | +| `global.namespaceOverride` | Override the namespace for resource deployed by the chart, but can itself be overridden by the local namespaceOverride | `""` | + + +### Common parameters + +| Name | Description | Value | +| ------------------------ | --------------------------------------------------------------------------------------------------------- | --------------- | +| `nameOverride` | String to partially override mongodb.fullname template (will maintain the release name) | `""` | +| `fullnameOverride` | String to fully override mongodb.fullname template | `""` | +| `clusterDomain` | Default Kubernetes cluster domain | `cluster.local` | +| `extraDeploy` | Array of extra objects to deploy with the release | `[]` | +| `commonLabels` | Add labels to all the deployed resources (sub-charts are not considered). Evaluated as a template | `{}` | +| `commonAnnotations` | Common annotations to add to all Mongo resources (sub-charts are not considered). Evaluated as a template | `{}` | +| `diagnosticMode.enabled` | Enable diagnostic mode (all probes will be disabled and the command will be overridden) | `false` | +| `diagnosticMode.command` | Command to override all containers in the deployment | `["sleep"]` | +| `diagnosticMode.args` | Args to override all containers in the deployment | `["infinity"]` | + + +### MongoDB(®) parameters + +| Name | Description | Value | +| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ---------------------- | +| `image.registry` | MongoDB(®) image registry | `docker.io` | +| `image.repository` | MongoDB(®) image registry | `bitnami/mongodb` | +| `image.tag` | MongoDB(®) image tag (immutable tags are recommended) | `4.4.11-debian-10-r12` | +| `image.pullPolicy` | MongoDB(®) image pull policy | `IfNotPresent` | +| `image.pullSecrets` | Specify docker-registry secret names as an array | `[]` | +| `image.debug` | Set to true if you would like to see extra information on logs | `false` | +| `schedulerName` | Name of the scheduler (other than default) to dispatch pods | `""` | +| `architecture` | MongoDB(®) architecture (`standalone` or `replicaset`) | `standalone` | +| `useStatefulSet` | Set to true to use a StatefulSet instead of a Deployment (only when `architecture=standalone`) | `false` | +| `auth.enabled` | Enable authentication | `true` | +| `auth.rootUser` | MongoDB(®) root user | `root` | +| `auth.rootPassword` | MongoDB(®) root password | `""` | +| `auth.usernames` | List of custom users to be created during the initialization | `[]` | +| `auth.passwords` | List of passwords for the custom users set at `auth.usernames` | `[]` | +| `auth.databases` | List of custom databases to be created during the initialization | `[]` | +| `auth.username` | DEPRECATED: use `auth.usernames` instead | `""` | +| `auth.password` | DEPRECATED: use `auth.passwords` instead | `""` | +| `auth.database` | DEPRECATED: use `auth.databases` instead | `""` | +| `auth.replicaSetKey` | Key used for authentication in the replicaset (only when `architecture=replicaset`) | `""` | +| `auth.existingSecret` | Existing secret with MongoDB(®) credentials (keys: `mongodb-password`, `mongodb-root-password`, ` mongodb-replica-set-key`) | `""` | +| `tls.enabled` | Enable MongoDB(®) TLS support between nodes in the cluster as well as between mongo clients and nodes | `false` | +| `tls.autoGenerated` | Generate a custom CA and self-signed certificates | `true` | +| `tls.existingSecret` | Existing secret with TLS certificates (keys: `mongodb-ca-cert`, `mongodb-ca-key`, `client-pem`) | `""` | +| `tls.caCert` | Custom CA certificated (base64 encoded) | `""` | +| `tls.caKey` | CA certificate private key (base64 encoded) | `""` | +| `tls.image.registry` | Init container TLS certs setup image registry | `docker.io` | +| `tls.image.repository` | Init container TLS certs setup image repository | `bitnami/nginx` | +| `tls.image.tag` | Init container TLS certs setup image tag (immutable tags are recommended) | `1.21.5-debian-10-r12` | +| `tls.image.pullPolicy` | Init container TLS certs setup image pull policy | `IfNotPresent` | +| `tls.extraDnsNames` | Add extra dns names to the CA, can solve x509 auth issue for pod clients | `[]` | +| `tls.mode` | Allows to set the tls mode which should be used when tls is enabled (options: `allowTLS`, `preferTLS`, `requireTLS`) | `requireTLS` | +| `hostAliases` | Add deployment host aliases | `[]` | +| `replicaSetName` | Name of the replica set (only when `architecture=replicaset`) | `rs0` | +| `replicaSetHostnames` | Enable DNS hostnames in the replicaset config (only when `architecture=replicaset`) | `true` | +| `enableIPv6` | Switch to enable/disable IPv6 on MongoDB(®) | `false` | +| `directoryPerDB` | Switch to enable/disable DirectoryPerDB on MongoDB(®) | `false` | +| `systemLogVerbosity` | MongoDB(®) system log verbosity level | `0` | +| `disableSystemLog` | Switch to enable/disable MongoDB(®) system log | `false` | +| `disableJavascript` | Switch to enable/disable MongoDB(®) server-side JavaScript execution | `false` | +| `enableJournal` | Switch to enable/disable MongoDB(®) Journaling | `true` | +| `configuration` | MongoDB(®) configuration file to be used for Primary and Secondary nodes | `""` | + + +### replicaSetConfigurationSettings settings applied during runtime (not via configuration file) + +| Name | Description | Value | +| ----------------------------------------------- | ----------------------------------------------------------------------------------------------- | ------- | +| `replicaSetConfigurationSettings.enabled` | Enable MongoDB(®) Switch to enable/disable configuring MongoDB(®) run time rs.conf settings | `false` | +| `replicaSetConfigurationSettings.configuration` | run-time rs.conf settings | `{}` | +| `existingConfigmap` | Name of existing ConfigMap with MongoDB(®) configuration for Primary and Secondary nodes | `""` | +| `initdbScripts` | Dictionary of initdb scripts | `{}` | +| `initdbScriptsConfigMap` | Existing ConfigMap with custom initdb scripts | `""` | +| `command` | Override default container command (useful when using custom images) | `[]` | +| `args` | Override default container args (useful when using custom images) | `[]` | +| `extraFlags` | MongoDB(®) additional command line flags | `[]` | +| `extraEnvVars` | Extra environment variables to add to MongoDB(®) pods | `[]` | +| `extraEnvVarsCM` | Name of existing ConfigMap containing extra env vars | `""` | +| `extraEnvVarsSecret` | Name of existing Secret containing extra env vars (in case of sensitive data) | `""` | + + +### MongoDB(®) statefulset parameters + +| Name | Description | Value | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------ | --------------- | +| `annotations` | Additional labels to be added to the MongoDB(®) statefulset. Evaluated as a template | `{}` | +| `labels` | Annotations to be added to the MongoDB(®) statefulset. Evaluated as a template | `{}` | +| `replicaCount` | Number of MongoDB(®) nodes (only when `architecture=replicaset`) | `2` | +| `strategyType` | StrategyType for MongoDB(®) statefulset | `RollingUpdate` | +| `podManagementPolicy` | Pod management policy for MongoDB(®) | `OrderedReady` | +| `podAffinityPreset` | MongoDB(®) Pod affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` | `""` | +| `podAntiAffinityPreset` | MongoDB(®) Pod anti-affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` | `soft` | +| `nodeAffinityPreset.type` | MongoDB(®) Node affinity preset type. Ignored if `affinity` is set. Allowed values: `soft` or `hard` | `""` | +| `nodeAffinityPreset.key` | MongoDB(®) Node label key to match Ignored if `affinity` is set. | `""` | +| `nodeAffinityPreset.values` | MongoDB(®) Node label values to match. Ignored if `affinity` is set. | `[]` | +| `affinity` | MongoDB(®) Affinity for pod assignment | `{}` | +| `nodeSelector` | MongoDB(®) Node labels for pod assignment | `{}` | +| `tolerations` | MongoDB(®) Tolerations for pod assignment | `[]` | +| `topologySpreadConstraints` | MongoDB(®) Spread Constraints for Pods | `[]` | +| `podLabels` | MongoDB(®) pod labels | `{}` | +| `podAnnotations` | MongoDB(®) Pod annotations | `{}` | +| `priorityClassName` | Name of the existing priority class to be used by MongoDB(®) pod(s) | `""` | +| `runtimeClassName` | Name of the runtime class to be used by MongoDB(®) pod(s) | `""` | +| `podSecurityContext.enabled` | Enable MongoDB(®) pod(s)' Security Context | `true` | +| `podSecurityContext.fsGroup` | Group ID for the volumes of the MongoDB(®) pod(s) | `1001` | +| `podSecurityContext.sysctls` | sysctl settings of the MongoDB(®) pod(s)' | `[]` | +| `containerSecurityContext.enabled` | Enable MongoDB(®) container(s)' Security Context | `true` | +| `containerSecurityContext.runAsUser` | User ID for the MongoDB(®) container | `1001` | +| `containerSecurityContext.runAsNonRoot` | Set MongoDB(®) container's Security Context runAsNonRoot | `true` | +| `resources.limits` | The resources limits for MongoDB(®) containers | `{}` | +| `resources.requests` | The requested resources for MongoDB(®) containers | `{}` | +| `livenessProbe.enabled` | Enable livenessProbe | `true` | +| `livenessProbe.initialDelaySeconds` | Initial delay seconds for livenessProbe | `30` | +| `livenessProbe.periodSeconds` | Period seconds for livenessProbe | `10` | +| `livenessProbe.timeoutSeconds` | Timeout seconds for livenessProbe | `5` | +| `livenessProbe.failureThreshold` | Failure threshold for livenessProbe | `6` | +| `livenessProbe.successThreshold` | Success threshold for livenessProbe | `1` | +| `readinessProbe.enabled` | Enable readinessProbe | `true` | +| `readinessProbe.initialDelaySeconds` | Initial delay seconds for readinessProbe | `5` | +| `readinessProbe.periodSeconds` | Period seconds for readinessProbe | `10` | +| `readinessProbe.timeoutSeconds` | Timeout seconds for readinessProbe | `5` | +| `readinessProbe.failureThreshold` | Failure threshold for readinessProbe | `6` | +| `readinessProbe.successThreshold` | Success threshold for readinessProbe | `1` | +| `startupProbe.enabled` | Enable startupProbe | `false` | +| `startupProbe.initialDelaySeconds` | Initial delay seconds for startupProbe | `5` | +| `startupProbe.periodSeconds` | Period seconds for startupProbe | `10` | +| `startupProbe.timeoutSeconds` | Timeout seconds for startupProbe | `5` | +| `startupProbe.failureThreshold` | Failure threshold for startupProbe | `30` | +| `startupProbe.successThreshold` | Success threshold for startupProbe | `1` | +| `customLivenessProbe` | Override default liveness probe for MongoDB(®) containers | `{}` | +| `customReadinessProbe` | Override default readiness probe for MongoDB(®) containers | `{}` | +| `customStartupProbe` | Override default startup probe for MongoDB(®) containers | `{}` | +| `initContainers` | Add additional init containers for the hidden node pod(s) | `[]` | +| `sidecars` | Add additional sidecar containers for the MongoDB(®) pod(s) | `[]` | +| `extraVolumeMounts` | Optionally specify extra list of additional volumeMounts for the MongoDB(®) container(s) | `[]` | +| `extraVolumes` | Optionally specify extra list of additional volumes to the MongoDB(®) statefulset | `[]` | +| `pdb.create` | Enable/disable a Pod Disruption Budget creation for MongoDB(®) pod(s) | `false` | +| `pdb.minAvailable` | Minimum number/percentage of MongoDB(®) pods that must still be available after the eviction | `1` | +| `pdb.maxUnavailable` | Maximum number/percentage of MongoDB(®) pods that may be made unavailable after the eviction | `""` | + + +### Traffic exposure parameters + +| Name | Description | Value | +| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | +| `service.nameOverride` | MongoDB(®) service name | `""` | +| `service.type` | Kubernetes Service type | `ClusterIP` | +| `service.port` | MongoDB(®) service port | `27017` | +| `service.portName` | MongoDB(®) service port name | `mongodb` | +| `service.nodePort` | Port to bind to for NodePort and LoadBalancer service types | `""` | +| `service.clusterIP` | MongoDB(®) service cluster IP | `""` | +| `service.externalIPs` | Specify the externalIP value ClusterIP service type. | `[]` | +| `service.loadBalancerIP` | loadBalancerIP for MongoDB(®) Service | `""` | +| `service.loadBalancerSourceRanges` | Address(es) that are allowed when service is LoadBalancer | `[]` | +| `service.annotations` | Provide any additional annotations that may be required | `{}` | +| `externalAccess.enabled` | Enable Kubernetes external cluster access to MongoDB(®) nodes (only for replicaset architecture) | `false` | +| `externalAccess.autoDiscovery.enabled` | Enable using an init container to auto-detect external IPs by querying the K8s API | `false` | +| `externalAccess.autoDiscovery.image.registry` | Init container auto-discovery image registry | `docker.io` | +| `externalAccess.autoDiscovery.image.repository` | Init container auto-discovery image repository | `bitnami/kubectl` | +| `externalAccess.autoDiscovery.image.tag` | Init container auto-discovery image tag (immutable tags are recommended) | `1.23.1-debian-10-r23` | +| `externalAccess.autoDiscovery.image.pullPolicy` | Init container auto-discovery image pull policy | `IfNotPresent` | +| `externalAccess.autoDiscovery.image.pullSecrets` | Init container auto-discovery image pull secrets | `[]` | +| `externalAccess.autoDiscovery.resources.limits` | Init container auto-discovery resource limits | `{}` | +| `externalAccess.autoDiscovery.resources.requests` | Init container auto-discovery resource requests | `{}` | +| `externalAccess.service.type` | Kubernetes Service type for external access. Allowed values: NodePort, LoadBalancer or ClusterIP | `LoadBalancer` | +| `externalAccess.service.port` | MongoDB(®) port used for external access when service type is LoadBalancer | `27017` | +| `externalAccess.service.loadBalancerIPs` | Array of load balancer IPs for MongoDB(®) nodes | `[]` | +| `externalAccess.service.loadBalancerSourceRanges` | Address(es) that are allowed when service is LoadBalancer | `[]` | +| `externalAccess.service.nodePorts` | Array of node ports used to configure MongoDB(®) advertised hostname when service type is NodePort | `[]` | +| `externalAccess.service.domain` | Domain or external IP used to configure MongoDB(®) advertised hostname when service type is NodePort | `""` | +| `externalAccess.service.annotations` | Service annotations for external access | `{}` | +| `externalAccess.hidden.enabled` | Enable Kubernetes external cluster access to MongoDB(®) hidden nodes | `false` | +| `externalAccess.hidden.service.type` | Kubernetes Service type for external access. Allowed values: NodePort or LoadBalancer | `LoadBalancer` | +| `externalAccess.hidden.service.port` | MongoDB(®) port used for external access when service type is LoadBalancer | `27017` | +| `externalAccess.hidden.service.loadBalancerIPs` | Array of load balancer IPs for MongoDB(®) nodes | `[]` | +| `externalAccess.hidden.service.loadBalancerSourceRanges` | Address(es) that are allowed when service is LoadBalancer | `[]` | +| `externalAccess.hidden.service.nodePorts` | Array of node ports used to configure MongoDB(®) advertised hostname when service type is NodePort. Length must be the same as replicaCount | `[]` | +| `externalAccess.hidden.service.domain` | Domain or external IP used to configure MongoDB(®) advertised hostname when service type is NodePort | `""` | +| `externalAccess.hidden.service.annotations` | Service annotations for external access | `{}` | + + +### Persistence parameters + +| Name | Description | Value | +| --------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------- | +| `persistence.enabled` | Enable MongoDB(®) data persistence using PVC | `true` | +| `persistence.medium` | Provide a medium for `emptyDir` volumes. | `""` | +| `persistence.existingClaim` | Provide an existing `PersistentVolumeClaim` (only when `architecture=standalone`) | `""` | +| `persistence.storageClass` | PVC Storage Class for MongoDB(®) data volume | `""` | +| `persistence.accessModes` | PV Access Mode | `["ReadWriteOnce"]` | +| `persistence.size` | PVC Storage Request for MongoDB(®) data volume | `8Gi` | +| `persistence.annotations` | PVC annotations | `{}` | +| `persistence.mountPath` | Path to mount the volume at | `/bitnami/mongodb` | +| `persistence.subPath` | Subdirectory of the volume to mount at | `""` | +| `persistence.volumeClaimTemplates.selector` | A label query over volumes to consider for binding (e.g. when using local volumes) | `{}` | +| `persistence.volumeClaimTemplates.requests` | Custom PVC requests attributes | `{}` | +| `persistence.volumeClaimTemplates.dataSource` | Add dataSource to the VolumeClaimTemplate | `{}` | + + +### RBAC parameters + +| Name | Description | Value | +| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `serviceAccount.create` | Enable creation of ServiceAccount for MongoDB(®) pods | `true` | +| `serviceAccount.name` | Name of the created serviceAccount | `""` | +| `serviceAccount.annotations` | Additional Service Account annotations | `{}` | +| `rbac.create` | Whether to create & use RBAC resources or not | `false` | +| `rbac.role.rules` | Custom rules to create following the role specification | `[]` | +| `podSecurityPolicy.create` | Whether to create a PodSecurityPolicy. WARNING: PodSecurityPolicy is deprecated in Kubernetes v1.21 or later, unavailable in v1.25 or later | `false` | +| `podSecurityPolicy.allowPrivilegeEscalation` | Enable privilege escalation | `false` | +| `podSecurityPolicy.privileged` | Allow privileged | `false` | +| `podSecurityPolicy.spec` | Specify the full spec to use for Pod Security Policy | `{}` | + + +### Volume Permissions parameters + +| Name | Description | Value | +| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ----------------------- | +| `volumePermissions.enabled` | Enable init container that changes the owner and group of the persistent volume(s) mountpoint to `runAsUser:fsGroup` | `false` | +| `volumePermissions.image.registry` | Init container volume-permissions image registry | `docker.io` | +| `volumePermissions.image.repository` | Init container volume-permissions image repository | `bitnami/bitnami-shell` | +| `volumePermissions.image.tag` | Init container volume-permissions image tag (immutable tags are recommended) | `10-debian-10-r304` | +| `volumePermissions.image.pullPolicy` | Init container volume-permissions image pull policy | `IfNotPresent` | +| `volumePermissions.image.pullSecrets` | Specify docker-registry secret names as an array | `[]` | +| `volumePermissions.resources.limits` | Init container volume-permissions resource limits | `{}` | +| `volumePermissions.resources.requests` | Init container volume-permissions resource requests | `{}` | +| `volumePermissions.securityContext.runAsUser` | User ID for the volumePermissions container | `0` | + + +### Arbiter parameters + +| Name | Description | Value | +| -------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------- | +| `arbiter.enabled` | Enable deploying the arbiter | `true` | +| `arbiter.configuration` | Arbiter configuration file to be used | `""` | +| `arbiter.hostAliases` | Add deployment host aliases | `[]` | +| `arbiter.existingConfigmap` | Name of existing ConfigMap with Arbiter configuration | `""` | +| `arbiter.command` | Override default container command (useful when using custom images) | `[]` | +| `arbiter.args` | Override default container args (useful when using custom images) | `[]` | +| `arbiter.extraFlags` | Arbiter additional command line flags | `[]` | +| `arbiter.extraEnvVars` | Extra environment variables to add to Arbiter pods | `[]` | +| `arbiter.extraEnvVarsCM` | Name of existing ConfigMap containing extra env vars | `""` | +| `arbiter.extraEnvVarsSecret` | Name of existing Secret containing extra env vars (in case of sensitive data) | `""` | +| `arbiter.annotations` | Additional labels to be added to the Arbiter statefulset | `{}` | +| `arbiter.labels` | Annotations to be added to the Arbiter statefulset | `{}` | +| `arbiter.podAffinityPreset` | Arbiter Pod affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` | `""` | +| `arbiter.podAntiAffinityPreset` | Arbiter Pod anti-affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` | `soft` | +| `arbiter.nodeAffinityPreset.type` | Arbiter Node affinity preset type. Ignored if `affinity` is set. Allowed values: `soft` or `hard` | `""` | +| `arbiter.nodeAffinityPreset.key` | Arbiter Node label key to match Ignored if `affinity` is set. | `""` | +| `arbiter.nodeAffinityPreset.values` | Arbiter Node label values to match. Ignored if `affinity` is set. | `[]` | +| `arbiter.affinity` | Arbiter Affinity for pod assignment | `{}` | +| `arbiter.nodeSelector` | Arbiter Node labels for pod assignment | `{}` | +| `arbiter.tolerations` | Arbiter Tolerations for pod assignment | `[]` | +| `arbiter.podLabels` | Arbiter pod labels | `{}` | +| `arbiter.podAnnotations` | Arbiter Pod annotations | `{}` | +| `arbiter.priorityClassName` | Name of the existing priority class to be used by Arbiter pod(s) | `""` | +| `arbiter.runtimeClassName` | Name of the runtime class to be used by Arbiter pod(s) | `""` | +| `arbiter.podSecurityContext.enabled` | Enable Arbiter pod(s)' Security Context | `true` | +| `arbiter.podSecurityContext.fsGroup` | Group ID for the volumes of the Arbiter pod(s) | `1001` | +| `arbiter.podSecurityContext.sysctls` | sysctl settings of the Arbiter pod(s)' | `[]` | +| `arbiter.containerSecurityContext.enabled` | Enable Arbiter container(s)' Security Context | `true` | +| `arbiter.containerSecurityContext.runAsUser` | User ID for the Arbiter container | `1001` | +| `arbiter.resources.limits` | The resources limits for Arbiter containers | `{}` | +| `arbiter.resources.requests` | The requested resources for Arbiter containers | `{}` | +| `arbiter.livenessProbe.enabled` | Enable livenessProbe | `true` | +| `arbiter.livenessProbe.initialDelaySeconds` | Initial delay seconds for livenessProbe | `30` | +| `arbiter.livenessProbe.periodSeconds` | Period seconds for livenessProbe | `10` | +| `arbiter.livenessProbe.timeoutSeconds` | Timeout seconds for livenessProbe | `5` | +| `arbiter.livenessProbe.failureThreshold` | Failure threshold for livenessProbe | `6` | +| `arbiter.livenessProbe.successThreshold` | Success threshold for livenessProbe | `1` | +| `arbiter.readinessProbe.enabled` | Enable readinessProbe | `true` | +| `arbiter.readinessProbe.initialDelaySeconds` | Initial delay seconds for readinessProbe | `5` | +| `arbiter.readinessProbe.periodSeconds` | Period seconds for readinessProbe | `10` | +| `arbiter.readinessProbe.timeoutSeconds` | Timeout seconds for readinessProbe | `5` | +| `arbiter.readinessProbe.failureThreshold` | Failure threshold for readinessProbe | `6` | +| `arbiter.readinessProbe.successThreshold` | Success threshold for readinessProbe | `1` | +| `arbiter.customLivenessProbe` | Override default liveness probe for Arbiter containers | `{}` | +| `arbiter.customReadinessProbe` | Override default readiness probe for Arbiter containers | `{}` | +| `arbiter.initContainers` | Add additional init containers for the Arbiter pod(s) | `[]` | +| `arbiter.sidecars` | Add additional sidecar containers for the Arbiter pod(s) | `[]` | +| `arbiter.extraVolumeMounts` | Optionally specify extra list of additional volumeMounts for the Arbiter container(s) | `[]` | +| `arbiter.extraVolumes` | Optionally specify extra list of additional volumes to the Arbiter statefulset | `[]` | +| `arbiter.pdb.create` | Enable/disable a Pod Disruption Budget creation for Arbiter pod(s) | `false` | +| `arbiter.pdb.minAvailable` | Minimum number/percentage of Arbiter pods that should remain scheduled | `1` | +| `arbiter.pdb.maxUnavailable` | Maximum number/percentage of Arbiter pods that may be made unavailable | `""` | +| `arbiter.service.nameOverride` | The arbiter service name | `""` | + + +### Hidden Node parameters + +| Name | Description | Value | +| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------- | +| `hidden.enabled` | Enable deploying the hidden nodes | `false` | +| `hidden.configuration` | Hidden node configuration file to be used | `""` | +| `hidden.existingConfigmap` | Name of existing ConfigMap with Hidden node configuration | `""` | +| `hidden.command` | Override default container command (useful when using custom images) | `[]` | +| `hidden.args` | Override default container args (useful when using custom images) | `[]` | +| `hidden.extraFlags` | Hidden node additional command line flags | `[]` | +| `hidden.extraEnvVars` | Extra environment variables to add to Hidden node pods | `[]` | +| `hidden.extraEnvVarsCM` | Name of existing ConfigMap containing extra env vars | `""` | +| `hidden.extraEnvVarsSecret` | Name of existing Secret containing extra env vars (in case of sensitive data) | `""` | +| `hidden.annotations` | Additional labels to be added to thehidden node statefulset | `{}` | +| `hidden.labels` | Annotations to be added to the hidden node statefulset | `{}` | +| `hidden.replicaCount` | Number of hidden nodes (only when `architecture=replicaset`) | `1` | +| `hidden.strategyType` | StrategyType for hidden node statefulset | `RollingUpdate` | +| `hidden.podManagementPolicy` | Pod management policy for hidden node | `OrderedReady` | +| `hidden.podAffinityPreset` | Hidden node Pod affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` | `""` | +| `hidden.podAntiAffinityPreset` | Hidden node Pod anti-affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` | `soft` | +| `hidden.nodeAffinityPreset.type` | Hidden Node affinity preset type. Ignored if `affinity` is set. Allowed values: `soft` or `hard` | `""` | +| `hidden.nodeAffinityPreset.key` | Hidden Node label key to match Ignored if `affinity` is set. | `""` | +| `hidden.nodeAffinityPreset.values` | Hidden Node label values to match. Ignored if `affinity` is set. | `[]` | +| `hidden.affinity` | Hidden node Affinity for pod assignment | `{}` | +| `hidden.nodeSelector` | Hidden node Node labels for pod assignment | `{}` | +| `hidden.tolerations` | Hidden node Tolerations for pod assignment | `[]` | +| `hidden.podLabels` | Hidden node pod labels | `{}` | +| `hidden.podAnnotations` | Hidden node Pod annotations | `{}` | +| `hidden.priorityClassName` | Name of the existing priority class to be used by hidden node pod(s) | `""` | +| `hidden.runtimeClassName` | Name of the runtime class to be used by hidden node pod(s) | `""` | +| `hidden.resources.limits` | The resources limits for hidden node containers | `{}` | +| `hidden.resources.requests` | The requested resources for hidden node containers | `{}` | +| `hidden.livenessProbe.enabled` | Enable livenessProbe | `true` | +| `hidden.livenessProbe.initialDelaySeconds` | Initial delay seconds for livenessProbe | `30` | +| `hidden.livenessProbe.periodSeconds` | Period seconds for livenessProbe | `10` | +| `hidden.livenessProbe.timeoutSeconds` | Timeout seconds for livenessProbe | `5` | +| `hidden.livenessProbe.failureThreshold` | Failure threshold for livenessProbe | `6` | +| `hidden.livenessProbe.successThreshold` | Success threshold for livenessProbe | `1` | +| `hidden.readinessProbe.enabled` | Enable readinessProbe | `true` | +| `hidden.readinessProbe.initialDelaySeconds` | Initial delay seconds for readinessProbe | `5` | +| `hidden.readinessProbe.periodSeconds` | Period seconds for readinessProbe | `10` | +| `hidden.readinessProbe.timeoutSeconds` | Timeout seconds for readinessProbe | `5` | +| `hidden.readinessProbe.failureThreshold` | Failure threshold for readinessProbe | `6` | +| `hidden.readinessProbe.successThreshold` | Success threshold for readinessProbe | `1` | +| `hidden.customLivenessProbe` | Override default liveness probe for hidden node containers | `{}` | +| `hidden.customReadinessProbe` | Override default readiness probe for hidden node containers | `{}` | +| `hidden.initContainers` | Add init containers to the MongoDB(®) Hidden pods. | `[]` | +| `hidden.sidecars` | Add additional sidecar containers for the hidden node pod(s) | `[]` | +| `hidden.extraVolumeMounts` | Optionally specify extra list of additional volumeMounts for the hidden node container(s) | `[]` | +| `hidden.extraVolumes` | Optionally specify extra list of additional volumes to the hidden node statefulset | `[]` | +| `hidden.pdb.create` | Enable/disable a Pod Disruption Budget creation for hidden node pod(s) | `false` | +| `hidden.pdb.minAvailable` | Minimum number/percentage of hidden node pods that should remain scheduled | `1` | +| `hidden.pdb.maxUnavailable` | Maximum number/percentage of hidden node pods that may be made unavailable | `""` | +| `hidden.persistence.enabled` | Enable hidden node data persistence using PVC | `true` | +| `hidden.persistence.medium` | Provide a medium for `emptyDir` volumes. | `""` | +| `hidden.persistence.storageClass` | PVC Storage Class for hidden node data volume | `""` | +| `hidden.persistence.accessModes` | PV Access Mode | `["ReadWriteOnce"]` | +| `hidden.persistence.size` | PVC Storage Request for hidden node data volume | `8Gi` | +| `hidden.persistence.annotations` | PVC annotations | `{}` | +| `hidden.persistence.mountPath` | The path the volume will be mounted at, useful when using different MongoDB(®) images. | `/bitnami/mongodb` | +| `hidden.persistence.subPath` | The subdirectory of the volume to mount to, useful in dev environments | `""` | +| `hidden.persistence.volumeClaimTemplates.selector` | A label query over volumes to consider for binding (e.g. when using local volumes) | `{}` | +| `hidden.persistence.volumeClaimTemplates.dataSource` | Set volumeClaimTemplate dataSource | `{}` | + + +### Metrics parameters + +| Name | Description | Value | +| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | -------------------------- | +| `metrics.enabled` | Enable using a sidecar Prometheus exporter | `false` | +| `metrics.image.registry` | MongoDB(®) Prometheus exporter image registry | `docker.io` | +| `metrics.image.repository` | MongoDB(®) Prometheus exporter image repository | `bitnami/mongodb-exporter` | +| `metrics.image.tag` | MongoDB(®) Prometheus exporter image tag (immutable tags are recommended) | `0.30.0-debian-10-r53` | +| `metrics.image.pullPolicy` | MongoDB(®) Prometheus exporter image pull policy | `IfNotPresent` | +| `metrics.image.pullSecrets` | Specify docker-registry secret names as an array | `[]` | +| `metrics.username` | String with username for the metrics exporter | `""` | +| `metrics.password` | String with password for the metrics exporter | `""` | +| `metrics.extraFlags` | String with extra flags to the metrics exporter | `""` | +| `metrics.extraUri` | Additional URI options of the metrics service | `""` | +| `metrics.resources.limits` | The resources limits for Prometheus exporter containers | `{}` | +| `metrics.resources.requests` | The requested resources for Prometheus exporter containers | `{}` | +| `metrics.containerPort` | Port of the Prometheus metrics container | `9216` | +| `metrics.service.annotations` | Annotations for Prometheus Exporter pods. Evaluated as a template. | `{}` | +| `metrics.service.type` | Type of the Prometheus metrics service | `ClusterIP` | +| `metrics.service.port` | Port of the Prometheus metrics service | `9216` | +| `metrics.livenessProbe.enabled` | Enable livenessProbe | `true` | +| `metrics.livenessProbe.initialDelaySeconds` | Initial delay seconds for livenessProbe | `15` | +| `metrics.livenessProbe.periodSeconds` | Period seconds for livenessProbe | `5` | +| `metrics.livenessProbe.timeoutSeconds` | Timeout seconds for livenessProbe | `5` | +| `metrics.livenessProbe.failureThreshold` | Failure threshold for livenessProbe | `3` | +| `metrics.livenessProbe.successThreshold` | Success threshold for livenessProbe | `1` | +| `metrics.readinessProbe.enabled` | Enable readinessProbe | `true` | +| `metrics.readinessProbe.initialDelaySeconds` | Initial delay seconds for readinessProbe | `5` | +| `metrics.readinessProbe.periodSeconds` | Period seconds for readinessProbe | `5` | +| `metrics.readinessProbe.timeoutSeconds` | Timeout seconds for readinessProbe | `1` | +| `metrics.readinessProbe.failureThreshold` | Failure threshold for readinessProbe | `3` | +| `metrics.readinessProbe.successThreshold` | Success threshold for readinessProbe | `1` | +| `metrics.serviceMonitor.enabled` | Create ServiceMonitor Resource for scraping metrics using Prometheus Operator | `false` | +| `metrics.serviceMonitor.namespace` | Namespace which Prometheus is running in | `""` | +| `metrics.serviceMonitor.interval` | Interval at which metrics should be scraped | `30s` | +| `metrics.serviceMonitor.scrapeTimeout` | Specify the timeout after which the scrape is ended | `""` | +| `metrics.serviceMonitor.relabellings` | RelabelConfigs to apply to samples before scraping. | `[]` | +| `metrics.serviceMonitor.metricRelabelings` | MetricsRelabelConfigs to apply to samples before ingestion. | `[]` | +| `metrics.serviceMonitor.additionalLabels` | Used to pass Labels that are used by the Prometheus installed in your cluster to select Service Monitors to work with | `{}` | +| `metrics.prometheusRule.enabled` | Set this to true to create prometheusRules for Prometheus operator | `false` | +| `metrics.prometheusRule.additionalLabels` | Additional labels that can be used so prometheusRules will be discovered by Prometheus | `{}` | +| `metrics.prometheusRule.namespace` | Namespace where prometheusRules resource should be created | `""` | +| `metrics.prometheusRule.rules` | Rules to be created, check values for an example | `{}` | + + +Specify each parameter using the `--set key=value[,key=value]` argument to `helm install`. For example, + +```bash +$ helm install my-release \ + --set auth.rootPassword=secretpassword,auth.username=my-user,auth.password=my-password,auth.database=my-database \ + bitnami/mongodb +``` + +The above command sets the MongoDB(®) `root` account password to `secretpassword`. Additionally, it creates a standard database user named `my-user`, with the password `my-password`, who has access to a database named `my-database`. + +> NOTE: Once this chart is deployed, it is not possible to change the application's access credentials, such as usernames or passwords, using Helm. To change these application credentials after deployment, delete any persistent volumes (PVs) used by the chart and re-deploy it, or use the application's built-in administrative tools if available. + +Alternatively, a YAML file that specifies the values for the parameters can be provided while installing the chart. For example, + +```bash +$ helm install my-release -f values.yaml bitnami/mongodb +``` + +> **Tip**: You can use the default [values.yaml](values.yaml) + +## Configuration and installation details + +### [Rolling vs Immutable tags](https://docs.bitnami.com/containers/how-to/understand-rolling-tags-containers/) + +It is strongly recommended to use immutable tags in a production environment. This ensures your deployment does not change automatically if the same tag is updated with a different image. + +Bitnami will release a new chart updating its containers if a new version of the main container, significant changes, or critical vulnerabilities exist. + +### Customize a new MongoDB instance + +The [Bitnami MongoDB(®) image](https://github.com/bitnami/bitnami-docker-mongodb) supports the use of custom scripts to initialize a fresh instance. In order to execute the scripts, two options are available: + +* Specify them using the `initdbScripts` parameter as dict. +* Define an external Kubernetes ConfigMap with all the initialization scripts by setting the `initdbScriptsConfigMap` parameter. Note that this will override the previous option. + +The allowed script extensions are `.sh` and `.js`. + +### Replicaset: Access MongoDB(®) nodes from outside the cluster + +In order to access MongoDB(®) nodes from outside the cluster when using a replicaset architecture, a specific service per MongoDB(®) pod will be created. There are two ways of configuring external access: + +- Using LoadBalancer services +- Using NodePort services. + +Refer to the [chart documentation for more details and configuration examples](https://docs.bitnami.com/kubernetes/infrastructure/mongodb/configuration/configure-external-access-replicaset/). + +### Add extra environment variables + +To add extra environment variables (useful for advanced operations like custom init scripts), use the `extraEnvVars` property. + +```yaml +extraEnvVars: + - name: LOG_LEVEL + value: error +``` + +Alternatively, you can use a ConfigMap or a Secret with the environment variables. To do so, use the `extraEnvVarsCM` or the `extraEnvVarsSecret` properties. + +### Use Sidecars and Init Containers + +If additional containers are needed in the same pod (such as additional metrics or logging exporters), they can be defined using the `sidecars` config parameter. Similarly, extra init containers can be added using the `initContainers` parameter. + +Refer to the chart documentation for more information on, and examples of, configuring and using [sidecars and init containers](https://docs.bitnami.com/kubernetes/infrastructure/mongodb/configuration/configure-sidecar-init-containers/). + +## Persistence + +The [Bitnami MongoDB(®)](https://github.com/bitnami/bitnami-docker-mongodb) image stores the MongoDB(®) data and configurations at the `/bitnami/mongodb` path of the container. + +The chart mounts a [Persistent Volume](https://kubernetes.io/docs/concepts/storage/persistent-volumes/) at this location. The volume is created using dynamic volume provisioning. + +If you encounter errors when working with persistent volumes, refer to our [troubleshooting guide for persistent volumes](https://docs.bitnami.com/kubernetes/faq/troubleshooting/troubleshooting-persistence-volumes/). + +## Use custom Prometheus rules + +Custom Prometheus rules can be defined for the Prometheus Operator by using the `prometheusRule` parameter. + +Refer to the [chart documentation for an example of a custom rule](https://docs.bitnami.com/kubernetes/infrastructure/mongodb/administration/use-prometheus-rules/). + +## Enable SSL/TLS + +This chart supports enabling SSL/TLS between nodes in the cluster, as well as between MongoDB(®) clients and nodes, by setting the `MONGODB_EXTRA_FLAGS` and `MONGODB_CLIENT_EXTRA_FLAGS` container environment variables, together with the correct `MONGODB_ADVERTISED_HOSTNAME`. To enable full TLS encryption, set the `tls.enabled` parameter to `true`. + +Refer to the [chart documentation for more information on enabling TLS](https://docs.bitnami.com/kubernetes/infrastructure/mongodb/administration/enable-tls/). + +### Set Pod affinity + +This chart allows you to set your custom affinity using the `XXX.affinity` parameter(s). Find more information about Pod affinity in the [Kubernetes documentation](https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity). + +As an alternative, you can use the preset configurations for pod affinity, pod anti-affinity, and node affinity available at the [bitnami/common](https://github.com/bitnami/charts/tree/master/bitnami/common#affinities) chart. To do so, set the `XXX.podAffinityPreset`, `XXX.podAntiAffinityPreset`, or `XXX.nodeAffinityPreset` parameters. + +## Troubleshooting + +Find more information about how to deal with common errors related to Bitnami's Helm charts in [this troubleshooting guide](https://docs.bitnami.com/general/how-to/troubleshoot-helm-chart-issues). + +## Upgrading + +If authentication is enabled, it's necessary to set the `auth.rootPassword` (also `auth.replicaSetKey` when using a replicaset architecture) when upgrading for readiness/liveness probes to work properly. When you install this chart for the first time, some notes will be displayed providing the credentials you must use under the 'Credentials' section. Please note down the password, and run the command below to upgrade your chart: + +```bash +$ helm upgrade my-release bitnami/mongodb --set auth.rootPassword=[PASSWORD] (--set auth.replicaSetKey=[REPLICASETKEY]) +``` + +> Note: you need to substitute the placeholders [PASSWORD] and [REPLICASETKEY] with the values obtained in the installation notes. + +### To 11.0.0 + +In this version, the mongodb-exporter bundled as part of this Helm chart was updated to a new version which, even it is not a major change, can contain breaking changes (from `0.11.X` to `0.30.X`). +Please visit the release notes from the upstream project at https://github.com/percona/mongodb_exporter/releases + +### To 10.0.0 + +[On November 13, 2020, Helm v2 support formally ended](https://github.com/helm/charts#status-of-the-project). This major version is the result of the required changes applied to the Helm Chart to be able to incorporate the different features added in Helm v3 and to be consistent with the Helm project itself regarding the Helm v2 EOL. + +[Learn more about this change and related upgrade considerations](https://docs.bitnami.com/kubernetes/infrastructure/mongodb/administration/upgrade-helm3/). + +### To 9.0.0 + +MongoDB(®) container images were updated to `4.4.x` and it can affect compatibility with older versions of MongoDB(®). Refer to the following guides to upgrade your applications: + +- [Standalone](https://docs.mongodb.com/manual/release-notes/4.4-upgrade-standalone/) +- [Replica Set](https://docs.mongodb.com/manual/release-notes/4.4-upgrade-replica-set/) + +### To 8.0.0 + +- Architecture used to configure MongoDB(®) as a replicaset was completely refactored. Now, both primary and secondary nodes are part of the same statefulset. +- Chart labels were adapted to follow the Helm charts best practices. +- This version introduces `bitnami/common`, a [library chart](https://helm.sh/docs/topics/library_charts/#helm) as a dependency. More documentation about this new utility could be found [here](https://github.com/bitnami/charts/tree/master/bitnami/common#bitnami-common-library-chart). Please, make sure that you have updated the chart dependencies before executing any upgrade. +- Several parameters were renamed or disappeared in favor of new ones on this major version. These are the most important ones: + - `replicas` is renamed to `replicaCount`. + - Authentication parameters are reorganized under the `auth.*` parameter: + - `usePassword` is renamed to `auth.enabled`. + - `mongodbRootPassword`, `mongodbUsername`, `mongodbPassword`, `mongodbDatabase`, and `replicaSet.key` are now `auth.rootPassword`, `auth.username`, `auth.password`, `auth.database`, and `auth.replicaSetKey` respectively. + - `securityContext.*` is deprecated in favor of `podSecurityContext` and `containerSecurityContext`. + - Parameters prefixed with `mongodb` are renamed removing the prefix. E.g. `mongodbEnableIPv6` is renamed to `enableIPv6`. + - Parameters affecting Arbiter nodes are reorganized under the `arbiter.*` parameter. + +Consequences: + +- Backwards compatibility is not guaranteed. To upgrade to `8.0.0`, install a new release of the MongoDB(®) chart, and migrate your data by creating a backup of the database, and restoring it on the new release. + +### To 7.0.0 + +From this version, the way of setting the ingress rules has changed. Instead of using `ingress.paths` and `ingress.hosts` as separate objects, you should now define the rules as objects inside the `ingress.hosts` value, for example: + +```yaml +ingress: + hosts: + - name: mongodb.local + path: / +``` + +### To 6.0.0 + +From this version, `mongodbEnableIPv6` is set to `false` by default in order to work properly in most k8s clusters, if you want to use IPv6 support, you need to set this variable to `true` by adding `--set mongodbEnableIPv6=true` to your `helm` command. +You can find more information in the [`bitnami/mongodb` image README](https://github.com/bitnami/bitnami-docker-mongodb/blob/master/README.md). + +### To 5.0.0 + +When enabling replicaset configuration, backwards compatibility is not guaranteed unless you modify the labels used on the chart's statefulsets. +Use the workaround below to upgrade from versions previous to 5.0.0. The following example assumes that the release name is `my-release`: + +```console +$ kubectl delete statefulset my-release-mongodb-arbiter my-release-mongodb-primary my-release-mongodb-secondary --cascade=false +``` + +### Add extra deployment options + +To add extra deployments (useful for advanced features like sidecars), use the `extraDeploy` property. + +In the example below, you can find how to use a example here for a [MongoDB replica set pod labeler sidecar](https://github.com/combor/k8s-mongo-labeler-sidecar) to identify the primary pod and dynamically label it as the primary node: + +```yaml +extraDeploy: + - apiVersion: v1 + kind: Service + metadata: + name: mongodb-primary + namespace: default + labels: + app.kubernetes.io/component: mongodb + app.kubernetes.io/instance: mongodb + app.kubernetes.io/managed-by: Helm + app.kubernetes.io/name: mongodb + spec: + type: NodePort + externalTrafficPolicy: Cluster + ports: + - name: mongodb-primary + port: 30001 + nodePort: 30001 + protocol: TCP + targetPort: mongodb + selector: + app.kubernetes.io/component: mongodb + app.kubernetes.io/instance: mongodb + app.kubernetes.io/name: mongodb + primary: "true" +``` + +## License + +Copyright © 2022 Bitnami + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/packages/shipa/charts/charts/mongodb/charts/common/.helmignore b/packages/shipa/charts/charts/mongodb/charts/common/.helmignore new file mode 100644 index 000000000..50af03172 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/.helmignore @@ -0,0 +1,22 @@ +# Patterns to ignore when building packages. +# This supports shell glob matching, relative path matching, and +# negation (prefixed with !). Only one pattern per line. +.DS_Store +# Common VCS dirs +.git/ +.gitignore +.bzr/ +.bzrignore +.hg/ +.hgignore +.svn/ +# Common backup files +*.swp +*.bak +*.tmp +*~ +# Various IDEs +.project +.idea/ +*.tmproj +.vscode/ diff --git a/packages/shipa/charts/charts/mongodb/charts/common/Chart.yaml b/packages/shipa/charts/charts/mongodb/charts/common/Chart.yaml new file mode 100644 index 000000000..87226649a --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/Chart.yaml @@ -0,0 +1,23 @@ +annotations: + category: Infrastructure +apiVersion: v2 +appVersion: 1.11.1 +description: A Library Helm Chart for grouping common logic between bitnami charts. + This chart is not deployable by itself. +home: https://github.com/bitnami/charts/tree/master/bitnami/common +icon: https://bitnami.com/downloads/logos/bitnami-mark.png +keywords: +- common +- helper +- template +- function +- bitnami +maintainers: +- email: containers@bitnami.com + name: Bitnami +name: common +sources: +- https://github.com/bitnami/charts +- https://www.bitnami.com/ +type: library +version: 1.11.1 diff --git a/packages/shipa/charts/charts/mongodb/charts/common/README.md b/packages/shipa/charts/charts/mongodb/charts/common/README.md new file mode 100644 index 000000000..da84c426d --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/README.md @@ -0,0 +1,345 @@ +# Bitnami Common Library Chart + +A [Helm Library Chart](https://helm.sh/docs/topics/library_charts/#helm) for grouping common logic between bitnami charts. + +## TL;DR + +```yaml +dependencies: + - name: common + version: 0.x.x + repository: https://charts.bitnami.com/bitnami +``` + +```bash +$ helm dependency update +``` + +```yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "common.names.fullname" . }} +data: + myvalue: "Hello World" +``` + +## Introduction + +This chart provides a common template helpers which can be used to develop new charts using [Helm](https://helm.sh) package manager. + +Bitnami charts can be used with [Kubeapps](https://kubeapps.com/) for deployment and management of Helm Charts in clusters. This Helm chart has been tested on top of [Bitnami Kubernetes Production Runtime](https://kubeprod.io/) (BKPR). Deploy BKPR to get automated TLS certificates, logging and monitoring for your applications. + +## Prerequisites + +- Kubernetes 1.19+ +- Helm 3.2.0+ + +## Parameters + +The following table lists the helpers available in the library which are scoped in different sections. + +### Affinities + +| Helper identifier | Description | Expected Input | +|-------------------------------|------------------------------------------------------|------------------------------------------------| +| `common.affinities.node.soft` | Return a soft nodeAffinity definition | `dict "key" "FOO" "values" (list "BAR" "BAZ")` | +| `common.affinities.node.hard` | Return a hard nodeAffinity definition | `dict "key" "FOO" "values" (list "BAR" "BAZ")` | +| `common.affinities.pod.soft` | Return a soft podAffinity/podAntiAffinity definition | `dict "component" "FOO" "context" $` | +| `common.affinities.pod.hard` | Return a hard podAffinity/podAntiAffinity definition | `dict "component" "FOO" "context" $` | + +### Capabilities + +| Helper identifier | Description | Expected Input | +|------------------------------------------------|------------------------------------------------------------------------------------------------|-------------------| +| `common.capabilities.kubeVersion` | Return the target Kubernetes version (using client default if .Values.kubeVersion is not set). | `.` Chart context | +| `common.capabilities.cronjob.apiVersion` | Return the appropriate apiVersion for cronjob. | `.` Chart context | +| `common.capabilities.deployment.apiVersion` | Return the appropriate apiVersion for deployment. | `.` Chart context | +| `common.capabilities.statefulset.apiVersion` | Return the appropriate apiVersion for statefulset. | `.` Chart context | +| `common.capabilities.ingress.apiVersion` | Return the appropriate apiVersion for ingress. | `.` Chart context | +| `common.capabilities.rbac.apiVersion` | Return the appropriate apiVersion for RBAC resources. | `.` Chart context | +| `common.capabilities.crd.apiVersion` | Return the appropriate apiVersion for CRDs. | `.` Chart context | +| `common.capabilities.policy.apiVersion` | Return the appropriate apiVersion for podsecuritypolicy. | `.` Chart context | +| `common.capabilities.networkPolicy.apiVersion` | Return the appropriate apiVersion for networkpolicy. | `.` Chart context | +| `common.capabilities.supportsHelmVersion` | Returns true if the used Helm version is 3.3+ | `.` Chart context | + +### Errors + +| Helper identifier | Description | Expected Input | +|-----------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------| +| `common.errors.upgrade.passwords.empty` | It will ensure required passwords are given when we are upgrading a chart. If `validationErrors` is not empty it will throw an error and will stop the upgrade action. | `dict "validationErrors" (list $validationError00 $validationError01) "context" $` | + +### Images + +| Helper identifier | Description | Expected Input | +|-----------------------------|------------------------------------------------------|---------------------------------------------------------------------------------------------------------| +| `common.images.image` | Return the proper and full image name | `dict "imageRoot" .Values.path.to.the.image "global" $`, see [ImageRoot](#imageroot) for the structure. | +| `common.images.pullSecrets` | Return the proper Docker Image Registry Secret Names (deprecated: use common.images.renderPullSecrets instead) | `dict "images" (list .Values.path.to.the.image1, .Values.path.to.the.image2) "global" .Values.global` | +| `common.images.renderPullSecrets` | Return the proper Docker Image Registry Secret Names (evaluates values as templates) | `dict "images" (list .Values.path.to.the.image1, .Values.path.to.the.image2) "context" $` | + +### Ingress + +| Helper identifier | Description | Expected Input | +|-------------------------------------------|-------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `common.ingress.backend` | Generate a proper Ingress backend entry depending on the API version | `dict "serviceName" "foo" "servicePort" "bar"`, see the [Ingress deprecation notice](https://kubernetes.io/blog/2019/07/18/api-deprecations-in-1-16/) for the syntax differences | +| `common.ingress.supportsPathType` | Prints "true" if the pathType field is supported | `.` Chart context | +| `common.ingress.supportsIngressClassname` | Prints "true" if the ingressClassname field is supported | `.` Chart context | +| `common.ingress.certManagerRequest` | Prints "true" if required cert-manager annotations for TLS signed certificates are set in the Ingress annotations | `dict "annotations" .Values.path.to.the.ingress.annotations` | + +### Labels + +| Helper identifier | Description | Expected Input | +|-----------------------------|------------------------------------------------------|-------------------| +| `common.labels.standard` | Return Kubernetes standard labels | `.` Chart context | +| `common.labels.matchLabels` | Return the proper Docker Image Registry Secret Names | `.` Chart context | + +### Names + +| Helper identifier | Description | Expected Input | +|-------------------------|------------------------------------------------------------|-------------------| +| `common.names.name` | Expand the name of the chart or use `.Values.nameOverride` | `.` Chart context | +| `common.names.fullname` | Create a default fully qualified app name. | `.` Chart context | +| `common.names.chart` | Chart name plus version | `.` Chart context | + +### Secrets + +| Helper identifier | Description | Expected Input | +|---------------------------|--------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `common.secrets.name` | Generate the name of the secret. | `dict "existingSecret" .Values.path.to.the.existingSecret "defaultNameSuffix" "mySuffix" "context" $` see [ExistingSecret](#existingsecret) for the structure. | +| `common.secrets.key` | Generate secret key. | `dict "existingSecret" .Values.path.to.the.existingSecret "key" "keyName"` see [ExistingSecret](#existingsecret) for the structure. | +| `common.passwords.manage` | Generate secret password or retrieve one if already created. | `dict "secret" "secret-name" "key" "keyName" "providedValues" (list "path.to.password1" "path.to.password2") "length" 10 "strong" false "chartName" "chartName" "context" $`, length, strong and chartNAme fields are optional. | +| `common.secrets.exists` | Returns whether a previous generated secret already exists. | `dict "secret" "secret-name" "context" $` | + +### Storage + +| Helper identifier | Description | Expected Input | +|-------------------------------|---------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| `common.storage.class` | Return the proper Storage Class | `dict "persistence" .Values.path.to.the.persistence "global" $`, see [Persistence](#persistence) for the structure. | + +### TplValues + +| Helper identifier | Description | Expected Input | +|---------------------------|----------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------| +| `common.tplvalues.render` | Renders a value that contains template | `dict "value" .Values.path.to.the.Value "context" $`, value is the value should rendered as template, context frequently is the chart context `$` or `.` | + +### Utils + +| Helper identifier | Description | Expected Input | +|--------------------------------|------------------------------------------------------------------------------------------|------------------------------------------------------------------------| +| `common.utils.fieldToEnvVar` | Build environment variable name given a field. | `dict "field" "my-password"` | +| `common.utils.secret.getvalue` | Print instructions to get a secret value. | `dict "secret" "secret-name" "field" "secret-value-field" "context" $` | +| `common.utils.getValueFromKey` | Gets a value from `.Values` object given its key path | `dict "key" "path.to.key" "context" $` | +| `common.utils.getKeyFromList` | Returns first `.Values` key with a defined value or first of the list if all non-defined | `dict "keys" (list "path.to.key1" "path.to.key2") "context" $` | + +### Validations + +| Helper identifier | Description | Expected Input | +|--------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `common.validations.values.single.empty` | Validate a value must not be empty. | `dict "valueKey" "path.to.value" "secret" "secret.name" "field" "my-password" "subchart" "subchart" "context" $` secret, field and subchart are optional. In case they are given, the helper will generate a how to get instruction. See [ValidateValue](#validatevalue) | +| `common.validations.values.multiple.empty` | Validate a multiple values must not be empty. It returns a shared error for all the values. | `dict "required" (list $validateValueConf00 $validateValueConf01) "context" $`. See [ValidateValue](#validatevalue) | +| `common.validations.values.mariadb.passwords` | This helper will ensure required password for MariaDB are not empty. It returns a shared error for all the values. | `dict "secret" "mariadb-secret" "subchart" "true" "context" $` subchart field is optional and could be true or false it depends on where you will use mariadb chart and the helper. | +| `common.validations.values.postgresql.passwords` | This helper will ensure required password for PostgreSQL are not empty. It returns a shared error for all the values. | `dict "secret" "postgresql-secret" "subchart" "true" "context" $` subchart field is optional and could be true or false it depends on where you will use postgresql chart and the helper. | +| `common.validations.values.redis.passwords` | This helper will ensure required password for Redis™ are not empty. It returns a shared error for all the values. | `dict "secret" "redis-secret" "subchart" "true" "context" $` subchart field is optional and could be true or false it depends on where you will use redis chart and the helper. | +| `common.validations.values.cassandra.passwords` | This helper will ensure required password for Cassandra are not empty. It returns a shared error for all the values. | `dict "secret" "cassandra-secret" "subchart" "true" "context" $` subchart field is optional and could be true or false it depends on where you will use cassandra chart and the helper. | +| `common.validations.values.mongodb.passwords` | This helper will ensure required password for MongoDB® are not empty. It returns a shared error for all the values. | `dict "secret" "mongodb-secret" "subchart" "true" "context" $` subchart field is optional and could be true or false it depends on where you will use mongodb chart and the helper. | + +### Warnings + +| Helper identifier | Description | Expected Input | +|------------------------------|----------------------------------|------------------------------------------------------------| +| `common.warnings.rollingTag` | Warning about using rolling tag. | `ImageRoot` see [ImageRoot](#imageroot) for the structure. | + +## Special input schemas + +### ImageRoot + +```yaml +registry: + type: string + description: Docker registry where the image is located + example: docker.io + +repository: + type: string + description: Repository and image name + example: bitnami/nginx + +tag: + type: string + description: image tag + example: 1.16.1-debian-10-r63 + +pullPolicy: + type: string + description: Specify a imagePullPolicy. Defaults to 'Always' if image tag is 'latest', else set to 'IfNotPresent' + +pullSecrets: + type: array + items: + type: string + description: Optionally specify an array of imagePullSecrets (evaluated as templates). + +debug: + type: boolean + description: Set to true if you would like to see extra information on logs + example: false + +## An instance would be: +# registry: docker.io +# repository: bitnami/nginx +# tag: 1.16.1-debian-10-r63 +# pullPolicy: IfNotPresent +# debug: false +``` + +### Persistence + +```yaml +enabled: + type: boolean + description: Whether enable persistence. + example: true + +storageClass: + type: string + description: Ghost data Persistent Volume Storage Class, If set to "-", storageClassName: "" which disables dynamic provisioning. + example: "-" + +accessMode: + type: string + description: Access mode for the Persistent Volume Storage. + example: ReadWriteOnce + +size: + type: string + description: Size the Persistent Volume Storage. + example: 8Gi + +path: + type: string + description: Path to be persisted. + example: /bitnami + +## An instance would be: +# enabled: true +# storageClass: "-" +# accessMode: ReadWriteOnce +# size: 8Gi +# path: /bitnami +``` + +### ExistingSecret + +```yaml +name: + type: string + description: Name of the existing secret. + example: mySecret +keyMapping: + description: Mapping between the expected key name and the name of the key in the existing secret. + type: object + +## An instance would be: +# name: mySecret +# keyMapping: +# password: myPasswordKey +``` + +#### Example of use + +When we store sensitive data for a deployment in a secret, some times we want to give to users the possibility of using theirs existing secrets. + +```yaml +# templates/secret.yaml +--- +apiVersion: v1 +kind: Secret +metadata: + name: {{ include "common.names.fullname" . }} + labels: + app: {{ include "common.names.fullname" . }} +type: Opaque +data: + password: {{ .Values.password | b64enc | quote }} + +# templates/dpl.yaml +--- +... + env: + - name: PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "common.secrets.name" (dict "existingSecret" .Values.existingSecret "context" $) }} + key: {{ include "common.secrets.key" (dict "existingSecret" .Values.existingSecret "key" "password") }} +... + +# values.yaml +--- +name: mySecret +keyMapping: + password: myPasswordKey +``` + +### ValidateValue + +#### NOTES.txt + +```console +{{- $validateValueConf00 := (dict "valueKey" "path.to.value00" "secret" "secretName" "field" "password-00") -}} +{{- $validateValueConf01 := (dict "valueKey" "path.to.value01" "secret" "secretName" "field" "password-01") -}} + +{{ include "common.validations.values.multiple.empty" (dict "required" (list $validateValueConf00 $validateValueConf01) "context" $) }} +``` + +If we force those values to be empty we will see some alerts + +```console +$ helm install test mychart --set path.to.value00="",path.to.value01="" + 'path.to.value00' must not be empty, please add '--set path.to.value00=$PASSWORD_00' to the command. To get the current value: + + export PASSWORD_00=$(kubectl get secret --namespace default secretName -o jsonpath="{.data.password-00}" | base64 --decode) + + 'path.to.value01' must not be empty, please add '--set path.to.value01=$PASSWORD_01' to the command. To get the current value: + + export PASSWORD_01=$(kubectl get secret --namespace default secretName -o jsonpath="{.data.password-01}" | base64 --decode) +``` + +## Upgrading + +### To 1.0.0 + +[On November 13, 2020, Helm v2 support was formally finished](https://github.com/helm/charts#status-of-the-project), this major version is the result of the required changes applied to the Helm Chart to be able to incorporate the different features added in Helm v3 and to be consistent with the Helm project itself regarding the Helm v2 EOL. + +**What changes were introduced in this major version?** + +- Previous versions of this Helm Chart use `apiVersion: v1` (installable by both Helm 2 and 3), this Helm Chart was updated to `apiVersion: v2` (installable by Helm 3 only). [Here](https://helm.sh/docs/topics/charts/#the-apiversion-field) you can find more information about the `apiVersion` field. +- Use `type: library`. [Here](https://v3.helm.sh/docs/faq/#library-chart-support) you can find more information. +- The different fields present in the *Chart.yaml* file has been ordered alphabetically in a homogeneous way for all the Bitnami Helm Charts + +**Considerations when upgrading to this version** + +- If you want to upgrade to this version from a previous one installed with Helm v3, you shouldn't face any issues +- If you want to upgrade to this version using Helm v2, this scenario is not supported as this version doesn't support Helm v2 anymore +- If you installed the previous version with Helm v2 and wants to upgrade to this version with Helm v3, please refer to the [official Helm documentation](https://helm.sh/docs/topics/v2_v3_migration/#migration-use-cases) about migrating from Helm v2 to v3 + +**Useful links** + +- https://docs.bitnami.com/tutorials/resolve-helm2-helm3-post-migration-issues/ +- https://helm.sh/docs/topics/v2_v3_migration/ +- https://helm.sh/blog/migrate-from-helm-v2-to-helm-v3/ + +## License + +Copyright © 2022 Bitnami + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/_affinities.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/_affinities.tpl new file mode 100644 index 000000000..189ea403d --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/_affinities.tpl @@ -0,0 +1,102 @@ +{{/* vim: set filetype=mustache: */}} + +{{/* +Return a soft nodeAffinity definition +{{ include "common.affinities.nodes.soft" (dict "key" "FOO" "values" (list "BAR" "BAZ")) -}} +*/}} +{{- define "common.affinities.nodes.soft" -}} +preferredDuringSchedulingIgnoredDuringExecution: + - preference: + matchExpressions: + - key: {{ .key }} + operator: In + values: + {{- range .values }} + - {{ . | quote }} + {{- end }} + weight: 1 +{{- end -}} + +{{/* +Return a hard nodeAffinity definition +{{ include "common.affinities.nodes.hard" (dict "key" "FOO" "values" (list "BAR" "BAZ")) -}} +*/}} +{{- define "common.affinities.nodes.hard" -}} +requiredDuringSchedulingIgnoredDuringExecution: + nodeSelectorTerms: + - matchExpressions: + - key: {{ .key }} + operator: In + values: + {{- range .values }} + - {{ . | quote }} + {{- end }} +{{- end -}} + +{{/* +Return a nodeAffinity definition +{{ include "common.affinities.nodes" (dict "type" "soft" "key" "FOO" "values" (list "BAR" "BAZ")) -}} +*/}} +{{- define "common.affinities.nodes" -}} + {{- if eq .type "soft" }} + {{- include "common.affinities.nodes.soft" . -}} + {{- else if eq .type "hard" }} + {{- include "common.affinities.nodes.hard" . -}} + {{- end -}} +{{- end -}} + +{{/* +Return a soft podAffinity/podAntiAffinity definition +{{ include "common.affinities.pods.soft" (dict "component" "FOO" "extraMatchLabels" .Values.extraMatchLabels "context" $) -}} +*/}} +{{- define "common.affinities.pods.soft" -}} +{{- $component := default "" .component -}} +{{- $extraMatchLabels := default (dict) .extraMatchLabels -}} +preferredDuringSchedulingIgnoredDuringExecution: + - podAffinityTerm: + labelSelector: + matchLabels: {{- (include "common.labels.matchLabels" .context) | nindent 10 }} + {{- if not (empty $component) }} + {{ printf "app.kubernetes.io/component: %s" $component }} + {{- end }} + {{- range $key, $value := $extraMatchLabels }} + {{ $key }}: {{ $value | quote }} + {{- end }} + namespaces: + - {{ .context.Release.Namespace | quote }} + topologyKey: kubernetes.io/hostname + weight: 1 +{{- end -}} + +{{/* +Return a hard podAffinity/podAntiAffinity definition +{{ include "common.affinities.pods.hard" (dict "component" "FOO" "extraMatchLabels" .Values.extraMatchLabels "context" $) -}} +*/}} +{{- define "common.affinities.pods.hard" -}} +{{- $component := default "" .component -}} +{{- $extraMatchLabels := default (dict) .extraMatchLabels -}} +requiredDuringSchedulingIgnoredDuringExecution: + - labelSelector: + matchLabels: {{- (include "common.labels.matchLabels" .context) | nindent 8 }} + {{- if not (empty $component) }} + {{ printf "app.kubernetes.io/component: %s" $component }} + {{- end }} + {{- range $key, $value := $extraMatchLabels }} + {{ $key }}: {{ $value | quote }} + {{- end }} + namespaces: + - {{ .context.Release.Namespace | quote }} + topologyKey: kubernetes.io/hostname +{{- end -}} + +{{/* +Return a podAffinity/podAntiAffinity definition +{{ include "common.affinities.pods" (dict "type" "soft" "key" "FOO" "values" (list "BAR" "BAZ")) -}} +*/}} +{{- define "common.affinities.pods" -}} + {{- if eq .type "soft" }} + {{- include "common.affinities.pods.soft" . -}} + {{- else if eq .type "hard" }} + {{- include "common.affinities.pods.hard" . -}} + {{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/_capabilities.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/_capabilities.tpl new file mode 100644 index 000000000..b94212bbe --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/_capabilities.tpl @@ -0,0 +1,128 @@ +{{/* vim: set filetype=mustache: */}} + +{{/* +Return the target Kubernetes version +*/}} +{{- define "common.capabilities.kubeVersion" -}} +{{- if .Values.global }} + {{- if .Values.global.kubeVersion }} + {{- .Values.global.kubeVersion -}} + {{- else }} + {{- default .Capabilities.KubeVersion.Version .Values.kubeVersion -}} + {{- end -}} +{{- else }} +{{- default .Capabilities.KubeVersion.Version .Values.kubeVersion -}} +{{- end -}} +{{- end -}} + +{{/* +Return the appropriate apiVersion for poddisruptionbudget. +*/}} +{{- define "common.capabilities.policy.apiVersion" -}} +{{- if semverCompare "<1.21-0" (include "common.capabilities.kubeVersion" .) -}} +{{- print "policy/v1beta1" -}} +{{- else -}} +{{- print "policy/v1" -}} +{{- end -}} +{{- end -}} + +{{/* +Return the appropriate apiVersion for networkpolicy. +*/}} +{{- define "common.capabilities.networkPolicy.apiVersion" -}} +{{- if semverCompare "<1.7-0" (include "common.capabilities.kubeVersion" .) -}} +{{- print "extensions/v1beta1" -}} +{{- else -}} +{{- print "networking.k8s.io/v1" -}} +{{- end -}} +{{- end -}} + +{{/* +Return the appropriate apiVersion for cronjob. +*/}} +{{- define "common.capabilities.cronjob.apiVersion" -}} +{{- if semverCompare "<1.21-0" (include "common.capabilities.kubeVersion" .) -}} +{{- print "batch/v1beta1" -}} +{{- else -}} +{{- print "batch/v1" -}} +{{- end -}} +{{- end -}} + +{{/* +Return the appropriate apiVersion for deployment. +*/}} +{{- define "common.capabilities.deployment.apiVersion" -}} +{{- if semverCompare "<1.14-0" (include "common.capabilities.kubeVersion" .) -}} +{{- print "extensions/v1beta1" -}} +{{- else -}} +{{- print "apps/v1" -}} +{{- end -}} +{{- end -}} + +{{/* +Return the appropriate apiVersion for statefulset. +*/}} +{{- define "common.capabilities.statefulset.apiVersion" -}} +{{- if semverCompare "<1.14-0" (include "common.capabilities.kubeVersion" .) -}} +{{- print "apps/v1beta1" -}} +{{- else -}} +{{- print "apps/v1" -}} +{{- end -}} +{{- end -}} + +{{/* +Return the appropriate apiVersion for ingress. +*/}} +{{- define "common.capabilities.ingress.apiVersion" -}} +{{- if .Values.ingress -}} +{{- if .Values.ingress.apiVersion -}} +{{- .Values.ingress.apiVersion -}} +{{- else if semverCompare "<1.14-0" (include "common.capabilities.kubeVersion" .) -}} +{{- print "extensions/v1beta1" -}} +{{- else if semverCompare "<1.19-0" (include "common.capabilities.kubeVersion" .) -}} +{{- print "networking.k8s.io/v1beta1" -}} +{{- else -}} +{{- print "networking.k8s.io/v1" -}} +{{- end }} +{{- else if semverCompare "<1.14-0" (include "common.capabilities.kubeVersion" .) -}} +{{- print "extensions/v1beta1" -}} +{{- else if semverCompare "<1.19-0" (include "common.capabilities.kubeVersion" .) -}} +{{- print "networking.k8s.io/v1beta1" -}} +{{- else -}} +{{- print "networking.k8s.io/v1" -}} +{{- end -}} +{{- end -}} + +{{/* +Return the appropriate apiVersion for RBAC resources. +*/}} +{{- define "common.capabilities.rbac.apiVersion" -}} +{{- if semverCompare "<1.17-0" (include "common.capabilities.kubeVersion" .) -}} +{{- print "rbac.authorization.k8s.io/v1beta1" -}} +{{- else -}} +{{- print "rbac.authorization.k8s.io/v1" -}} +{{- end -}} +{{- end -}} + +{{/* +Return the appropriate apiVersion for CRDs. +*/}} +{{- define "common.capabilities.crd.apiVersion" -}} +{{- if semverCompare "<1.19-0" (include "common.capabilities.kubeVersion" .) -}} +{{- print "apiextensions.k8s.io/v1beta1" -}} +{{- else -}} +{{- print "apiextensions.k8s.io/v1" -}} +{{- end -}} +{{- end -}} + +{{/* +Returns true if the used Helm version is 3.3+. +A way to check the used Helm version was not introduced until version 3.3.0 with .Capabilities.HelmVersion, which contains an additional "{}}" structure. +This check is introduced as a regexMatch instead of {{ if .Capabilities.HelmVersion }} because checking for the key HelmVersion in <3.3 results in a "interface not found" error. +**To be removed when the catalog's minimun Helm version is 3.3** +*/}} +{{- define "common.capabilities.supportsHelmVersion" -}} +{{- if regexMatch "{(v[0-9])*[^}]*}}$" (.Capabilities | toString ) }} + {{- true -}} +{{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/_errors.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/_errors.tpl new file mode 100644 index 000000000..a79cc2e32 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/_errors.tpl @@ -0,0 +1,23 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Through error when upgrading using empty passwords values that must not be empty. + +Usage: +{{- $validationError00 := include "common.validations.values.single.empty" (dict "valueKey" "path.to.password00" "secret" "secretName" "field" "password-00") -}} +{{- $validationError01 := include "common.validations.values.single.empty" (dict "valueKey" "path.to.password01" "secret" "secretName" "field" "password-01") -}} +{{ include "common.errors.upgrade.passwords.empty" (dict "validationErrors" (list $validationError00 $validationError01) "context" $) }} + +Required password params: + - validationErrors - String - Required. List of validation strings to be return, if it is empty it won't throw error. + - context - Context - Required. Parent context. +*/}} +{{- define "common.errors.upgrade.passwords.empty" -}} + {{- $validationErrors := join "" .validationErrors -}} + {{- if and $validationErrors .context.Release.IsUpgrade -}} + {{- $errorString := "\nPASSWORDS ERROR: You must provide your current passwords when upgrading the release." -}} + {{- $errorString = print $errorString "\n Note that even after reinstallation, old credentials may be needed as they may be kept in persistent volume claims." -}} + {{- $errorString = print $errorString "\n Further information can be obtained at https://docs.bitnami.com/general/how-to/troubleshoot-helm-chart-issues/#credential-errors-while-upgrading-chart-releases" -}} + {{- $errorString = print $errorString "\n%s" -}} + {{- printf $errorString $validationErrors | fail -}} + {{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/_images.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/_images.tpl new file mode 100644 index 000000000..42ffbc722 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/_images.tpl @@ -0,0 +1,75 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Return the proper image name +{{ include "common.images.image" ( dict "imageRoot" .Values.path.to.the.image "global" $) }} +*/}} +{{- define "common.images.image" -}} +{{- $registryName := .imageRoot.registry -}} +{{- $repositoryName := .imageRoot.repository -}} +{{- $tag := .imageRoot.tag | toString -}} +{{- if .global }} + {{- if .global.imageRegistry }} + {{- $registryName = .global.imageRegistry -}} + {{- end -}} +{{- end -}} +{{- if $registryName }} +{{- printf "%s/%s:%s" $registryName $repositoryName $tag -}} +{{- else -}} +{{- printf "%s:%s" $repositoryName $tag -}} +{{- end -}} +{{- end -}} + +{{/* +Return the proper Docker Image Registry Secret Names (deprecated: use common.images.renderPullSecrets instead) +{{ include "common.images.pullSecrets" ( dict "images" (list .Values.path.to.the.image1, .Values.path.to.the.image2) "global" .Values.global) }} +*/}} +{{- define "common.images.pullSecrets" -}} + {{- $pullSecrets := list }} + + {{- if .global }} + {{- range .global.imagePullSecrets -}} + {{- $pullSecrets = append $pullSecrets . -}} + {{- end -}} + {{- end -}} + + {{- range .images -}} + {{- range .pullSecrets -}} + {{- $pullSecrets = append $pullSecrets . -}} + {{- end -}} + {{- end -}} + + {{- if (not (empty $pullSecrets)) }} +imagePullSecrets: + {{- range $pullSecrets }} + - name: {{ . }} + {{- end }} + {{- end }} +{{- end -}} + +{{/* +Return the proper Docker Image Registry Secret Names evaluating values as templates +{{ include "common.images.renderPullSecrets" ( dict "images" (list .Values.path.to.the.image1, .Values.path.to.the.image2) "context" $) }} +*/}} +{{- define "common.images.renderPullSecrets" -}} + {{- $pullSecrets := list }} + {{- $context := .context }} + + {{- if $context.Values.global }} + {{- range $context.Values.global.imagePullSecrets -}} + {{- $pullSecrets = append $pullSecrets (include "common.tplvalues.render" (dict "value" . "context" $context)) -}} + {{- end -}} + {{- end -}} + + {{- range .images -}} + {{- range .pullSecrets -}} + {{- $pullSecrets = append $pullSecrets (include "common.tplvalues.render" (dict "value" . "context" $context)) -}} + {{- end -}} + {{- end -}} + + {{- if (not (empty $pullSecrets)) }} +imagePullSecrets: + {{- range $pullSecrets }} + - name: {{ . }} + {{- end }} + {{- end }} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/_ingress.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/_ingress.tpl new file mode 100644 index 000000000..8caf73a61 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/_ingress.tpl @@ -0,0 +1,68 @@ +{{/* vim: set filetype=mustache: */}} + +{{/* +Generate backend entry that is compatible with all Kubernetes API versions. + +Usage: +{{ include "common.ingress.backend" (dict "serviceName" "backendName" "servicePort" "backendPort" "context" $) }} + +Params: + - serviceName - String. Name of an existing service backend + - servicePort - String/Int. Port name (or number) of the service. It will be translated to different yaml depending if it is a string or an integer. + - context - Dict - Required. The context for the template evaluation. +*/}} +{{- define "common.ingress.backend" -}} +{{- $apiVersion := (include "common.capabilities.ingress.apiVersion" .context) -}} +{{- if or (eq $apiVersion "extensions/v1beta1") (eq $apiVersion "networking.k8s.io/v1beta1") -}} +serviceName: {{ .serviceName }} +servicePort: {{ .servicePort }} +{{- else -}} +service: + name: {{ .serviceName }} + port: + {{- if typeIs "string" .servicePort }} + name: {{ .servicePort }} + {{- else if or (typeIs "int" .servicePort) (typeIs "float64" .servicePort) }} + number: {{ .servicePort | int }} + {{- end }} +{{- end -}} +{{- end -}} + +{{/* +Print "true" if the API pathType field is supported +Usage: +{{ include "common.ingress.supportsPathType" . }} +*/}} +{{- define "common.ingress.supportsPathType" -}} +{{- if (semverCompare "<1.18-0" (include "common.capabilities.kubeVersion" .)) -}} +{{- print "false" -}} +{{- else -}} +{{- print "true" -}} +{{- end -}} +{{- end -}} + +{{/* +Returns true if the ingressClassname field is supported +Usage: +{{ include "common.ingress.supportsIngressClassname" . }} +*/}} +{{- define "common.ingress.supportsIngressClassname" -}} +{{- if semverCompare "<1.18-0" (include "common.capabilities.kubeVersion" .) -}} +{{- print "false" -}} +{{- else -}} +{{- print "true" -}} +{{- end -}} +{{- end -}} + +{{/* +Return true if cert-manager required annotations for TLS signed +certificates are set in the Ingress annotations +Ref: https://cert-manager.io/docs/usage/ingress/#supported-annotations +Usage: +{{ include "common.ingress.certManagerRequest" ( dict "annotations" .Values.path.to.the.ingress.annotations ) }} +*/}} +{{- define "common.ingress.certManagerRequest" -}} +{{ if or (hasKey .annotations "cert-manager.io/cluster-issuer") (hasKey .annotations "cert-manager.io/issuer") }} + {{- true -}} +{{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/_labels.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/_labels.tpl new file mode 100644 index 000000000..252066c7e --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/_labels.tpl @@ -0,0 +1,18 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Kubernetes standard labels +*/}} +{{- define "common.labels.standard" -}} +app.kubernetes.io/name: {{ include "common.names.name" . }} +helm.sh/chart: {{ include "common.names.chart" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end -}} + +{{/* +Labels to use on deploy.spec.selector.matchLabels and svc.spec.selector +*/}} +{{- define "common.labels.matchLabels" -}} +app.kubernetes.io/name: {{ include "common.names.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/_names.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/_names.tpl new file mode 100644 index 000000000..cf0323171 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/_names.tpl @@ -0,0 +1,52 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Expand the name of the chart. +*/}} +{{- define "common.names.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "common.names.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{/* +Create a default fully qualified app name. +We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). +If release name contains chart name it will be used as a full name. +*/}} +{{- define "common.names.fullname" -}} +{{- if .Values.fullnameOverride -}} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- $name := default .Chart.Name .Values.nameOverride -}} +{{- if contains $name .Release.Name -}} +{{- .Release.Name | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}} +{{- end -}} +{{- end -}} +{{- end -}} + +{{/* +Create a default fully qualified dependency name. +We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). +If release name contains chart name it will be used as a full name. +Usage: +{{ include "common.names.dependency.fullname" (dict "chartName" "dependency-chart-name" "chartValues" .Values.dependency-chart "context" $) }} +*/}} +{{- define "common.names.dependency.fullname" -}} +{{- if .chartValues.fullnameOverride -}} +{{- .chartValues.fullnameOverride | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- $name := default .chartName .chartValues.nameOverride -}} +{{- if contains $name .context.Release.Name -}} +{{- .context.Release.Name | trunc 63 | trimSuffix "-" -}} +{{- else -}} +{{- printf "%s-%s" .context.Release.Name $name | trunc 63 | trimSuffix "-" -}} +{{- end -}} +{{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/_secrets.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/_secrets.tpl new file mode 100644 index 000000000..a1afc1195 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/_secrets.tpl @@ -0,0 +1,131 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Generate secret name. + +Usage: +{{ include "common.secrets.name" (dict "existingSecret" .Values.path.to.the.existingSecret "defaultNameSuffix" "mySuffix" "context" $) }} + +Params: + - existingSecret - ExistingSecret/String - Optional. The path to the existing secrets in the values.yaml given by the user + to be used instead of the default one. Allows for it to be of type String (just the secret name) for backwards compatibility. + +info: https://github.com/bitnami/charts/tree/master/bitnami/common#existingsecret + - defaultNameSuffix - String - Optional. It is used only if we have several secrets in the same deployment. + - context - Dict - Required. The context for the template evaluation. +*/}} +{{- define "common.secrets.name" -}} +{{- $name := (include "common.names.fullname" .context) -}} + +{{- if .defaultNameSuffix -}} +{{- $name = printf "%s-%s" $name .defaultNameSuffix | trunc 63 | trimSuffix "-" -}} +{{- end -}} + +{{- with .existingSecret -}} +{{- if not (typeIs "string" .) -}} +{{- with .name -}} +{{- $name = . -}} +{{- end -}} +{{- else -}} +{{- $name = . -}} +{{- end -}} +{{- end -}} + +{{- printf "%s" $name -}} +{{- end -}} + +{{/* +Generate secret key. + +Usage: +{{ include "common.secrets.key" (dict "existingSecret" .Values.path.to.the.existingSecret "key" "keyName") }} + +Params: + - existingSecret - ExistingSecret/String - Optional. The path to the existing secrets in the values.yaml given by the user + to be used instead of the default one. Allows for it to be of type String (just the secret name) for backwards compatibility. + +info: https://github.com/bitnami/charts/tree/master/bitnami/common#existingsecret + - key - String - Required. Name of the key in the secret. +*/}} +{{- define "common.secrets.key" -}} +{{- $key := .key -}} + +{{- if .existingSecret -}} + {{- if not (typeIs "string" .existingSecret) -}} + {{- if .existingSecret.keyMapping -}} + {{- $key = index .existingSecret.keyMapping $.key -}} + {{- end -}} + {{- end }} +{{- end -}} + +{{- printf "%s" $key -}} +{{- end -}} + +{{/* +Generate secret password or retrieve one if already created. + +Usage: +{{ include "common.secrets.passwords.manage" (dict "secret" "secret-name" "key" "keyName" "providedValues" (list "path.to.password1" "path.to.password2") "length" 10 "strong" false "chartName" "chartName" "context" $) }} + +Params: + - secret - String - Required - Name of the 'Secret' resource where the password is stored. + - key - String - Required - Name of the key in the secret. + - providedValues - List - Required - The path to the validating value in the values.yaml, e.g: "mysql.password". Will pick first parameter with a defined value. + - length - int - Optional - Length of the generated random password. + - strong - Boolean - Optional - Whether to add symbols to the generated random password. + - chartName - String - Optional - Name of the chart used when said chart is deployed as a subchart. + - context - Context - Required - Parent context. +*/}} +{{- define "common.secrets.passwords.manage" -}} + +{{- $password := "" }} +{{- $subchart := "" }} +{{- $chartName := default "" .chartName }} +{{- $passwordLength := default 10 .length }} +{{- $providedPasswordKey := include "common.utils.getKeyFromList" (dict "keys" .providedValues "context" $.context) }} +{{- $providedPasswordValue := include "common.utils.getValueFromKey" (dict "key" $providedPasswordKey "context" $.context) }} +{{- $secretData := (lookup "v1" "Secret" $.context.Release.Namespace .secret).data }} +{{- if $secretData }} + {{- if hasKey $secretData .key }} + {{- $password = index $secretData .key }} + {{- else }} + {{- printf "\nPASSWORDS ERROR: The secret \"%s\" does not contain the key \"%s\"\n" .secret .key | fail -}} + {{- end -}} +{{- else if $providedPasswordValue }} + {{- $password = $providedPasswordValue | toString | b64enc | quote }} +{{- else }} + + {{- if .context.Values.enabled }} + {{- $subchart = $chartName }} + {{- end -}} + + {{- $requiredPassword := dict "valueKey" $providedPasswordKey "secret" .secret "field" .key "subchart" $subchart "context" $.context -}} + {{- $requiredPasswordError := include "common.validations.values.single.empty" $requiredPassword -}} + {{- $passwordValidationErrors := list $requiredPasswordError -}} + {{- include "common.errors.upgrade.passwords.empty" (dict "validationErrors" $passwordValidationErrors "context" $.context) -}} + + {{- if .strong }} + {{- $subStr := list (lower (randAlpha 1)) (randNumeric 1) (upper (randAlpha 1)) | join "_" }} + {{- $password = randAscii $passwordLength }} + {{- $password = regexReplaceAllLiteral "\\W" $password "@" | substr 5 $passwordLength }} + {{- $password = printf "%s%s" $subStr $password | toString | shuffle | b64enc | quote }} + {{- else }} + {{- $password = randAlphaNum $passwordLength | b64enc | quote }} + {{- end }} +{{- end -}} +{{- printf "%s" $password -}} +{{- end -}} + +{{/* +Returns whether a previous generated secret already exists + +Usage: +{{ include "common.secrets.exists" (dict "secret" "secret-name" "context" $) }} + +Params: + - secret - String - Required - Name of the 'Secret' resource where the password is stored. + - context - Context - Required - Parent context. +*/}} +{{- define "common.secrets.exists" -}} +{{- $secret := (lookup "v1" "Secret" $.context.Release.Namespace .secret) }} +{{- if $secret }} + {{- true -}} +{{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/_storage.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/_storage.tpl new file mode 100644 index 000000000..60e2a844f --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/_storage.tpl @@ -0,0 +1,23 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Return the proper Storage Class +{{ include "common.storage.class" ( dict "persistence" .Values.path.to.the.persistence "global" $) }} +*/}} +{{- define "common.storage.class" -}} + +{{- $storageClass := .persistence.storageClass -}} +{{- if .global -}} + {{- if .global.storageClass -}} + {{- $storageClass = .global.storageClass -}} + {{- end -}} +{{- end -}} + +{{- if $storageClass -}} + {{- if (eq "-" $storageClass) -}} + {{- printf "storageClassName: \"\"" -}} + {{- else }} + {{- printf "storageClassName: %s" $storageClass -}} + {{- end -}} +{{- end -}} + +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/_tplvalues.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/_tplvalues.tpl new file mode 100644 index 000000000..2db166851 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/_tplvalues.tpl @@ -0,0 +1,13 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Renders a value that contains template. +Usage: +{{ include "common.tplvalues.render" ( dict "value" .Values.path.to.the.Value "context" $) }} +*/}} +{{- define "common.tplvalues.render" -}} + {{- if typeIs "string" .value }} + {{- tpl .value .context }} + {{- else }} + {{- tpl (.value | toYaml) .context }} + {{- end }} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/_utils.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/_utils.tpl new file mode 100644 index 000000000..ea083a249 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/_utils.tpl @@ -0,0 +1,62 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Print instructions to get a secret value. +Usage: +{{ include "common.utils.secret.getvalue" (dict "secret" "secret-name" "field" "secret-value-field" "context" $) }} +*/}} +{{- define "common.utils.secret.getvalue" -}} +{{- $varname := include "common.utils.fieldToEnvVar" . -}} +export {{ $varname }}=$(kubectl get secret --namespace {{ .context.Release.Namespace | quote }} {{ .secret }} -o jsonpath="{.data.{{ .field }}}" | base64 --decode) +{{- end -}} + +{{/* +Build env var name given a field +Usage: +{{ include "common.utils.fieldToEnvVar" dict "field" "my-password" }} +*/}} +{{- define "common.utils.fieldToEnvVar" -}} + {{- $fieldNameSplit := splitList "-" .field -}} + {{- $upperCaseFieldNameSplit := list -}} + + {{- range $fieldNameSplit -}} + {{- $upperCaseFieldNameSplit = append $upperCaseFieldNameSplit ( upper . ) -}} + {{- end -}} + + {{ join "_" $upperCaseFieldNameSplit }} +{{- end -}} + +{{/* +Gets a value from .Values given +Usage: +{{ include "common.utils.getValueFromKey" (dict "key" "path.to.key" "context" $) }} +*/}} +{{- define "common.utils.getValueFromKey" -}} +{{- $splitKey := splitList "." .key -}} +{{- $value := "" -}} +{{- $latestObj := $.context.Values -}} +{{- range $splitKey -}} + {{- if not $latestObj -}} + {{- printf "please review the entire path of '%s' exists in values" $.key | fail -}} + {{- end -}} + {{- $value = ( index $latestObj . ) -}} + {{- $latestObj = $value -}} +{{- end -}} +{{- printf "%v" (default "" $value) -}} +{{- end -}} + +{{/* +Returns first .Values key with a defined value or first of the list if all non-defined +Usage: +{{ include "common.utils.getKeyFromList" (dict "keys" (list "path.to.key1" "path.to.key2") "context" $) }} +*/}} +{{- define "common.utils.getKeyFromList" -}} +{{- $key := first .keys -}} +{{- $reverseKeys := reverse .keys }} +{{- range $reverseKeys }} + {{- $value := include "common.utils.getValueFromKey" (dict "key" . "context" $.context ) }} + {{- if $value -}} + {{- $key = . }} + {{- end -}} +{{- end -}} +{{- printf "%s" $key -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/_warnings.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/_warnings.tpl new file mode 100644 index 000000000..ae10fa41e --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/_warnings.tpl @@ -0,0 +1,14 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Warning about using rolling tag. +Usage: +{{ include "common.warnings.rollingTag" .Values.path.to.the.imageRoot }} +*/}} +{{- define "common.warnings.rollingTag" -}} + +{{- if and (contains "bitnami/" .repository) (not (.tag | toString | regexFind "-r\\d+$|sha256:")) }} +WARNING: Rolling tag detected ({{ .repository }}:{{ .tag }}), please note that it is strongly recommended to avoid using rolling tags in a production environment. ++info https://docs.bitnami.com/containers/how-to/understand-rolling-tags-containers/ +{{- end }} + +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_cassandra.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_cassandra.tpl new file mode 100644 index 000000000..ded1ae3bc --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_cassandra.tpl @@ -0,0 +1,72 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Validate Cassandra required passwords are not empty. + +Usage: +{{ include "common.validations.values.cassandra.passwords" (dict "secret" "secretName" "subchart" false "context" $) }} +Params: + - secret - String - Required. Name of the secret where Cassandra values are stored, e.g: "cassandra-passwords-secret" + - subchart - Boolean - Optional. Whether Cassandra is used as subchart or not. Default: false +*/}} +{{- define "common.validations.values.cassandra.passwords" -}} + {{- $existingSecret := include "common.cassandra.values.existingSecret" . -}} + {{- $enabled := include "common.cassandra.values.enabled" . -}} + {{- $dbUserPrefix := include "common.cassandra.values.key.dbUser" . -}} + {{- $valueKeyPassword := printf "%s.password" $dbUserPrefix -}} + + {{- if and (or (not $existingSecret) (eq $existingSecret "\"\"")) (eq $enabled "true") -}} + {{- $requiredPasswords := list -}} + + {{- $requiredPassword := dict "valueKey" $valueKeyPassword "secret" .secret "field" "cassandra-password" -}} + {{- $requiredPasswords = append $requiredPasswords $requiredPassword -}} + + {{- include "common.validations.values.multiple.empty" (dict "required" $requiredPasswords "context" .context) -}} + + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for existingSecret. + +Usage: +{{ include "common.cassandra.values.existingSecret" (dict "context" $) }} +Params: + - subchart - Boolean - Optional. Whether Cassandra is used as subchart or not. Default: false +*/}} +{{- define "common.cassandra.values.existingSecret" -}} + {{- if .subchart -}} + {{- .context.Values.cassandra.dbUser.existingSecret | quote -}} + {{- else -}} + {{- .context.Values.dbUser.existingSecret | quote -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for enabled cassandra. + +Usage: +{{ include "common.cassandra.values.enabled" (dict "context" $) }} +*/}} +{{- define "common.cassandra.values.enabled" -}} + {{- if .subchart -}} + {{- printf "%v" .context.Values.cassandra.enabled -}} + {{- else -}} + {{- printf "%v" (not .context.Values.enabled) -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for the key dbUser + +Usage: +{{ include "common.cassandra.values.key.dbUser" (dict "subchart" "true" "context" $) }} +Params: + - subchart - Boolean - Optional. Whether Cassandra is used as subchart or not. Default: false +*/}} +{{- define "common.cassandra.values.key.dbUser" -}} + {{- if .subchart -}} + cassandra.dbUser + {{- else -}} + dbUser + {{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_mariadb.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_mariadb.tpl new file mode 100644 index 000000000..b6906ff77 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_mariadb.tpl @@ -0,0 +1,103 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Validate MariaDB required passwords are not empty. + +Usage: +{{ include "common.validations.values.mariadb.passwords" (dict "secret" "secretName" "subchart" false "context" $) }} +Params: + - secret - String - Required. Name of the secret where MariaDB values are stored, e.g: "mysql-passwords-secret" + - subchart - Boolean - Optional. Whether MariaDB is used as subchart or not. Default: false +*/}} +{{- define "common.validations.values.mariadb.passwords" -}} + {{- $existingSecret := include "common.mariadb.values.auth.existingSecret" . -}} + {{- $enabled := include "common.mariadb.values.enabled" . -}} + {{- $architecture := include "common.mariadb.values.architecture" . -}} + {{- $authPrefix := include "common.mariadb.values.key.auth" . -}} + {{- $valueKeyRootPassword := printf "%s.rootPassword" $authPrefix -}} + {{- $valueKeyUsername := printf "%s.username" $authPrefix -}} + {{- $valueKeyPassword := printf "%s.password" $authPrefix -}} + {{- $valueKeyReplicationPassword := printf "%s.replicationPassword" $authPrefix -}} + + {{- if and (or (not $existingSecret) (eq $existingSecret "\"\"")) (eq $enabled "true") -}} + {{- $requiredPasswords := list -}} + + {{- $requiredRootPassword := dict "valueKey" $valueKeyRootPassword "secret" .secret "field" "mariadb-root-password" -}} + {{- $requiredPasswords = append $requiredPasswords $requiredRootPassword -}} + + {{- $valueUsername := include "common.utils.getValueFromKey" (dict "key" $valueKeyUsername "context" .context) }} + {{- if not (empty $valueUsername) -}} + {{- $requiredPassword := dict "valueKey" $valueKeyPassword "secret" .secret "field" "mariadb-password" -}} + {{- $requiredPasswords = append $requiredPasswords $requiredPassword -}} + {{- end -}} + + {{- if (eq $architecture "replication") -}} + {{- $requiredReplicationPassword := dict "valueKey" $valueKeyReplicationPassword "secret" .secret "field" "mariadb-replication-password" -}} + {{- $requiredPasswords = append $requiredPasswords $requiredReplicationPassword -}} + {{- end -}} + + {{- include "common.validations.values.multiple.empty" (dict "required" $requiredPasswords "context" .context) -}} + + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for existingSecret. + +Usage: +{{ include "common.mariadb.values.auth.existingSecret" (dict "context" $) }} +Params: + - subchart - Boolean - Optional. Whether MariaDB is used as subchart or not. Default: false +*/}} +{{- define "common.mariadb.values.auth.existingSecret" -}} + {{- if .subchart -}} + {{- .context.Values.mariadb.auth.existingSecret | quote -}} + {{- else -}} + {{- .context.Values.auth.existingSecret | quote -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for enabled mariadb. + +Usage: +{{ include "common.mariadb.values.enabled" (dict "context" $) }} +*/}} +{{- define "common.mariadb.values.enabled" -}} + {{- if .subchart -}} + {{- printf "%v" .context.Values.mariadb.enabled -}} + {{- else -}} + {{- printf "%v" (not .context.Values.enabled) -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for architecture + +Usage: +{{ include "common.mariadb.values.architecture" (dict "subchart" "true" "context" $) }} +Params: + - subchart - Boolean - Optional. Whether MariaDB is used as subchart or not. Default: false +*/}} +{{- define "common.mariadb.values.architecture" -}} + {{- if .subchart -}} + {{- .context.Values.mariadb.architecture -}} + {{- else -}} + {{- .context.Values.architecture -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for the key auth + +Usage: +{{ include "common.mariadb.values.key.auth" (dict "subchart" "true" "context" $) }} +Params: + - subchart - Boolean - Optional. Whether MariaDB is used as subchart or not. Default: false +*/}} +{{- define "common.mariadb.values.key.auth" -}} + {{- if .subchart -}} + mariadb.auth + {{- else -}} + auth + {{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_mongodb.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_mongodb.tpl new file mode 100644 index 000000000..a071ea4d3 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_mongodb.tpl @@ -0,0 +1,108 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Validate MongoDB® required passwords are not empty. + +Usage: +{{ include "common.validations.values.mongodb.passwords" (dict "secret" "secretName" "subchart" false "context" $) }} +Params: + - secret - String - Required. Name of the secret where MongoDB® values are stored, e.g: "mongodb-passwords-secret" + - subchart - Boolean - Optional. Whether MongoDB® is used as subchart or not. Default: false +*/}} +{{- define "common.validations.values.mongodb.passwords" -}} + {{- $existingSecret := include "common.mongodb.values.auth.existingSecret" . -}} + {{- $enabled := include "common.mongodb.values.enabled" . -}} + {{- $authPrefix := include "common.mongodb.values.key.auth" . -}} + {{- $architecture := include "common.mongodb.values.architecture" . -}} + {{- $valueKeyRootPassword := printf "%s.rootPassword" $authPrefix -}} + {{- $valueKeyUsername := printf "%s.username" $authPrefix -}} + {{- $valueKeyDatabase := printf "%s.database" $authPrefix -}} + {{- $valueKeyPassword := printf "%s.password" $authPrefix -}} + {{- $valueKeyReplicaSetKey := printf "%s.replicaSetKey" $authPrefix -}} + {{- $valueKeyAuthEnabled := printf "%s.enabled" $authPrefix -}} + + {{- $authEnabled := include "common.utils.getValueFromKey" (dict "key" $valueKeyAuthEnabled "context" .context) -}} + + {{- if and (or (not $existingSecret) (eq $existingSecret "\"\"")) (eq $enabled "true") (eq $authEnabled "true") -}} + {{- $requiredPasswords := list -}} + + {{- $requiredRootPassword := dict "valueKey" $valueKeyRootPassword "secret" .secret "field" "mongodb-root-password" -}} + {{- $requiredPasswords = append $requiredPasswords $requiredRootPassword -}} + + {{- $valueUsername := include "common.utils.getValueFromKey" (dict "key" $valueKeyUsername "context" .context) }} + {{- $valueDatabase := include "common.utils.getValueFromKey" (dict "key" $valueKeyDatabase "context" .context) }} + {{- if and $valueUsername $valueDatabase -}} + {{- $requiredPassword := dict "valueKey" $valueKeyPassword "secret" .secret "field" "mongodb-password" -}} + {{- $requiredPasswords = append $requiredPasswords $requiredPassword -}} + {{- end -}} + + {{- if (eq $architecture "replicaset") -}} + {{- $requiredReplicaSetKey := dict "valueKey" $valueKeyReplicaSetKey "secret" .secret "field" "mongodb-replica-set-key" -}} + {{- $requiredPasswords = append $requiredPasswords $requiredReplicaSetKey -}} + {{- end -}} + + {{- include "common.validations.values.multiple.empty" (dict "required" $requiredPasswords "context" .context) -}} + + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for existingSecret. + +Usage: +{{ include "common.mongodb.values.auth.existingSecret" (dict "context" $) }} +Params: + - subchart - Boolean - Optional. Whether MongoDb is used as subchart or not. Default: false +*/}} +{{- define "common.mongodb.values.auth.existingSecret" -}} + {{- if .subchart -}} + {{- .context.Values.mongodb.auth.existingSecret | quote -}} + {{- else -}} + {{- .context.Values.auth.existingSecret | quote -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for enabled mongodb. + +Usage: +{{ include "common.mongodb.values.enabled" (dict "context" $) }} +*/}} +{{- define "common.mongodb.values.enabled" -}} + {{- if .subchart -}} + {{- printf "%v" .context.Values.mongodb.enabled -}} + {{- else -}} + {{- printf "%v" (not .context.Values.enabled) -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for the key auth + +Usage: +{{ include "common.mongodb.values.key.auth" (dict "subchart" "true" "context" $) }} +Params: + - subchart - Boolean - Optional. Whether MongoDB® is used as subchart or not. Default: false +*/}} +{{- define "common.mongodb.values.key.auth" -}} + {{- if .subchart -}} + mongodb.auth + {{- else -}} + auth + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for architecture + +Usage: +{{ include "common.mongodb.values.architecture" (dict "subchart" "true" "context" $) }} +Params: + - subchart - Boolean - Optional. Whether MariaDB is used as subchart or not. Default: false +*/}} +{{- define "common.mongodb.values.architecture" -}} + {{- if .subchart -}} + {{- .context.Values.mongodb.architecture -}} + {{- else -}} + {{- .context.Values.architecture -}} + {{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_postgresql.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_postgresql.tpl new file mode 100644 index 000000000..164ec0d01 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_postgresql.tpl @@ -0,0 +1,129 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Validate PostgreSQL required passwords are not empty. + +Usage: +{{ include "common.validations.values.postgresql.passwords" (dict "secret" "secretName" "subchart" false "context" $) }} +Params: + - secret - String - Required. Name of the secret where postgresql values are stored, e.g: "postgresql-passwords-secret" + - subchart - Boolean - Optional. Whether postgresql is used as subchart or not. Default: false +*/}} +{{- define "common.validations.values.postgresql.passwords" -}} + {{- $existingSecret := include "common.postgresql.values.existingSecret" . -}} + {{- $enabled := include "common.postgresql.values.enabled" . -}} + {{- $valueKeyPostgresqlPassword := include "common.postgresql.values.key.postgressPassword" . -}} + {{- $valueKeyPostgresqlReplicationEnabled := include "common.postgresql.values.key.replicationPassword" . -}} + {{- if and (or (not $existingSecret) (eq $existingSecret "\"\"")) (eq $enabled "true") -}} + {{- $requiredPasswords := list -}} + {{- $requiredPostgresqlPassword := dict "valueKey" $valueKeyPostgresqlPassword "secret" .secret "field" "postgresql-password" -}} + {{- $requiredPasswords = append $requiredPasswords $requiredPostgresqlPassword -}} + + {{- $enabledReplication := include "common.postgresql.values.enabled.replication" . -}} + {{- if (eq $enabledReplication "true") -}} + {{- $requiredPostgresqlReplicationPassword := dict "valueKey" $valueKeyPostgresqlReplicationEnabled "secret" .secret "field" "postgresql-replication-password" -}} + {{- $requiredPasswords = append $requiredPasswords $requiredPostgresqlReplicationPassword -}} + {{- end -}} + + {{- include "common.validations.values.multiple.empty" (dict "required" $requiredPasswords "context" .context) -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to decide whether evaluate global values. + +Usage: +{{ include "common.postgresql.values.use.global" (dict "key" "key-of-global" "context" $) }} +Params: + - key - String - Required. Field to be evaluated within global, e.g: "existingSecret" +*/}} +{{- define "common.postgresql.values.use.global" -}} + {{- if .context.Values.global -}} + {{- if .context.Values.global.postgresql -}} + {{- index .context.Values.global.postgresql .key | quote -}} + {{- end -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for existingSecret. + +Usage: +{{ include "common.postgresql.values.existingSecret" (dict "context" $) }} +*/}} +{{- define "common.postgresql.values.existingSecret" -}} + {{- $globalValue := include "common.postgresql.values.use.global" (dict "key" "existingSecret" "context" .context) -}} + + {{- if .subchart -}} + {{- default (.context.Values.postgresql.existingSecret | quote) $globalValue -}} + {{- else -}} + {{- default (.context.Values.existingSecret | quote) $globalValue -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for enabled postgresql. + +Usage: +{{ include "common.postgresql.values.enabled" (dict "context" $) }} +*/}} +{{- define "common.postgresql.values.enabled" -}} + {{- if .subchart -}} + {{- printf "%v" .context.Values.postgresql.enabled -}} + {{- else -}} + {{- printf "%v" (not .context.Values.enabled) -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for the key postgressPassword. + +Usage: +{{ include "common.postgresql.values.key.postgressPassword" (dict "subchart" "true" "context" $) }} +Params: + - subchart - Boolean - Optional. Whether postgresql is used as subchart or not. Default: false +*/}} +{{- define "common.postgresql.values.key.postgressPassword" -}} + {{- $globalValue := include "common.postgresql.values.use.global" (dict "key" "postgresqlUsername" "context" .context) -}} + + {{- if not $globalValue -}} + {{- if .subchart -}} + postgresql.postgresqlPassword + {{- else -}} + postgresqlPassword + {{- end -}} + {{- else -}} + global.postgresql.postgresqlPassword + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for enabled.replication. + +Usage: +{{ include "common.postgresql.values.enabled.replication" (dict "subchart" "true" "context" $) }} +Params: + - subchart - Boolean - Optional. Whether postgresql is used as subchart or not. Default: false +*/}} +{{- define "common.postgresql.values.enabled.replication" -}} + {{- if .subchart -}} + {{- printf "%v" .context.Values.postgresql.replication.enabled -}} + {{- else -}} + {{- printf "%v" .context.Values.replication.enabled -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for the key replication.password. + +Usage: +{{ include "common.postgresql.values.key.replicationPassword" (dict "subchart" "true" "context" $) }} +Params: + - subchart - Boolean - Optional. Whether postgresql is used as subchart or not. Default: false +*/}} +{{- define "common.postgresql.values.key.replicationPassword" -}} + {{- if .subchart -}} + postgresql.replication.password + {{- else -}} + replication.password + {{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_redis.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_redis.tpl new file mode 100644 index 000000000..5d72959b9 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_redis.tpl @@ -0,0 +1,76 @@ + +{{/* vim: set filetype=mustache: */}} +{{/* +Validate Redis™ required passwords are not empty. + +Usage: +{{ include "common.validations.values.redis.passwords" (dict "secret" "secretName" "subchart" false "context" $) }} +Params: + - secret - String - Required. Name of the secret where redis values are stored, e.g: "redis-passwords-secret" + - subchart - Boolean - Optional. Whether redis is used as subchart or not. Default: false +*/}} +{{- define "common.validations.values.redis.passwords" -}} + {{- $enabled := include "common.redis.values.enabled" . -}} + {{- $valueKeyPrefix := include "common.redis.values.keys.prefix" . -}} + {{- $standarizedVersion := include "common.redis.values.standarized.version" . }} + + {{- $existingSecret := ternary (printf "%s%s" $valueKeyPrefix "auth.existingSecret") (printf "%s%s" $valueKeyPrefix "existingSecret") (eq $standarizedVersion "true") }} + {{- $existingSecretValue := include "common.utils.getValueFromKey" (dict "key" $existingSecret "context" .context) }} + + {{- $valueKeyRedisPassword := ternary (printf "%s%s" $valueKeyPrefix "auth.password") (printf "%s%s" $valueKeyPrefix "password") (eq $standarizedVersion "true") }} + {{- $valueKeyRedisUseAuth := ternary (printf "%s%s" $valueKeyPrefix "auth.enabled") (printf "%s%s" $valueKeyPrefix "usePassword") (eq $standarizedVersion "true") }} + + {{- if and (or (not $existingSecret) (eq $existingSecret "\"\"")) (eq $enabled "true") -}} + {{- $requiredPasswords := list -}} + + {{- $useAuth := include "common.utils.getValueFromKey" (dict "key" $valueKeyRedisUseAuth "context" .context) -}} + {{- if eq $useAuth "true" -}} + {{- $requiredRedisPassword := dict "valueKey" $valueKeyRedisPassword "secret" .secret "field" "redis-password" -}} + {{- $requiredPasswords = append $requiredPasswords $requiredRedisPassword -}} + {{- end -}} + + {{- include "common.validations.values.multiple.empty" (dict "required" $requiredPasswords "context" .context) -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right value for enabled redis. + +Usage: +{{ include "common.redis.values.enabled" (dict "context" $) }} +*/}} +{{- define "common.redis.values.enabled" -}} + {{- if .subchart -}} + {{- printf "%v" .context.Values.redis.enabled -}} + {{- else -}} + {{- printf "%v" (not .context.Values.enabled) -}} + {{- end -}} +{{- end -}} + +{{/* +Auxiliary function to get the right prefix path for the values + +Usage: +{{ include "common.redis.values.key.prefix" (dict "subchart" "true" "context" $) }} +Params: + - subchart - Boolean - Optional. Whether redis is used as subchart or not. Default: false +*/}} +{{- define "common.redis.values.keys.prefix" -}} + {{- if .subchart -}}redis.{{- else -}}{{- end -}} +{{- end -}} + +{{/* +Checks whether the redis chart's includes the standarizations (version >= 14) + +Usage: +{{ include "common.redis.values.standarized.version" (dict "context" $) }} +*/}} +{{- define "common.redis.values.standarized.version" -}} + + {{- $standarizedAuth := printf "%s%s" (include "common.redis.values.keys.prefix" .) "auth" -}} + {{- $standarizedAuthValues := include "common.utils.getValueFromKey" (dict "key" $standarizedAuth "context" .context) }} + + {{- if $standarizedAuthValues -}} + {{- true -}} + {{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_validations.tpl b/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_validations.tpl new file mode 100644 index 000000000..9a814cf40 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/templates/validations/_validations.tpl @@ -0,0 +1,46 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Validate values must not be empty. + +Usage: +{{- $validateValueConf00 := (dict "valueKey" "path.to.value" "secret" "secretName" "field" "password-00") -}} +{{- $validateValueConf01 := (dict "valueKey" "path.to.value" "secret" "secretName" "field" "password-01") -}} +{{ include "common.validations.values.empty" (dict "required" (list $validateValueConf00 $validateValueConf01) "context" $) }} + +Validate value params: + - valueKey - String - Required. The path to the validating value in the values.yaml, e.g: "mysql.password" + - secret - String - Optional. Name of the secret where the validating value is generated/stored, e.g: "mysql-passwords-secret" + - field - String - Optional. Name of the field in the secret data, e.g: "mysql-password" +*/}} +{{- define "common.validations.values.multiple.empty" -}} + {{- range .required -}} + {{- include "common.validations.values.single.empty" (dict "valueKey" .valueKey "secret" .secret "field" .field "context" $.context) -}} + {{- end -}} +{{- end -}} + +{{/* +Validate a value must not be empty. + +Usage: +{{ include "common.validations.value.empty" (dict "valueKey" "mariadb.password" "secret" "secretName" "field" "my-password" "subchart" "subchart" "context" $) }} + +Validate value params: + - valueKey - String - Required. The path to the validating value in the values.yaml, e.g: "mysql.password" + - secret - String - Optional. Name of the secret where the validating value is generated/stored, e.g: "mysql-passwords-secret" + - field - String - Optional. Name of the field in the secret data, e.g: "mysql-password" + - subchart - String - Optional - Name of the subchart that the validated password is part of. +*/}} +{{- define "common.validations.values.single.empty" -}} + {{- $value := include "common.utils.getValueFromKey" (dict "key" .valueKey "context" .context) }} + {{- $subchart := ternary "" (printf "%s." .subchart) (empty .subchart) }} + + {{- if not $value -}} + {{- $varname := "my-value" -}} + {{- $getCurrentValue := "" -}} + {{- if and .secret .field -}} + {{- $varname = include "common.utils.fieldToEnvVar" . -}} + {{- $getCurrentValue = printf " To get the current value:\n\n %s\n" (include "common.utils.secret.getvalue" .) -}} + {{- end -}} + {{- printf "\n '%s' must not be empty, please add '--set %s%s=$%s' to the command.%s" .valueKey $subchart .valueKey $varname $getCurrentValue -}} + {{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/charts/common/values.yaml b/packages/shipa/charts/charts/mongodb/charts/common/values.yaml new file mode 100644 index 000000000..f2df68e5e --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/charts/common/values.yaml @@ -0,0 +1,5 @@ +## bitnami/common +## It is required by CI/CD tools and processes. +## @skip exampleValue +## +exampleValue: common-chart diff --git a/packages/shipa/charts/charts/mongodb/ci/values-replicaset-with-rbac.yaml b/packages/shipa/charts/charts/mongodb/ci/values-replicaset-with-rbac.yaml new file mode 100644 index 000000000..a8b62e27c --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/ci/values-replicaset-with-rbac.yaml @@ -0,0 +1,8 @@ +architecture: replicaset +replicaCount: 3 +pdb: + create: true +rbac: + create: true +serviceAccount: + create: true diff --git a/packages/shipa/charts/charts/mongodb/templates/NOTES.txt b/packages/shipa/charts/charts/mongodb/templates/NOTES.txt new file mode 100644 index 000000000..d3b3b91bc --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/NOTES.txt @@ -0,0 +1,204 @@ +CHART NAME: {{ .Chart.Name }} +CHART VERSION: {{ .Chart.Version }} +APP VERSION: {{ .Chart.AppVersion }} + +{{- if .Values.diagnosticMode.enabled }} +The chart has been deployed in diagnostic mode. All probes have been disabled and the command has been overwritten with: + + command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 4 }} + args: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.args "context" $) | nindent 4 }} + +Get the list of pods by executing: + + kubectl get pods --namespace {{ .Release.Namespace }} -l app.kubernetes.io/instance={{ .Release.Name }} + +Access the pod you want to debug by executing + + kubectl exec --namespace {{ .Release.Namespace }} -ti -- bash + +In order to replicate the container startup scripts execute this command: + + /opt/bitnami/scripts/mongodb/entrypoint.sh /opt/bitnami/scripts/mongodb/run.sh + +{{- else }} + +{{- $replicaCount := int .Values.replicaCount }} +{{- $portNumber := int .Values.service.port }} +{{- $fullname := include "mongodb.fullname" . }} +{{- $releaseNamespace := include "mongodb.namespace" . }} +{{- $clusterDomain := .Values.clusterDomain }} +{{- $loadBalancerIPListLength := len .Values.externalAccess.service.loadBalancerIPs }} +{{- $mongoList := list }} +{{- range $e, $i := until $replicaCount }} +{{- $mongoList = append $mongoList (printf "%s-%d.%s-headless.%s.svc.%s:%d" $fullname $i $fullname $releaseNamespace $clusterDomain $portNumber) }} +{{- end }} + +{{- if and (eq .Values.architecture "replicaset") .Values.externalAccess.enabled (not .Values.externalAccess.autoDiscovery.enabled) (not (eq $replicaCount $loadBalancerIPListLength )) (eq .Values.externalAccess.service.type "LoadBalancer") }} + +#################################################################################### +### ERROR: You enabled external access to MongoDB® nodes without specifying ### +### the array of load balancer IPs for MongoDB® nodes. ### +#################################################################################### + +This deployment will be incomplete until you configure the array of load balancer +IPs for MongoDB® nodes. To complete your deployment follow the steps below: + +1. Wait for the load balancer IPs (it may take a few minutes for them to be available): + + kubectl get svc --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ template "mongodb.name" . }},app.kubernetes.io/instance={{ .Release.Name }},app.kubernetes.io/component=mongodb" -w + +2. Obtain the load balancer IPs and upgrade your chart: + + {{- range $e, $i := until $replicaCount }} + LOAD_BALANCER_IP_{{ add $i 1 }}="$(kubectl get svc --namespace {{ $releaseNamespace }} {{ $fullname }}-{{ $i }}-external -o jsonpath='{.status.loadBalancer.ingress[0].ip}')" + {{- end }} + +3. Upgrade you chart: + + helm upgrade --namespace {{ .Release.Namespace }} {{ .Release.Name }} bitnami/{{ .Chart.Name }} \ + --set mongodb.replicaCount={{ $replicaCount }} \ + --set mongodb.externalAccess.enabled=true \ + {{- range $i, $e := until $replicaCount }} + --set mongodb.externalAccess.service.loadBalancerIPs[{{ $i }}]=$LOAD_BALANCER_IP_{{ add $i 1 }} \ + {{- end }} + --set mongodb.externalAccess.service.type=LoadBalancer + +{{- else }} + +{{- if and (or (and (eq .Values.architecture "standalone") (or (eq .Values.service.type "LoadBalancer") (eq .Values.service.type "NodePort"))) (and (eq .Values.architecture "replicaset") .Values.externalAccess.enabled)) (not .Values.auth.enabled) }} +------------------------------------------------------------------------------- + WARNING + + By not enabling "mongodb.auth.enabled" you have most likely exposed the + MongoDB® service externally without any authentication mechanism. + + For security reasons, we strongly suggest that you enable authentiation + setting the "mongodb.auth.enabled" parameter to "true". + +------------------------------------------------------------------------------- +{{- end }} + +** Please be patient while the chart is being deployed ** + +MongoDB® can be accessed on the following DNS name(s) and ports from within your cluster: + +{{- if eq .Values.architecture "replicaset" }} +{{ join "\n" $mongoList | nindent 4 }} +{{- else }} + + {{ $fullname }}.{{ $releaseNamespace }}.svc.{{ .Values.clusterDomain }} + +{{- end }} + +{{- if .Values.auth.enabled }} + +To get the root password run: + + export MONGODB_ROOT_PASSWORD=$(kubectl get secret --namespace {{ template "mongodb.namespace" . }} {{ template "mongodb.secretName" . }} -o jsonpath="{.data.mongodb-root-password}" | base64 --decode) + +{{- end }} +{{- $customUsers := include "mongodb.customUsers" . -}} +{{- $customDatabases := include "mongodb.customDatabases" . -}} +{{- if and (not (empty $customUsers)) (not (empty $customDatabases)) }} +{{- $customUsersList := splitList "," $customUsers }} +{{- range $index, $user := $customUsersList }} + +To get the password for "{{ $user }}" run: + + export MONGODB_PASSWORD=$(kubectl get secret --namespace {{ include "mongodb.namespace" $ }} {{ include "mongodb.secretName" $ }} -o jsonpath="{.data.mongodb-passwords}" | base64 --decode | awk -F',' '{print ${{ add 1 $index }}}') + +{{- end }} +{{- end }} + +To connect to your database, create a MongoDB® client container: + + kubectl run --namespace {{ template "mongodb.namespace" . }} {{ template "mongodb.fullname" . }}-client --rm --tty -i --restart='Never' --env="MONGODB_ROOT_PASSWORD=$MONGODB_ROOT_PASSWORD" --image {{ template "mongodb.image" . }} --command -- bash + +Then, run the following command: + + {{- if eq .Values.architecture "replicaset" }} + mongo admin --host "{{ join "," $mongoList }}" {{- if .Values.auth.enabled }} --authenticationDatabase admin -u root -p $MONGODB_ROOT_PASSWORD{{- end }} + {{- else }} + mongo admin --host "{{ template "mongodb.fullname" . }}" {{- if .Values.auth.enabled }} --authenticationDatabase admin -u root -p $MONGODB_ROOT_PASSWORD{{- end }} + {{- end }} + +{{- if and (eq .Values.architecture "replicaset") .Values.externalAccess.enabled }} + +To connect to your database nodes from outside, you need to add both primary and secondary nodes hostnames/IPs to your Mongo client. To obtain them, follow the instructions below: + +{{- if eq "NodePort" .Values.externalAccess.service.type }} +{{- if .Values.externalAccess.service.domain }} + + MongoDB® nodes domain: Use your provided hostname to reach MongoDB® nodes, {{ .Values.externalAccess.service.domain }} + +{{- else }} + + MongoDB® nodes domain: you can reach MongoDB® nodes on any of the K8s nodes external IPs. + + kubectl get nodes -o wide + +{{- end }} + + MongoDB® nodes port: You will have a different node port for each MongoDB® node. You can get the list of configured node ports using the command below: + + echo "$(kubectl get svc --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ template "mongodb.name" . }},app.kubernetes.io/instance={{ .Release.Name }},app.kubernetes.io/component=mongodb,pod" -o jsonpath='{.items[*].spec.ports[0].nodePort}' | tr ' ' '\n')" + +{{- else if contains "LoadBalancer" .Values.externalAccess.service.type }} + + NOTE: It may take a few minutes for the LoadBalancer IPs to be available. + Watch the status with: 'kubectl get svc --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ template "mongodb.name" . }},app.kubernetes.io/instance={{ .Release.Name }},app.kubernetes.io/component=mongodb,pod" -w' + + MongoDB® nodes domain: You will have a different external IP for each MongoDB® node. You can get the list of external IPs using the command below: + + echo "$(kubectl get svc --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ template "mongodb.name" . }},app.kubernetes.io/instance={{ .Release.Name }},app.kubernetes.io/component=mongodb,pod" -o jsonpath='{.items[*].status.loadBalancer.ingress[0].ip}' | tr ' ' '\n')" + + MongoDB® nodes port: {{ .Values.externalAccess.service.port }} + +{{- end }} + +{{- else if eq .Values.architecture "standalone" }} + +To connect to your database from outside the cluster execute the following commands: + +{{- if contains "NodePort" .Values.service.type }} + + export NODE_IP=$(kubectl get nodes --namespace {{ template "mongodb.namespace" . }} -o jsonpath="{.items[0].status.addresses[0].address}") + export NODE_PORT=$(kubectl get --namespace {{ template "mongodb.namespace" . }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ template "mongodb.fullname" . }}) + mongo --host $NODE_IP --port $NODE_PORT {{- if .Values.auth.enabled }} --authenticationDatabase admin -p $MONGODB_ROOT_PASSWORD{{- end }} + +{{- else if contains "LoadBalancer" .Values.service.type }} + + NOTE: It may take a few minutes for the LoadBalancer IP to be available. + Watch the status with: 'kubectl get svc --namespace {{ template "mongodb.namespace" . }} -w {{ template "mongodb.fullname" . }}' + + export SERVICE_IP=$(kubectl get svc --namespace {{ template "mongodb.namespace" . }} {{ template "mongodb.fullname" . }} --template "{{ "{{ range (index .status.loadBalancer.ingress 0) }}{{ . }}{{ end }}" }}") + mongo --host $SERVICE_IP --port {{ $portNumber }} {{- if .Values.auth.enabled }} --authenticationDatabase admin -p $MONGODB_ROOT_PASSWORD{{- end }} + +{{- else if contains "ClusterIP" .Values.service.type }} + + kubectl port-forward --namespace {{ template "mongodb.namespace" . }} svc/{{ template "mongodb.fullname" . }} {{ $portNumber }}:{{ $portNumber }} & + mongo --host 127.0.0.1 {{- if .Values.auth.enabled }} --authenticationDatabase admin -p $MONGODB_ROOT_PASSWORD{{- end }} + +{{- end }} +{{- end }} +{{- end }} + +{{- if .Values.metrics.enabled }} + +To access the MongoDB® Prometheus metrics, get the MongoDB® Prometheus URL by running: + + kubectl port-forward --namespace {{ .Release.Namespace }} svc/{{ include "mongodb.fullname" . }}-metrics {{ .Values.metrics.service.port }}:{{ .Values.metrics.service.port }} & + echo "Prometheus Metrics URL: http://127.0.0.1:{{ .Values.metrics.service.port }}/metrics" + +Then, open the obtained URL in a browser. + +{{- end }} +{{- end }} +{{- include "common.warnings.rollingTag" .Values.image }} +{{- include "common.warnings.rollingTag" .Values.metrics.image }} +{{- include "common.warnings.rollingTag" .Values.externalAccess.autoDiscovery.image }} +{{- include "common.warnings.rollingTag" .Values.volumePermissions.image }} +{{- include "mongodb.validateValues" . }} +{{- $secretName := include "mongodb.fullname" . -}} +{{- $passwordValidationErrors := include "common.validations.values.mongodb.passwords" (dict "secret" $secretName "context" $) -}} +{{- include "common.errors.upgrade.passwords.empty" (dict "validationErrors" (list $passwordValidationErrors) "context" $) -}} diff --git a/packages/shipa/charts/charts/mongodb/templates/_helpers.tpl b/packages/shipa/charts/charts/mongodb/templates/_helpers.tpl new file mode 100644 index 000000000..496d4e8fe --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/_helpers.tpl @@ -0,0 +1,444 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Expand the name of the chart. +*/}} +{{- define "mongodb.name" -}} +{{- include "common.names.name" . -}} +{{- end -}} + +{{/* +Create a default fully qualified app name. +We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). +If release name contains chart name it will be used as a full name. +*/}} +{{- define "mongodb.fullname" -}} +{{- include "common.names.fullname" . -}} +{{- end -}} + +{{/* +Create a default mongo service name which can be overridden. +*/}} +{{- define "mongodb.service.nameOverride" -}} + {{- if .Values.service -}} + {{- if .Values.service.nameOverride }} + {{- .Values.service.nameOverride -}} + {{- else -}} + {{ include "mongodb.fullname" . }}-headless + {{- end -}} + {{- else -}} + {{ include "mongodb.fullname" . }}-headless + {{- end }} +{{- end }} + +{{/* +Create a default mongo arbiter service name which can be overridden. +*/}} +{{- define "mongodb.arbiter.service.nameOverride" -}} + {{- if .Values.arbiter.service -}} + {{- if .Values.arbiter.service.nameOverride }} + {{- .Values.arbiter.service.nameOverride -}} + {{- else -}} + {{ include "mongodb.fullname" . }}-arbiter-headless + {{- end -}} + {{- else -}} + {{ include "mongodb.fullname" . }}-arbiter-headless + {{- end }} +{{- end }} + +{{/* +Return the proper MongoDB® image name +*/}} +{{- define "mongodb.image" -}} +{{ include "common.images.image" (dict "imageRoot" .Values.image "global" .Values.global) }} +{{- end -}} + +{{/* +Return the proper image name (for the metrics image) +*/}} +{{- define "mongodb.metrics.image" -}} +{{ include "common.images.image" (dict "imageRoot" .Values.metrics.image "global" .Values.global) }} +{{- end -}} + +{{/* +Return the proper image name (for the init container volume-permissions image) +*/}} +{{- define "mongodb.volumePermissions.image" -}} +{{ include "common.images.image" (dict "imageRoot" .Values.volumePermissions.image "global" .Values.global) }} +{{- end -}} + +{{/* +Return the proper image name (for the init container auto-discovery image) +*/}} +{{- define "mongodb.externalAccess.autoDiscovery.image" -}} +{{ include "common.images.image" (dict "imageRoot" .Values.externalAccess.autoDiscovery.image "global" .Values.global) }} +{{- end -}} + +{{/* +Return the proper image name (for the TLS Certs image) +*/}} +{{- define "mongodb.tls.image" -}} +{{ include "common.images.image" (dict "imageRoot" .Values.tls.image "global" .Values.global) }} +{{- end -}} + +{{/* +Return the proper Docker Image Registry Secret Names +*/}} +{{- define "mongodb.imagePullSecrets" -}} +{{ include "common.images.pullSecrets" (dict "images" (list .Values.image .Values.metrics.image .Values.volumePermissions.image) "global" .Values.global) }} +{{- end -}} + +{{/* +Allow the release namespace to be overridden for multi-namespace deployments in combined charts. +*/}} +{{- define "mongodb.namespace" -}} + {{- if .Values.global -}} + {{- if .Values.global.namespaceOverride }} + {{- .Values.global.namespaceOverride -}} + {{- else -}} + {{- .Release.Namespace -}} + {{- end -}} + {{- else -}} + {{- .Release.Namespace -}} + {{- end }} +{{- end -}} +{{- define "mongodb.serviceMonitor.namespace" -}} + {{- if .Values.metrics.serviceMonitor.namespace -}} + {{- .Values.metrics.serviceMonitor.namespace -}} + {{- else -}} + {{- include "mongodb.namespace" . -}} + {{- end }} +{{- end -}} +{{- define "mongodb.prometheusRule.namespace" -}} + {{- if .Values.metrics.prometheusRule.namespace -}} + {{- .Values.metrics.prometheusRule.namespace -}} + {{- else -}} + {{- include "mongodb.namespace" . -}} + {{- end }} +{{- end -}} + +{{/* +Returns the proper service account name depending if an explicit service account name is set +in the values file. If the name is not set it will default to either mongodb.fullname if serviceAccount.create +is true or default otherwise. +*/}} +{{- define "mongodb.serviceAccountName" -}} + {{- if .Values.serviceAccount.create -}} + {{ default (include "mongodb.fullname" .) .Values.serviceAccount.name }} + {{- else -}} + {{ default "default" .Values.serviceAccount.name }} + {{- end -}} +{{- end -}} + +{{/* +Return the list of custom users to create during the initialization (string format) +*/}} +{{- define "mongodb.customUsers" -}} + {{- $customUsers := list -}} + {{- if .Values.auth.username -}} + {{- $customUsers = append $customUsers .Values.auth.username }} + {{- end }} + {{- range .Values.auth.usernames }} + {{- $customUsers = append $customUsers . }} + {{- end }} + {{- printf "%s" (default "" (join "," $customUsers)) -}} +{{- end -}} + +{{/* +Return the list of passwords for the custom users (string format) +*/}} +{{- define "mongodb.customPasswords" -}} + {{- $customPasswords := list -}} + {{- if .Values.auth.password -}} + {{- $customPasswords = append $customPasswords .Values.auth.password }} + {{- end }} + {{- range .Values.auth.passwords }} + {{- $customPasswords = append $customPasswords . }} + {{- end }} + {{- printf "%s" (default "" (join "," $customPasswords)) -}} +{{- end -}} + +{{/* +Return the list of custom databases to create during the initialization (string format) +*/}} +{{- define "mongodb.customDatabases" -}} + {{- $customDatabases := list -}} + {{- if .Values.auth.database -}} + {{- $customDatabases = append $customDatabases .Values.auth.database }} + {{- end }} + {{- range .Values.auth.databases }} + {{- $customDatabases = append $customDatabases . }} + {{- end }} + {{- printf "%s" (default "" (join "," $customDatabases)) -}} +{{- end -}} + +{{/* +Return the configmap with the MongoDB® configuration +*/}} +{{- define "mongodb.configmapName" -}} +{{- if .Values.existingConfigmap -}} + {{- printf "%s" (tpl .Values.existingConfigmap $) -}} +{{- else -}} + {{- printf "%s" (include "mongodb.fullname" .) -}} +{{- end -}} +{{- end -}} + +{{/* +Return true if a configmap object should be created for MongoDB® +*/}} +{{- define "mongodb.createConfigmap" -}} +{{- if and .Values.configuration (not .Values.existingConfigmap) }} + {{- true -}} +{{- else -}} +{{- end -}} +{{- end -}} + +{{/* +Return the secret with MongoDB® credentials +*/}} +{{- define "mongodb.secretName" -}} + {{- if .Values.auth.existingSecret -}} + {{- printf "%s" (tpl .Values.auth.existingSecret $) -}} + {{- else -}} + {{- printf "%s" (include "mongodb.fullname" .) -}} + {{- end -}} +{{- end -}} + +{{/* +Return true if a secret object should be created for MongoDB® +*/}} +{{- define "mongodb.createSecret" -}} +{{- if and .Values.auth.enabled (not .Values.auth.existingSecret) }} + {{- true -}} +{{- else -}} +{{- end -}} +{{- end -}} + +{{/* +Get the initialization scripts ConfigMap name. +*/}} +{{- define "mongodb.initdbScriptsCM" -}} +{{- if .Values.initdbScriptsConfigMap -}} +{{- printf "%s" .Values.initdbScriptsConfigMap -}} +{{- else -}} +{{- printf "%s-init-scripts" (include "mongodb.fullname" .) -}} +{{- end -}} +{{- end -}} + +{{/* +Return true if the Arbiter should be deployed +*/}} +{{- define "mongodb.arbiter.enabled" -}} +{{- if and (eq .Values.architecture "replicaset") .Values.arbiter.enabled }} + {{- true -}} +{{- else -}} +{{- end -}} +{{- end -}} + +{{/* +Return the configmap with the MongoDB® configuration for the Arbiter +*/}} +{{- define "mongodb.arbiter.configmapName" -}} +{{- if .Values.arbiter.existingConfigmap -}} + {{- printf "%s" (tpl .Values.arbiter.existingConfigmap $) -}} +{{- else -}} + {{- printf "%s-arbiter" (include "mongodb.fullname" .) -}} +{{- end -}} +{{- end -}} + +{{/* +Return true if a configmap object should be created for MongoDB® Arbiter +*/}} +{{- define "mongodb.arbiter.createConfigmap" -}} +{{- if and (eq .Values.architecture "replicaset") .Values.arbiter.enabled .Values.arbiter.configuration (not .Values.arbiter.existingConfigmap) }} + {{- true -}} +{{- else -}} +{{- end -}} +{{- end -}} + +{{/* +Return true if the Hidden should be deployed +*/}} +{{- define "mongodb.hidden.enabled" -}} +{{- if and (eq .Values.architecture "replicaset") .Values.hidden.enabled }} + {{- true -}} +{{- end -}} +{{- end -}} + +{{/* +Return the configmap with the MongoDB® configuration for the Hidden +*/}} +{{- define "mongodb.hidden.configmapName" -}} +{{- if .Values.hidden.existingConfigmap -}} + {{- printf "%s" (tpl .Values.hidden.existingConfigmap $) -}} +{{- else -}} + {{- printf "%s-hidden" (include "mongodb.fullname" .) -}} +{{- end -}} +{{- end -}} + +{{/* +Return true if a configmap object should be created for MongoDB® Hidden +*/}} +{{- define "mongodb.hidden.createConfigmap" -}} +{{- if and (include "mongodb.hidden.enabled" .) .Values.hidden.enabled .Values.hidden.configuration (not .Values.hidden.existingConfigmap) }} + {{- true -}} +{{- end -}} +{{- end -}} + +{{/* +Compile all warnings into a single message, and call fail. +*/}} +{{- define "mongodb.validateValues" -}} +{{- $messages := list -}} +{{- $messages := append $messages (include "mongodb.validateValues.pspAndRBAC" .) -}} +{{- $messages := append $messages (include "mongodb.validateValues.architecture" .) -}} +{{- $messages := append $messages (include "mongodb.validateValues.customUsersDBs" .) -}} +{{- $messages := append $messages (include "mongodb.validateValues.customUsersDBsLength" .) -}} +{{- $messages := append $messages (include "mongodb.validateValues.externalAccessServiceType" .) -}} +{{- $messages := append $messages (include "mongodb.validateValues.loadBalancerIPsListLength" .) -}} +{{- $messages := append $messages (include "mongodb.validateValues.nodePortListLength" .) -}} +{{- $messages := append $messages (include "mongodb.validateValues.externalAccessAutoDiscoveryRBAC" .) -}} +{{- $messages := without $messages "" -}} +{{- $message := join "\n" $messages -}} + +{{- if $message -}} +{{- printf "\nVALUES VALIDATION:\n%s" $message | fail -}} +{{- end -}} +{{- end -}} + +{{/* Validate RBAC is created when using PSP */}} +{{- define "mongodb.validateValues.pspAndRBAC" -}} +{{- if and (.Values.podSecurityPolicy.create) (not .Values.rbac.create) -}} +mongodb: podSecurityPolicy.create, rbac.create + Both podSecurityPolicy.create and rbac.create must be true, if you want + to create podSecurityPolicy +{{- end -}} +{{- end -}} + +{{/* Validate values of MongoDB® - must provide a valid architecture */}} +{{- define "mongodb.validateValues.architecture" -}} +{{- if and (ne .Values.architecture "standalone") (ne .Values.architecture "replicaset") -}} +mongodb: architecture + Invalid architecture selected. Valid values are "standalone" and + "replicaset". Please set a valid architecture (--set mongodb.architecture="xxxx") +{{- end -}} +{{- end -}} + +{{/* +Validate values of MongoDB® - both auth.usernames and auth.databases are necessary +to create a custom user and database during 1st initialization +*/}} +{{- define "mongodb.validateValues.customUsersDBs" -}} +{{- $customUsers := include "mongodb.customUsers" . -}} +{{- $customDatabases := include "mongodb.customDatabases" . -}} +{{- if or (and (empty $customUsers) (not (empty $customDatabases))) (and (not (empty $customUsers)) (empty $customDatabases)) }} +mongodb: auth.usernames, auth.databases + Both auth.usernames and auth.databases must be provided to create + custom users and databases during 1st initialization. + Please set both of them (--set auth.usernames[0]="xxxx",auth.databases[0]="yyyy") +{{- end -}} +{{- end -}} + +{{/* +Validate values of MongoDB® - both auth.usernames and auth.databases arrays should have the same length +to create a custom user and database during 1st initialization +*/}} +{{- define "mongodb.validateValues.customUsersDBsLength" -}} +{{- if ne (len .Values.auth.usernames) (len .Values.auth.databases) }} +mongodb: auth.usernames, auth.databases + Both auth.usernames and auth.databases arrays should have the same length +{{- end -}} +{{- end -}} + +{{/* +Validate values of MongoDB® - service type for external access +*/}} +{{- define "mongodb.validateValues.externalAccessServiceType" -}} +{{- if and (eq .Values.architecture "replicaset") (not (eq .Values.externalAccess.service.type "NodePort")) (not (eq .Values.externalAccess.service.type "LoadBalancer")) (not (eq .Values.externalAccess.service.type "ClusterIP")) -}} +mongodb: externalAccess.service.type + Available service type for external access are NodePort, LoadBalancer or ClusterIP. +{{- end -}} +{{- end -}} + +{{/* +Validate values of MongoDB® - number of replicas must be the same than LoadBalancer IPs list +*/}} +{{- define "mongodb.validateValues.loadBalancerIPsListLength" -}} +{{- $replicaCount := int .Values.replicaCount }} +{{- $loadBalancerListLength := len .Values.externalAccess.service.loadBalancerIPs }} +{{- if and (eq .Values.architecture "replicaset") .Values.externalAccess.enabled (not .Values.externalAccess.autoDiscovery.enabled ) (eq .Values.externalAccess.service.type "LoadBalancer") (not (eq $replicaCount $loadBalancerListLength )) -}} +mongodb: .Values.externalAccess.service.loadBalancerIPs + Number of replicas and loadBalancerIPs array length must be the same. +{{- end -}} +{{- end -}} + +{{/* +Validate values of MongoDB® - number of replicas must be the same than NodePort list +*/}} +{{- define "mongodb.validateValues.nodePortListLength" -}} +{{- $replicaCount := int .Values.replicaCount }} +{{- $nodePortListLength := len .Values.externalAccess.service.nodePorts }} +{{- if and (eq .Values.architecture "replicaset") .Values.externalAccess.enabled (eq .Values.externalAccess.service.type "NodePort") (not (eq $replicaCount $nodePortListLength )) -}} +mongodb: .Values.externalAccess.service.nodePorts + Number of replicas and nodePorts array length must be the same. +{{- end -}} +{{- end -}} + +{{/* +Validate values of MongoDB® - RBAC should be enabled when autoDiscovery is enabled +*/}} +{{- define "mongodb.validateValues.externalAccessAutoDiscoveryRBAC" -}} +{{- if and (eq .Values.architecture "replicaset") .Values.externalAccess.enabled .Values.externalAccess.autoDiscovery.enabled (not .Values.rbac.create ) }} +mongodb: rbac.create + By specifying "externalAccess.enabled=true" and "externalAccess.autoDiscovery.enabled=true" + an initContainer will be used to autodetect the external IPs/ports by querying the + K8s API. Please note this initContainer requires specific RBAC resources. You can create them + by specifying "--set rbac.create=true". +{{- end -}} +{{- end -}} + +{{/* +Validate values of MongoDB® exporter URI string - auth.enabled and/or tls.enabled must be enabled or it defaults +*/}} +{{- define "mongodb.mongodb_exporter.uri" -}} + {{- $uriTlsArgs := ternary "tls=true&tlsCertificateKeyFile=/certs/mongodb.pem&tlsCAFile=/certs/mongodb-ca-cert" "" .Values.tls.enabled -}} + {{- if .Values.metrics.username }} + {{- $uriAuth := ternary "$(echo $MONGODB_METRICS_USERNAME | sed -r \"s/@/%40/g;s/:/%3A/g\"):$(echo $MONGODB_METRICS_PASSWORD | sed -r \"s/@/%40/g;s/:/%3A/g\")@" "" .Values.auth.enabled -}} + {{- printf "mongodb://%slocalhost:27017/admin?%s" $uriAuth $uriTlsArgs -}} + {{- else -}} + {{- $uriAuth := ternary "$MONGODB_ROOT_USER:$(echo $MONGODB_ROOT_PASSWORD | sed -r \"s/@/%40/g;s/:/%3A/g\")@" "" .Values.auth.enabled -}} + {{- printf "mongodb://%slocalhost:27017/admin?%s" $uriAuth $uriTlsArgs -}} + {{- end -}} +{{- end -}} + + +{{/* +Return the appropriate apiGroup for PodSecurityPolicy. +*/}} +{{- define "podSecurityPolicy.apiGroup" -}} +{{- if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}} +{{- print "policy" -}} +{{- else -}} +{{- print "extensions" -}} +{{- end -}} +{{- end -}} + +{{/* +Return true if a TLS secret object should be created +*/}} +{{- define "mongodb.createTlsSecret" -}} +{{- if and .Values.tls.enabled (not .Values.tls.existingSecret) }} + {{- true -}} +{{- end -}} +{{- end -}} + +{{/* +Return the secret containing MongoDB® TLS certificates +*/}} +{{- define "mongodb.tlsSecretName" -}} +{{- $secretName := .Values.tls.existingSecret -}} +{{- if $secretName -}} + {{- printf "%s" (tpl $secretName $) -}} +{{- else -}} + {{- printf "%s-ca" (include "mongodb.fullname" .) -}} +{{- end -}} +{{- end -}} diff --git a/packages/shipa/charts/charts/mongodb/templates/arbiter/configmap.yaml b/packages/shipa/charts/charts/mongodb/templates/arbiter/configmap.yaml new file mode 100644 index 000000000..60a171f1d --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/arbiter/configmap.yaml @@ -0,0 +1,18 @@ +{{- if (include "mongodb.arbiter.createConfigmap" .) }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "mongodb.fullname" . }}-arbiter + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: arbiter + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} +data: + mongodb.conf: |- + {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.configuration "context" $) | nindent 4 }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/arbiter/headless-svc.yaml b/packages/shipa/charts/charts/mongodb/templates/arbiter/headless-svc.yaml new file mode 100644 index 000000000..6228f1065 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/arbiter/headless-svc.yaml @@ -0,0 +1,30 @@ +{{- if (include "mongodb.arbiter.enabled" .) }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "mongodb.arbiter.service.nameOverride" . }} + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: arbiter + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if or .Values.service.annotations .Values.commonAnnotations }} + annotations: + {{- if .Values.service.annotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.service.annotations "context" $) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} + {{- end }} +spec: + type: ClusterIP + clusterIP: None + ports: + - name: tcp-mongodb + port: {{ .Values.service.port }} + targetPort: mongodb + selector: {{- include "common.labels.matchLabels" . | nindent 4 }} + app.kubernetes.io/component: arbiter +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/arbiter/pdb.yaml b/packages/shipa/charts/charts/mongodb/templates/arbiter/pdb.yaml new file mode 100644 index 000000000..27932cea5 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/arbiter/pdb.yaml @@ -0,0 +1,25 @@ +{{- if and (include "mongodb.arbiter.enabled" .) .Values.arbiter.pdb.create }} +apiVersion: {{ include "common.capabilities.policy.apiVersion" . }} +kind: PodDisruptionBudget +metadata: + name: {{ include "mongodb.fullname" . }}-arbiter + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: arbiter + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} +spec: + {{- if .Values.arbiter.pdb.minAvailable }} + minAvailable: {{ .Values.arbiter.pdb.minAvailable }} + {{- end }} + {{- if .Values.arbiter.pdb.maxUnavailable }} + maxUnavailable: {{ .Values.arbiter.pdb.maxUnavailable }} + {{- end }} + selector: + matchLabels: {{ include "common.labels.matchLabels" . | nindent 6 }} + app.kubernetes.io/component: arbiter +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/arbiter/statefulset.yaml b/packages/shipa/charts/charts/mongodb/templates/arbiter/statefulset.yaml new file mode 100644 index 000000000..462754b2f --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/arbiter/statefulset.yaml @@ -0,0 +1,291 @@ +{{- if (include "mongodb.arbiter.enabled" .) }} +apiVersion: {{ include "common.capabilities.statefulset.apiVersion" . }} +kind: StatefulSet +metadata: + name: {{ include "mongodb.fullname" . }}-arbiter + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: arbiter + {{- if .Values.arbiter.labels }} + {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.labels "context" $) | nindent 4 }} + {{- end }} + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if or .Values.arbiter.annotations .Values.commonAnnotations }} + annotations: + {{- if .Values.arbiter.annotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.arbiter.annotations "context" $) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} + {{- end }} +spec: + serviceName: {{ include "mongodb.arbiter.service.nameOverride" . }} + selector: + matchLabels: {{- include "common.labels.matchLabels" . | nindent 6 }} + app.kubernetes.io/component: arbiter + template: + metadata: + labels: {{- include "common.labels.standard" . | nindent 8 }} + app.kubernetes.io/component: arbiter + {{- if .Values.arbiter.podLabels }} + {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.podLabels "context" $) | nindent 8 }} + {{- end }} + {{- if or (include "mongodb.arbiter.createConfigmap" .) .Values.arbiter.podAnnotations }} + annotations: + {{- if (include "mongodb.arbiter.createConfigmap" .) }} + checksum/configuration: {{ include (print $.Template.BasePath "/arbiter/configmap.yaml") . | sha256sum }} + {{- end }} + {{- if .Values.arbiter.podAnnotations }} + {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.podAnnotations "context" $) | nindent 8 }} + {{- end }} + {{- end }} + spec: + {{- include "mongodb.imagePullSecrets" . | nindent 6 }} + {{- if .Values.schedulerName }} + schedulerName: "{{ .Values.schedulerName }}" + {{- end }} + serviceAccountName: {{ template "mongodb.serviceAccountName" . }} + {{- if .Values.arbiter.affinity }} + affinity: {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.affinity "context" $) | nindent 8 }} + {{- else }} + affinity: + podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.arbiter.podAffinityPreset "component" "arbiter" "context" $) | nindent 10 }} + podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.arbiter.podAntiAffinityPreset "component" "arbiter" "context" $) | nindent 10 }} + nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.arbiter.nodeAffinityPreset.type "key" .Values.arbiter.nodeAffinityPreset.key "values" .Values.arbiter.nodeAffinityPreset.values) | nindent 10 }} + {{- end }} + {{- if .Values.arbiter.nodeSelector }} + nodeSelector: {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.nodeSelector "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.arbiter.hostAliases }} + hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.hostAliases "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.arbiter.tolerations }} + tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.tolerations "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.arbiter.priorityClassName }} + priorityClassName: {{ .Values.arbiter.priorityClassName }} + {{- end }} + {{- if .Values.arbiter.runtimeClassName }} + runtimeClassName: {{ .Values.arbiter.runtimeClassName }} + {{- end }} + {{- if .Values.arbiter.podSecurityContext.enabled }} + securityContext: {{- omit .Values.arbiter.podSecurityContext "enabled" | toYaml | nindent 8 }} + {{- end }} + initContainers: + {{- if .Values.arbiter.initContainers }} + {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.initContainers "context" $) | nindent 8 }} + {{- end }} + {{- if and .Values.tls.enabled .Values.arbiter.enabled }} + - name: generate-client + image: {{ include "mongodb.tls.image" . }} + imagePullPolicy: {{ .Values.tls.image.pullPolicy | quote }} + env: + - name: MY_POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + volumeMounts: + - name: certs-volume + mountPath: /certs/CAs + - name: certs + mountPath: /certs + command: + - sh + - "-c" + - | + /bin/bash <<'EOF' + my_hostname=$(hostname) + svc=$(echo -n "$my_hostname" | sed s/-[0-9]*$//)-headless + + cp /certs/CAs/* /certs/ + + cat >/certs/openssl.cnf < /certs/mongodb.pem + cd /certs/ + shopt -s extglob + rm -rf !(mongodb-ca-cert|mongodb.pem|CAs|openssl.cnf) + chmod 0600 mongodb-ca-cert mongodb.pem + EOF + {{- end }} + containers: + - name: mongodb-arbiter + image: {{ include "mongodb.image" . }} + imagePullPolicy: {{ .Values.image.pullPolicy | quote }} + {{- if .Values.arbiter.containerSecurityContext.enabled }} + securityContext: {{- omit .Values.arbiter.containerSecurityContext "enabled" | toYaml | nindent 12 }} + {{- end }} + {{- if .Values.diagnosticMode.enabled }} + command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }} + {{- else if .Values.arbiter.command }} + command: {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.command "context" $) | nindent 12 }} + {{- end }} + {{- if .Values.diagnosticMode.enabled }} + args: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.args "context" $) | nindent 12 }} + {{- else if .Values.arbiter.args }} + args: {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.args "context" $) | nindent 12 }} + {{- end }} + env: + - name: BITNAMI_DEBUG + value: {{ ternary "true" "false" (or .Values.image.debug .Values.diagnosticMode.enabled) | quote }} + - name: MY_POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: MY_POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: K8S_SERVICE_NAME + value: "{{ include "mongodb.arbiter.service.nameOverride" . }}" + - name: MONGODB_REPLICA_SET_MODE + value: "arbiter" + - name: MONGODB_INITIAL_PRIMARY_HOST + value: "{{ include "mongodb.fullname" . }}-0.{{ include "mongodb.service.nameOverride" . }}.$(MY_POD_NAMESPACE).svc.{{ .Values.clusterDomain }}" + - name: MONGODB_REPLICA_SET_NAME + value: {{ .Values.replicaSetName | quote }} + - name: MONGODB_ADVERTISED_HOSTNAME + value: "$(MY_POD_NAME).$(K8S_SERVICE_NAME).$(MY_POD_NAMESPACE).svc.{{ .Values.clusterDomain }}" + {{- if .Values.auth.enabled }} + - name: MONGODB_INITIAL_PRIMARY_ROOT_USER + value: {{ .Values.auth.rootUser | quote }} + - name: MONGODB_INITIAL_PRIMARY_ROOT_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-root-password + - name: MONGODB_REPLICA_SET_KEY + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-replica-set-key + {{- end }} + - name: ALLOW_EMPTY_PASSWORD + value: {{ ternary "no" "yes" .Values.auth.enabled | quote }} + {{- $extraFlags := .Values.arbiter.extraFlags | join " " -}} + {{- if and .Values.tls.enabled .Values.arbiter.enabled }} + {{- $extraFlags = printf "--tlsMode=%s --tlsCertificateKeyFile=/certs/mongodb.pem --tlsCAFile=/certs/mongodb-ca-cert %s" .Values.tls.mode $extraFlags }} + {{- end }} + {{- if ne $extraFlags "" }} + - name: MONGODB_EXTRA_FLAGS + value: {{ $extraFlags | quote }} + {{- end }} + {{- if and .Values.tls.enabled .Values.arbiter.enabled }} + - name: MONGODB_CLIENT_EXTRA_FLAGS + value: --tls --tlsCertificateKeyFile=/certs/mongodb.pem --tlsCAFile=/certs/mongodb-ca-cert + {{- end }} + {{- if .Values.arbiter.extraEnvVars }} + {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.extraEnvVars "context" $) | nindent 12 }} + {{- end }} + {{- if or .Values.arbiter.extraEnvVarsCM .Values.arbiter.extraEnvVarsSecret }} + envFrom: + {{- if .Values.arbiter.extraEnvVarsCM }} + - configMapRef: + name: {{ tpl .Values.arbiter.extraEnvVarsCM . | quote }} + {{- end }} + {{- if .Values.arbiter.extraEnvVarsSecret }} + - secretRef: + name: {{ tpl .Values.arbiter.extraEnvVarsSecret . | quote }} + {{- end }} + {{- end }} + ports: + - containerPort: 27017 + name: mongodb + {{- if not .Values.diagnosticMode.enabled }} + {{- if .Values.arbiter.livenessProbe.enabled }} + livenessProbe: + tcpSocket: + port: mongodb + initialDelaySeconds: {{ .Values.arbiter.livenessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.arbiter.livenessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.arbiter.livenessProbe.timeoutSeconds }} + successThreshold: {{ .Values.arbiter.livenessProbe.successThreshold }} + failureThreshold: {{ .Values.arbiter.livenessProbe.failureThreshold }} + {{- else if .Values.arbiter.customLivenessProbe }} + livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.customLivenessProbe "context" $) | nindent 12 }} + {{- end }} + {{- if .Values.arbiter.readinessProbe.enabled }} + readinessProbe: + tcpSocket: + port: mongodb + initialDelaySeconds: {{ .Values.arbiter.readinessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.arbiter.readinessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.arbiter.readinessProbe.timeoutSeconds }} + successThreshold: {{ .Values.arbiter.readinessProbe.successThreshold }} + failureThreshold: {{ .Values.arbiter.readinessProbe.failureThreshold }} + {{- else if .Values.arbiter.customReadinessProbe }} + readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.customReadinessProbe "context" $) | nindent 12 }} + {{- end }} + {{- end }} + {{- if .Values.arbiter.resources }} + resources: {{- toYaml .Values.arbiter.resources | nindent 12 }} + {{- end }} + {{- if or .Values.arbiter.configuration .Values.arbiter.existingConfigmap .Values.arbiter.extraVolumeMounts .Values.tls.enabled }} + volumeMounts: + {{- if or .Values.arbiter.configuration .Values.arbiter.existingConfigmap }} + - name: config + mountPath: /opt/bitnami/mongodb/conf/mongodb.conf + subPath: mongodb.conf + {{- end }} + {{- if and .Values.tls.enabled .Values.arbiter.enabled }} + - name: certs + mountPath: /certs + {{- end }} + {{- if .Values.arbiter.extraVolumeMounts }} + {{- toYaml .Values.arbiter.extraVolumeMounts | nindent 12 }} + {{- end }} + {{- end }} + {{- if .Values.arbiter.sidecars }} + {{- include "common.tplvalues.render" (dict "value" .Values.arbiter.sidecars "context" $) | nindent 8 }} + {{- end }} + {{- if or .Values.arbiter.configuration .Values.arbiter.existingConfigmap .Values.arbiter.extraVolumes .Values.tls.enabled }} + volumes: + {{- if or .Values.arbiter.configuration .Values.arbiter.existingConfigmap }} + - name: config + configMap: + name: {{ include "mongodb.arbiter.configmapName" . }} + {{- end }} + {{- if and .Values.tls.enabled .Values.arbiter.enabled }} + - name: certs + emptyDir: {} + - name: certs-volume + secret: + secretName: {{ template "mongodb.tlsSecretName" . }} + items: + - key: mongodb-ca-cert + path: mongodb-ca-cert + mode: 0600 + - key: mongodb-ca-key + path: mongodb-ca-key + mode: 0600 + {{- end }} + {{- if .Values.arbiter.extraVolumes }} + {{- toYaml .Values.arbiter.extraVolumes | nindent 8 }} + {{- end }} + {{- end }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/configmap.yaml b/packages/shipa/charts/charts/mongodb/templates/configmap.yaml new file mode 100644 index 000000000..529d393bc --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/configmap.yaml @@ -0,0 +1,18 @@ +{{- if (include "mongodb.createConfigmap" .) }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "mongodb.fullname" . }} + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: mongodb + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} +data: + mongodb.conf: |- + {{- include "common.tplvalues.render" (dict "value" .Values.configuration "context" $) | nindent 4 }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/extra-list.yaml b/packages/shipa/charts/charts/mongodb/templates/extra-list.yaml new file mode 100644 index 000000000..9ac65f9e1 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/extra-list.yaml @@ -0,0 +1,4 @@ +{{- range .Values.extraDeploy }} +--- +{{ include "common.tplvalues.render" (dict "value" . "context" $) }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/hidden/configmap.yaml b/packages/shipa/charts/charts/mongodb/templates/hidden/configmap.yaml new file mode 100644 index 000000000..4c222d414 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/hidden/configmap.yaml @@ -0,0 +1,15 @@ +{{- if (include "mongodb.hidden.createConfigmap" .) }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "mongodb.fullname" . }}-hidden + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: hidden + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} +data: + mongodb.conf: |- + {{- include "common.tplvalues.render" (dict "value" .Values.hidden.configuration "context" $) | nindent 4 }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/hidden/external-access-svc.yaml b/packages/shipa/charts/charts/mongodb/templates/hidden/external-access-svc.yaml new file mode 100644 index 000000000..87781ea76 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/hidden/external-access-svc.yaml @@ -0,0 +1,49 @@ +{{- if and (include "mongodb.hidden.enabled" .) .Values.externalAccess.hidden.enabled }} +{{- $fullName := include "mongodb.fullname" . }} +{{- $replicaCount := .Values.hidden.replicaCount | int }} +{{- $root := . }} + +{{- range $i, $e := until $replicaCount }} +{{- $targetPod := printf "%s-hidden-%d" (printf "%s" $fullName) $i }} +{{- $_ := set $ "targetPod" $targetPod }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ $fullName }}-hidden-{{ $i }}-external + namespace: {{ include "mongodb.namespace" $ }} + labels: {{- include "common.labels.standard" $ | nindent 4 }} + app.kubernetes.io/component: hidden + {{- if $root.Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" $root.Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + pod: {{ $targetPod }} + {{- if $root.Values.externalAccess.hidden.service.annotations }} + annotations: {{- include "common.tplvalues.render" ( dict "value" $root.Values.externalAccess.hidden.service.annotations "context" $) | nindent 4 }} + {{- end }} +spec: + type: {{ $root.Values.externalAccess.hidden.service.type }} + {{- if eq $root.Values.externalAccess.hidden.service.type "LoadBalancer" }} + {{- if not (empty $root.Values.externalAccess.hidden.service.loadBalancerIPs) }} + loadBalancerIP: {{ index $root.Values.externalAccess.hidden.service.loadBalancerIPs $i }} + {{- end }} + {{- if $root.Values.externalAccess.hidden.service.loadBalancerSourceRanges }} + loadBalancerSourceRanges: {{- toYaml $root.Values.externalAccess.hidden.service.loadBalancerSourceRanges | nindent 4 }} + {{- end }} + {{- end }} + publishNotReadyAddresses: true + ports: + - name: {{ $root.Values.service.portName }} + port: {{ $root.Values.externalAccess.hidden.service.port }} + {{- if not (empty $root.Values.externalAccess.hidden.service.nodePorts) }} + nodePort: {{ index $root.Values.externalAccess.hidden.service.nodePorts $i }} + {{- else }} + nodePort: null + {{- end }} + targetPort: mongodb + selector: {{- include "common.labels.matchLabels" $ | nindent 4 }} + app.kubernetes.io/component: hidden + statefulset.kubernetes.io/pod-name: {{ $targetPod }} +--- +{{- end }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/hidden/headless-svc.yaml b/packages/shipa/charts/charts/mongodb/templates/hidden/headless-svc.yaml new file mode 100644 index 000000000..59c4d07e1 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/hidden/headless-svc.yaml @@ -0,0 +1,25 @@ +{{- if (include "mongodb.hidden.enabled" .) }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "mongodb.fullname" . }}-hidden-headless + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: hidden + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.service.annotations }} + annotations: {{- include "common.tplvalues.render" (dict "value" .Values.service.annotations "context" $) | nindent 4 }} + {{- end }} +spec: + type: ClusterIP + clusterIP: None + publishNotReadyAddresses: true + ports: + - name: {{ .Values.service.portName }} + port: {{ .Values.service.port }} + targetPort: mongodb + selector: {{- include "common.labels.matchLabels" . | nindent 4 }} + app.kubernetes.io/component: hidden +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/hidden/pdb.yaml b/packages/shipa/charts/charts/mongodb/templates/hidden/pdb.yaml new file mode 100644 index 000000000..de77008c1 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/hidden/pdb.yaml @@ -0,0 +1,22 @@ +{{- if and (include "mongodb.hidden.enabled" .) .Values.hidden.pdb.create }} +apiVersion: {{ include "common.capabilities.policy.apiVersion" . }} +kind: PodDisruptionBudget +metadata: + name: {{ include "mongodb.fullname" . }}-hidden + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: hidden + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} +spec: + {{- if .Values.hidden.pdb.minAvailable }} + minAvailable: {{ .Values.hidden.pdb.minAvailable }} + {{- end }} + {{- if .Values.hidden.pdb.maxUnavailable }} + maxUnavailable: {{ .Values.hidden.pdb.maxUnavailable }} + {{- end }} + selector: + matchLabels: {{ include "common.labels.matchLabels" . | nindent 6 }} + app.kubernetes.io/component: hidden +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/hidden/statefulset.yaml b/packages/shipa/charts/charts/mongodb/templates/hidden/statefulset.yaml new file mode 100644 index 000000000..324d2076d --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/hidden/statefulset.yaml @@ -0,0 +1,557 @@ +{{- if (include "mongodb.hidden.enabled" .) }} +{{- $replicaCount := int .Values.hidden.replicaCount }} +{{- $loadBalancerIPListLength := len .Values.externalAccess.hidden.service.loadBalancerIPs }} +{{- if not (and .Values.externalAccess.hidden.enabled (not .Values.externalAccess.autoDiscovery.enabled) (not (eq $replicaCount $loadBalancerIPListLength )) (eq .Values.externalAccess.hidden.service.type "LoadBalancer")) }} +apiVersion: {{ include "common.capabilities.statefulset.apiVersion" . }} +kind: StatefulSet +metadata: + name: {{ include "mongodb.fullname" . }}-hidden + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: hidden + {{- if .Values.hidden.labels }} + {{- include "common.tplvalues.render" (dict "value" .Values.hidden.labels "context" $) | nindent 4 }} + {{- end }} + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.hidden.annotations }} + annotations: {{- include "common.tplvalues.render" (dict "value" .Values.hidden.annotations "context" $) | nindent 4 }} + {{- end }} +spec: + serviceName: {{ include "mongodb.fullname" . }}-hidden-headless + podManagementPolicy: {{ .Values.hidden.podManagementPolicy }} + replicas: {{ .Values.hidden.replicaCount }} + updateStrategy: + type: {{ .Values.hidden.strategyType }} + {{- if (eq "OnDelete" .Values.hidden.strategyType) }} + rollingUpdate: null + {{- end }} + selector: + matchLabels: {{- include "common.labels.matchLabels" . | nindent 6 }} + app.kubernetes.io/component: hidden + template: + metadata: + labels: {{- include "common.labels.standard" . | nindent 8 }} + app.kubernetes.io/component: hidden + {{- if .Values.hidden.podLabels }} + {{- include "common.tplvalues.render" (dict "value" .Values.hidden.podLabels "context" $) | nindent 8 }} + {{- end }} + {{- if or (include "mongodb.hidden.createConfigmap" .) .Values.hidden.podAnnotations }} + annotations: + {{- if (include "mongodb.hidden.createConfigmap" .) }} + checksum/configuration: {{ include (print $.Template.BasePath "/hidden/configmap.yaml") . | sha256sum }} + {{- end }} + {{- if .Values.hidden.podAnnotations }} + {{- include "common.tplvalues.render" (dict "value" .Values.hidden.podAnnotations "context" $) | nindent 8 }} + {{- end }} + {{- end }} + spec: + {{- include "mongodb.imagePullSecrets" . | nindent 6 }} + {{- if .Values.schedulerName }} + schedulerName: "{{ .Values.schedulerName }}" + {{- end }} + serviceAccountName: {{ template "mongodb.serviceAccountName" . }} + {{- if .Values.hidden.affinity }} + affinity: {{- include "common.tplvalues.render" (dict "value" .Values.hidden.affinity "context" $) | nindent 8 }} + {{- else }} + affinity: + podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.hidden.podAffinityPreset "component" "" "context" $) | nindent 10 }} + podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.hidden.podAntiAffinityPreset "component" "" "context" $) | nindent 10 }} + nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.hidden.nodeAffinityPreset.type "key" .Values.nodeAffinityPreset.key "values" .Values.nodeAffinityPreset.values) | nindent 10 }} + {{- end }} + {{- if .Values.hidden.nodeSelector }} + nodeSelector: {{- include "common.tplvalues.render" (dict "value" .Values.hidden.nodeSelector "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.hidden.tolerations }} + tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.hidden.tolerations "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.hidden.priorityClassName }} + priorityClassName: {{ .Values.hidden.priorityClassName }} + {{- end }} + {{- if .Values.hidden.runtimeClassName }} + runtimeClassName: {{ .Values.hidden.runtimeClassName }} + {{- end }} + {{- if .Values.podSecurityContext.enabled }} + securityContext: {{- omit .Values.podSecurityContext "enabled" | toYaml | nindent 8 }} + {{- end }} + {{- if or .Values.hidden.initContainers (and .Values.volumePermissions.enabled .Values.hidden.persistence.enabled) (and .Values.externalAccess.hidden.enabled .Values.externalAccess.autoDiscovery.enabled) .Values.tls.enabled }} + initContainers: + {{- if .Values.hidden.initContainers }} + {{- include "common.tplvalues.render" (dict "value" .Values.hidden.initContainers "context" $) | nindent 8 }} + {{- end }} + {{- if and .Values.volumePermissions.enabled .Values.hidden.persistence.enabled }} + - name: volume-permissions + image: {{ include "mongodb.volumePermissions.image" . }} + imagePullPolicy: {{ .Values.volumePermissions.image.pullPolicy | quote }} + command: + - /bin/bash + - -ec + args: + - | + mkdir -p {{ .Values.hidden.persistence.mountPath }}{{- if .Values.hidden.persistence.subPath }}/{{ .Values.hidden.persistence.subPath }}{{- end }} + {{- if and .Values.podSecurityContext.enabled .Values.containerSecurityContext.enabled }} + chown -R "{{ .Values.containerSecurityContext.runAsUser }}:{{ .Values.podSecurityContext.fsGroup }}" "{{ .Values.hidden.persistence.mountPath }}{{- if .Values.hidden.persistence.subPath }}/{{ .Values.hidden.persistence.subPath }}{{- end }}" + {{- end }} + {{- if eq ( toString ( .Values.volumePermissions.securityContext.runAsUser )) "auto" }} + securityContext: {{- omit .Values.volumePermissions.securityContext "runAsUser" | toYaml | nindent 12 }} + {{- else }} + securityContext: {{- .Values.volumePermissions.securityContext | toYaml | nindent 12 }} + {{- end }} + {{- if .Values.volumePermissions.resources }} + resources: {{- toYaml .Values.volumePermissions.resources | nindent 12 }} + {{- end }} + volumeMounts: + - name: datadir + mountPath: {{ .Values.hidden.persistence.mountPath }} + {{- end }} + {{- if .Values.tls.enabled }} + - name: generate-tls-certs + image: {{ include "mongodb.tls.image" . }} + imagePullPolicy: {{ .Values.tls.image.pullPolicy | quote }} + env: + - name: MY_POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: MY_POD_HOST_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + volumeMounts: + - name: certs-volume + mountPath: /certs/CAs + - name: certs + mountPath: /certs + command: + - sh + - "-c" + - | + /bin/bash <<'EOF' + my_hostname=$(hostname) + svc=$(echo -n "$my_hostname" | sed s/-[0-9]*$//)-headless + cp /certs/CAs/* /certs/ + cat >/certs/openssl.cnf < /certs/mongodb.pem + cd /certs/ + shopt -s extglob + rm -rf !(mongodb-ca-cert|mongodb.pem|CAs|openssl.cnf) + chmod 0600 mongodb-ca-cert mongodb.pem + EOF + {{- end }} + {{- if and .Values.externalAccess.hidden.enabled .Values.externalAccess.autoDiscovery.enabled (eq .Values.externalAccess.hidden.service.type "LoadBalancer") }} + - name: auto-discovery + image: {{ include "mongodb.externalAccess.autoDiscovery.image" . }} + imagePullPolicy: {{ .Values.externalAccess.autoDiscovery.image.pullPolicy | quote }} + command: + - /scripts/auto-discovery.sh + env: + - name: MY_POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: SHARED_FILE + value: "/shared/info.txt" + {{- if .Values.externalAccess.autoDiscovery.resources }} + resources: {{- toYaml .Values.externalAccess.autoDiscovery.resources | nindent 12 }} + {{- end }} + volumeMounts: + - name: shared + mountPath: /shared + - name: scripts + mountPath: /scripts/auto-discovery.sh + subPath: auto-discovery.sh + {{- end }} + {{- end }} + containers: + - name: mongodb + image: {{ include "mongodb.image" . }} + imagePullPolicy: {{ .Values.image.pullPolicy | quote }} + {{- if .Values.containerSecurityContext.enabled }} + securityContext: {{- omit .Values.containerSecurityContext "enabled" | toYaml | nindent 12 }} + {{- end }} + {{- if .Values.diagnosticMode.enabled }} + command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }} + {{- else if .Values.hidden.command }} + command: {{- include "common.tplvalues.render" (dict "value" .Values.hidden.command "context" $) | nindent 12 }} + {{- else }} + command: + - /scripts/setup-hidden.sh + {{- end }} + {{- if .Values.diagnosticMode.enabled }} + args: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.args "context" $) | nindent 12 }} + {{- else if .Values.hidden.args }} + args: {{- include "common.tplvalues.render" (dict "value" .Values.hidden.args "context" $) | nindent 12 }} + {{- end }} + env: + - name: BITNAMI_DEBUG + value: {{ ternary "true" "false" (or .Values.image.debug .Values.diagnosticMode.enabled) | quote }} + {{- if and .Values.externalAccess.hidden.enabled .Values.externalAccess.autoDiscovery.enabled (eq .Values.externalAccess.hidden.service.type "LoadBalancer") }} + - name: SHARED_FILE + value: "/shared/info.txt" + {{- end }} + - name: MY_POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: MY_POD_HOST_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: MY_POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: K8S_SERVICE_NAME + value: "{{ include "mongodb.service.nameOverride" . }}" + - name: K8S_HIDDEN_NODE_SERVICE_NAME + value: "{{ include "mongodb.fullname" . }}-hidden-headless" + - name: MONGODB_REPLICA_SET_MODE + value: "hidden" + - name: MONGODB_INITIAL_PRIMARY_HOST + value: "{{ include "mongodb.fullname" . }}-0.$(K8S_SERVICE_NAME).$(MY_POD_NAMESPACE).svc.{{ .Values.clusterDomain }}" + - name: MONGODB_REPLICA_SET_NAME + value: {{ .Values.replicaSetName | quote }} + {{- if and .Values.replicaSetHostnames (not .Values.externalAccess.hidden.enabled) }} + - name: MONGODB_ADVERTISED_HOSTNAME + value: "$(MY_POD_NAME).$(K8S_HIDDEN_NODE_SERVICE_NAME).$(MY_POD_NAMESPACE).svc.{{ .Values.clusterDomain }}" + {{- end }} + {{- $customUsers := include "mongodb.customUsers" . -}} + {{- $customDatabases := include "mongodb.customDatabases" . -}} + {{- if not (empty $customUsers) }} + - name: MONGODB_EXTRA_USERNAMES + value: {{ $customUsers | quote }} + {{- end }} + {{- if not (empty $customDatabases) }} + - name: MONGODB_EXTRA_DATABASES + value: {{ $customDatabases | quote }} + {{- end }} + {{- if .Values.auth.enabled }} + {{- if and (not (empty $customUsers)) (not (empty $customDatabases)) }} + - name: MONGODB_EXTRA_PASSWORDS + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-passwords + {{- end }} + - name: MONGODB_ROOT_USER + value: {{ .Values.auth.rootUser | quote }} + - name: MONGODB_ROOT_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-root-password + - name: MONGODB_REPLICA_SET_KEY + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-replica-set-key + {{- end }} + {{- if and .Values.metrics.enabled (not (empty .Values.metrics.username)) }} + - name: MONGODB_METRICS_USERNAME + value: {{ .Values.metrics.username | quote }} + {{- if .Values.auth.enabled }} + - name: MONGODB_METRICS_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-metrics-password + {{- end }} + {{- end }} + - name: ALLOW_EMPTY_PASSWORD + value: {{ ternary "no" "yes" .Values.auth.enabled | quote }} + - name: MONGODB_SYSTEM_LOG_VERBOSITY + value: {{ .Values.systemLogVerbosity | quote }} + - name: MONGODB_DISABLE_SYSTEM_LOG + value: {{ ternary "yes" "no" .Values.disableSystemLog | quote }} + - name: MONGODB_DISABLE_JAVASCRIPT + value: {{ ternary "yes" "no" .Values.disableJavascript | quote }} + - name: MONGODB_ENABLE_JOURNAL + value: {{ ternary "yes" "no" .Values.enableJournal | quote }} + - name: MONGODB_ENABLE_IPV6 + value: {{ ternary "yes" "no" .Values.enableIPv6 | quote }} + - name: MONGODB_ENABLE_DIRECTORY_PER_DB + value: {{ ternary "yes" "no" .Values.directoryPerDB | quote }} + {{- $extraFlags := .Values.hidden.extraFlags | join " " -}} + {{- if .Values.tls.enabled }} + {{- $extraFlags = printf "--tlsMode=%s --tlsCertificateKeyFile=/certs/mongodb.pem --tlsCAFile=/certs/mongodb-ca-cert %s" .Values.tls.mode $extraFlags }} + {{- end }} + {{- if ne $extraFlags "" }} + - name: MONGODB_EXTRA_FLAGS + value: {{ $extraFlags | quote }} + {{- end }} + {{- if .Values.tls.enabled }} + - name: MONGODB_CLIENT_EXTRA_FLAGS + value: --tls --tlsCertificateKeyFile=/certs/mongodb.pem --tlsCAFile=/certs/mongodb-ca-cert + {{- end }} + {{- if .Values.hidden.extraEnvVars }} + {{- include "common.tplvalues.render" (dict "value" .Values.hidden.extraEnvVars "context" $) | nindent 12 }} + {{- end }} + {{- if or .Values.hidden.extraEnvVarsCM .Values.hidden.extraEnvVarsSecret }} + envFrom: + {{- if .Values.hidden.extraEnvVarsCM }} + - configMapRef: + name: {{ tpl .Values.hidden.extraEnvVarsCM . | quote }} + {{- end }} + {{- if .Values.hidden.extraEnvVarsSecret }} + - secretRef: + name: {{ tpl .Values.hidden.extraEnvVarsSecret . | quote }} + {{- end }} + {{- end }} + ports: + - containerPort: 27017 + name: mongodb + {{- if not .Values.diagnosticMode.enabled }} + {{- if .Values.hidden.livenessProbe.enabled }} + livenessProbe: + exec: + command: + - mongo + {{- if .Values.tls.enabled }} + - --tls + - --tlsCertificateKeyFile=/certs/mongodb.pem + - --tlsCAFile=/certs/mongodb-ca-cert + {{- end }} + - --eval + - "db.adminCommand('ping')" + initialDelaySeconds: {{ .Values.hidden.livenessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.hidden.livenessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.hidden.livenessProbe.timeoutSeconds }} + successThreshold: {{ .Values.hidden.livenessProbe.successThreshold }} + failureThreshold: {{ .Values.hidden.livenessProbe.failureThreshold }} + {{- else if .Values.hidden.customLivenessProbe }} + livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.hidden.customLivenessProbe "context" $) | nindent 12 }} + {{- end }} + {{- if .Values.hidden.readinessProbe.enabled }} + readinessProbe: + exec: + command: + - mongo + {{- if .Values.tls.enabled }} + - --tls + - --tlsCertificateKeyFile=/certs/mongodb.pem + - --tlsCAFile=/certs/mongodb-ca-cert + {{- end }} + - --eval + - "db.adminCommand('ping')" + initialDelaySeconds: {{ .Values.hidden.readinessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.hidden.readinessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.hidden.readinessProbe.timeoutSeconds }} + successThreshold: {{ .Values.hidden.readinessProbe.successThreshold }} + failureThreshold: {{ .Values.hidden.readinessProbe.failureThreshold }} + {{- else if .Values.hidden.customReadinessProbe }} + readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.hidden.customReadinessProbe "context" $) | nindent 12 }} + {{- end }} + {{- end }} + {{- if .Values.hidden.resources }} + resources: {{- toYaml .Values.hidden.resources | nindent 12 }} + {{- end }} + volumeMounts: + - name: datadir + mountPath: {{ .Values.hidden.persistence.mountPath }} + subPath: {{ .Values.hidden.persistence.subPath }} + {{- if or .Values.initdbScriptsConfigMap .Values.initdbScripts }} + - name: custom-init-scripts + mountPath: /docker-entrypoint-initdb.d + {{- end }} + {{- if or .Values.hidden.configuration .Values.hidden.existingConfigmap }} + - name: config + mountPath: /opt/bitnami/mongodb/conf/mongodb.conf + subPath: mongodb.conf + {{- end }} + - name: scripts + mountPath: /scripts/setup-hidden.sh + subPath: setup-hidden.sh + {{- if and .Values.externalAccess.hidden.enabled .Values.externalAccess.autoDiscovery.enabled (eq .Values.externalAccess.hidden.service.type "LoadBalancer") }} + - name: shared + mountPath: /shared + {{- end }} + {{- if .Values.tls.enabled }} + - name: certs + mountPath: /certs + {{- end }} + {{- if .Values.hidden.extraVolumeMounts }} + {{- toYaml .Values.hidden.extraVolumeMounts | nindent 12 }} + {{- end }} + {{- if .Values.metrics.enabled }} + - name: metrics + image: {{ template "mongodb.metrics.image" . }} + imagePullPolicy: {{ .Values.metrics.image.pullPolicy | quote }} + {{- if .Values.containerSecurityContext.enabled }} + securityContext: {{- omit .Values.containerSecurityContext "enabled" | toYaml | nindent 12 }} + {{- end }} + {{- if .Values.diagnosticMode.enabled }} + command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }} + {{- else }} + command: + - /bin/bash + - -ec + {{- end }} + {{- if .Values.diagnosticMode.enabled }} + args: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.args "context" $) | nindent 12 }} + {{- else }} + args: + - | + /bin/mongodb_exporter --mongodb.uri "{{ include "mongodb.mongodb_exporter.uri" . }}" {{ .Values.metrics.extraFlags }} + {{- end }} + env: + {{- if .Values.auth.enabled }} + {{- if not .Values.metrics.username }} + - name: MONGODB_ROOT_USER + value: {{ .Values.auth.rootUser | quote }} + - name: MONGODB_ROOT_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-root-password + {{- else }} + - name: MONGODB_METRICS_USERNAME + value: {{ .Values.metrics.username | quote }} + - name: MONGODB_METRICS_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-metrics-password + {{- end }} + {{- end }} + volumeMounts: + {{- if .Values.tls.enabled }} + - name: certs + mountPath: /certs + {{- end }} + ports: + - name: metrics + containerPort: 9216 + {{- if not .Values.diagnosticMode.enabled }} + {{- if .Values.metrics.livenessProbe.enabled }} + livenessProbe: + httpGet: + path: / + port: metrics + initialDelaySeconds: {{ .Values.metrics.livenessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.metrics.livenessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.metrics.livenessProbe.timeoutSeconds }} + failureThreshold: {{ .Values.metrics.livenessProbe.failureThreshold }} + successThreshold: {{ .Values.metrics.livenessProbe.successThreshold }} + {{- end }} + {{- if .Values.metrics.readinessProbe.enabled }} + readinessProbe: + httpGet: + path: / + port: metrics + initialDelaySeconds: {{ .Values.metrics.readinessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.metrics.readinessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.metrics.readinessProbe.timeoutSeconds }} + failureThreshold: {{ .Values.metrics.readinessProbe.failureThreshold }} + successThreshold: {{ .Values.metrics.readinessProbe.successThreshold }} + {{- end }} + {{- end }} + {{- if .Values.metrics.resources }} + resources: {{- toYaml .Values.metrics.resources | nindent 12 }} + {{- end }} + {{- end }} + {{- if .Values.hidden.sidecars }} + {{- include "common.tplvalues.render" (dict "value" .Values.hidden.sidecars "context" $) | nindent 8 }} + {{- end }} + volumes: + {{- if or .Values.initdbScriptsConfigMap .Values.initdbScripts }} + - name: custom-init-scripts + configMap: + name: {{ template "mongodb.initdbScriptsCM" . }} + {{- end }} + {{- if or .Values.hidden.configuration .Values.hidden.existingConfigmap }} + - name: config + configMap: + name: {{ include "mongodb.hidden.configmapName" . }} + {{- end }} + {{- if and .Values.externalAccess.hidden.enabled .Values.externalAccess.autoDiscovery.enabled (eq .Values.externalAccess.hidden.service.type "LoadBalancer") }} + - name: shared + emptyDir: {} + {{- end }} + - name: scripts + configMap: + name: {{ include "mongodb.fullname" . }}-scripts + defaultMode: 0755 + {{- if .Values.hidden.extraVolumes }} + {{- toYaml .Values.hidden.extraVolumes | nindent 8 }} + {{- end }} + {{- if .Values.tls.enabled }} + - name: certs + emptyDir: {} + - name: certs-volume + secret: + secretName: {{ template "mongodb.tlsSecretName" . }} + items: + - key: mongodb-ca-cert + path: mongodb-ca-cert + mode: 0600 + - key: mongodb-ca-key + path: mongodb-ca-key + mode: 0600 + {{- end }} + {{- if not .Values.hidden.persistence.enabled }} + - name: datadir + {{- if .Values.hidden.persistence.medium }} + emptyDir: + medium: {{ .Values.hidden.persistence.medium | quote }} + {{- else }} + emptyDir: {} + {{- end }} + {{- else }} + volumeClaimTemplates: + - metadata: + name: datadir + {{- if .Values.hidden.persistence.annotations }} + annotations: {{- include "common.tplvalues.render" (dict "value" .Values.hidden.persistence.annotations "context" $) | nindent 10 }} + {{- end }} + spec: + accessModes: + {{- range .Values.hidden.persistence.accessModes }} + - {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.hidden.persistence.size | quote }} + {{- if .Values.hidden.persistence.volumeClaimTemplates.requests }} + {{- include "common.tplvalues.render" (dict "value" .Values.hidden.persistence.volumeClaimTemplates.requests "context" $) | nindent 12 }} + {{- end }} + {{- if .Values.hidden.persistence.volumeClaimTemplates.dataSource }} + dataSource: {{- include "common.tplvalues.render" (dict "value" .Values.hidden.persistence.volumeClaimTemplates.dataSource "context" $) | nindent 10 }} + {{- end }} + {{- if .Values.hidden.persistence.volumeClaimTemplates.selector }} + selector: {{- include "common.tplvalues.render" (dict "value" .Values.hidden.persistence.volumeClaimTemplates.selector "context" $) | nindent 10 }} + {{- end }} + {{ include "common.storage.class" (dict "persistence" .Values.hidden.persistence "global" .Values.global) }} + {{- end }} +{{- end }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/initialization-configmap.yaml b/packages/shipa/charts/charts/mongodb/templates/initialization-configmap.yaml new file mode 100644 index 000000000..91d0cd844 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/initialization-configmap.yaml @@ -0,0 +1,17 @@ +{{- if and .Values.initdbScripts (not .Values.initdbScriptsConfigMap) }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "mongodb.fullname" . }}-init-scripts + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: mongodb + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} +data: +{{- include "common.tplvalues.render" (dict "value" .Values.initdbScripts "context" .) | nindent 2 }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/metrics-svc.yaml b/packages/shipa/charts/charts/mongodb/templates/metrics-svc.yaml new file mode 100644 index 000000000..e27eadbb0 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/metrics-svc.yaml @@ -0,0 +1,24 @@ +{{- if .Values.metrics.enabled }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "mongodb.fullname" . }}-metrics + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: metrics + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.metrics.service.annotations }} + annotations: {{- include "common.tplvalues.render" (dict "value" .Values.metrics.service.annotations "context" $) | nindent 4 }} + {{- end }} +spec: + type: {{ .Values.metrics.service.type }} + ports: + - port: {{ .Values.metrics.service.port }} + targetPort: metrics + protocol: TCP + name: http-metrics + selector: {{- include "common.labels.matchLabels" $ | nindent 4 }} + app.kubernetes.io/component: mongodb +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/prometheusrule.yaml b/packages/shipa/charts/charts/mongodb/templates/prometheusrule.yaml new file mode 100644 index 000000000..b4809af7d --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/prometheusrule.yaml @@ -0,0 +1,17 @@ +{{- if and .Values.metrics.enabled .Values.metrics.prometheusRule.enabled }} +apiVersion: monitoring.coreos.com/v1 +kind: PrometheusRule +metadata: + name: {{ include "mongodb.fullname" . }} + namespace: {{ include "mongodb.prometheusRule.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.metrics.prometheusRule.additionalLabels }} + {{- include "common.tplvalues.render" (dict "value" .Values.metrics.prometheusRule.additionalLabels "context" $) | nindent 4 }} + {{- end }} +spec: + groups: + {{- include "common.tplvalues.render" (dict "value" .Values.metrics.prometheusRule.rules "context" $) | nindent 2 }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/psp.yaml b/packages/shipa/charts/charts/mongodb/templates/psp.yaml new file mode 100644 index 000000000..3af67d52a --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/psp.yaml @@ -0,0 +1,49 @@ +{{- $pspAvailable := (semverCompare "<1.25-0" (include "common.capabilities.kubeVersion" .)) -}} +{{- if and $pspAvailable .Values.podSecurityPolicy.create }} +apiVersion: policy/v1beta1 +kind: PodSecurityPolicy +metadata: + name: {{ include "mongodb.fullname" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} +spec: +{{- if .Values.podSecurityPolicy.spec }} +{{ include "common.tplvalues.render" ( dict "value" .Values.podSecurityPolicy.spec "context" $ ) | nindent 2 }} +{{- else }} + allowPrivilegeEscalation: {{ .Values.podSecurityPolicy.allowPrivilegeEscalation }} + fsGroup: + rule: 'MustRunAs' + ranges: + - min: {{ .Values.podSecurityContext.fsGroup }} + max: {{ .Values.podSecurityContext.fsGroup }} + hostIPC: false + hostNetwork: false + hostPID: false + privileged: {{ .Values.podSecurityPolicy.privileged }} + readOnlyRootFilesystem: false + requiredDropCapabilities: + - ALL + runAsUser: + rule: 'MustRunAs' + ranges: + - min: {{ .Values.containerSecurityContext.runAsUser }} + max: {{ .Values.containerSecurityContext.runAsUser }} + seLinux: + rule: 'RunAsAny' + supplementalGroups: + rule: 'MustRunAs' + ranges: + - min: {{ .Values.containerSecurityContext.runAsUser }} + max: {{ .Values.containerSecurityContext.runAsUser }} + volumes: + - 'configMap' + - 'secret' + - 'emptyDir' + - 'persistentVolumeClaim' +{{- end }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/replicaset/external-access-svc.yaml b/packages/shipa/charts/charts/mongodb/templates/replicaset/external-access-svc.yaml new file mode 100644 index 000000000..b000b734b --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/replicaset/external-access-svc.yaml @@ -0,0 +1,47 @@ +{{- if and (eq .Values.architecture "replicaset") .Values.externalAccess.enabled (not (eq .Values.externalAccess.service.type "ClusterIP")) }} +{{- $fullName := include "mongodb.fullname" . }} +{{- $replicaCount := .Values.replicaCount | int }} +{{- $root := . }} + +{{- range $i, $e := until $replicaCount }} +{{- $targetPod := printf "%s-%d" (printf "%s" $fullName) $i }} +{{- $_ := set $ "targetPod" $targetPod }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ $fullName }}-{{ $i }}-external + namespace: {{ include "mongodb.namespace" $ }} + labels: {{- include "common.labels.standard" $ | nindent 4 }} + app.kubernetes.io/component: mongodb + {{- if $root.Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" $root.Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + pod: {{ $targetPod }} + {{- if $root.Values.externalAccess.service.annotations }} + annotations: {{- include "common.tplvalues.render" ( dict "value" $root.Values.externalAccess.service.annotations "context" $) | nindent 4 }} + {{- end }} +spec: + type: {{ $root.Values.externalAccess.service.type }} + {{- if eq $root.Values.externalAccess.service.type "LoadBalancer" }} + {{- if not (empty $root.Values.externalAccess.service.loadBalancerIPs) }} + loadBalancerIP: {{ index $root.Values.externalAccess.service.loadBalancerIPs $i }} + {{- end }} + {{- if $root.Values.externalAccess.service.loadBalancerSourceRanges }} + loadBalancerSourceRanges: {{- toYaml $root.Values.externalAccess.service.loadBalancerSourceRanges | nindent 4 }} + {{- end }} + {{- end }} + publishNotReadyAddresses: true + ports: + - name: {{ $root.Values.service.portName }} + port: {{ $root.Values.externalAccess.service.port }} + {{- if not (empty $root.Values.externalAccess.service.nodePorts) }} + nodePort: {{ index $root.Values.externalAccess.service.nodePorts $i }} + {{- end }} + targetPort: mongodb + selector: {{- include "common.labels.matchLabels" $ | nindent 4 }} + app.kubernetes.io/component: mongodb + statefulset.kubernetes.io/pod-name: {{ $targetPod }} +--- +{{- end }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/replicaset/headless-svc.yaml b/packages/shipa/charts/charts/mongodb/templates/replicaset/headless-svc.yaml new file mode 100644 index 000000000..0021352ec --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/replicaset/headless-svc.yaml @@ -0,0 +1,31 @@ +{{- if eq .Values.architecture "replicaset" }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "mongodb.service.nameOverride" . }} + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: mongodb + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if or .Values.service.annotations .Values.commonAnnotations }} + annotations: + {{- if .Values.service.annotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.service.annotations "context" $) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} + {{- end }} +spec: + type: ClusterIP + clusterIP: None + publishNotReadyAddresses: true + ports: + - name: {{ .Values.service.portName }} + port: {{ .Values.service.port }} + targetPort: mongodb + selector: {{- include "common.labels.matchLabels" . | nindent 4 }} + app.kubernetes.io/component: mongodb +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/replicaset/pdb.yaml b/packages/shipa/charts/charts/mongodb/templates/replicaset/pdb.yaml new file mode 100644 index 000000000..94bd2aceb --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/replicaset/pdb.yaml @@ -0,0 +1,25 @@ +{{- if and (eq .Values.architecture "replicaset") .Values.pdb.create }} +apiVersion: {{ include "common.capabilities.policy.apiVersion" . }} +kind: PodDisruptionBudget +metadata: + name: {{ include "mongodb.fullname" . }} + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: mongodb + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} +spec: + {{- if .Values.pdb.minAvailable }} + minAvailable: {{ .Values.pdb.minAvailable }} + {{- end }} + {{- if .Values.pdb.maxUnavailable }} + maxUnavailable: {{ .Values.pdb.maxUnavailable }} + {{- end }} + selector: + matchLabels: {{ include "common.labels.matchLabels" . | nindent 6 }} + app.kubernetes.io/component: mongodb +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/replicaset/scripts-configmap.yaml b/packages/shipa/charts/charts/mongodb/templates/replicaset/scripts-configmap.yaml new file mode 100644 index 000000000..6b9d82a10 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/replicaset/scripts-configmap.yaml @@ -0,0 +1,259 @@ +{{- if eq .Values.architecture "replicaset" }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "mongodb.fullname" . }}-scripts + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: mongodb + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} +data: + {{- $fullname := include "mongodb.fullname" . }} + {{- $releaseNamespace := include "mongodb.namespace" . }} + {{- if and .Values.externalAccess.autoDiscovery.enabled (eq .Values.externalAccess.service.type "LoadBalancer") }} + auto-discovery.sh: |- + #!/bin/bash + + SVC_NAME="${MY_POD_NAME}-external" + + # Auxiliary functions + retry_while() { + local -r cmd="${1:?cmd is missing}" + local -r retries="${2:-12}" + local -r sleep_time="${3:-5}" + local return_value=1 + + read -r -a command <<< "$cmd" + for ((i = 1 ; i <= retries ; i+=1 )); do + "${command[@]}" && return_value=0 && break + sleep "$sleep_time" + done + return $return_value + } + k8s_svc_lb_ip() { + local namespace=${1:?namespace is missing} + local service=${2:?service is missing} + local service_ip=$(kubectl get svc "$service" -n "$namespace" -o jsonpath="{.status.loadBalancer.ingress[0].ip}") + local service_hostname=$(kubectl get svc "$service" -n "$namespace" -o jsonpath="{.status.loadBalancer.ingress[0].hostname}") + + if [[ -n ${service_ip} ]]; then + echo "${service_ip}" + else + echo "${service_hostname}" + fi + } + k8s_svc_lb_ip_ready() { + local namespace=${1:?namespace is missing} + local service=${2:?service is missing} + [[ -n "$(k8s_svc_lb_ip "$namespace" "$service")" ]] + } + # Wait until LoadBalancer IP is ready + retry_while "k8s_svc_lb_ip_ready {{ $releaseNamespace }} $SVC_NAME" || exit 1 + # Obtain LoadBalancer external IP + k8s_svc_lb_ip "{{ $releaseNamespace }}" "$SVC_NAME" | tee "$SHARED_FILE" + {{- end }} + setup.sh: |- + #!/bin/bash + + . /opt/bitnami/scripts/mongodb-env.sh + + {{- if .Values.externalAccess.enabled }} + {{- if eq .Values.externalAccess.service.type "LoadBalancer" }} + {{- if .Values.externalAccess.autoDiscovery.enabled }} + export MONGODB_ADVERTISED_HOSTNAME="$(<${SHARED_FILE})" + {{- else }} + ID="${MY_POD_NAME#"{{ $fullname }}-"}" + export MONGODB_ADVERTISED_HOSTNAME=$(echo '{{ .Values.externalAccess.service.loadBalancerIPs }}' | tr -d '[]' | cut -d ' ' -f "$(($ID + 1))") + {{- end }} + {{- else if eq .Values.externalAccess.service.type "NodePort" }} + ID="${MY_POD_NAME#"{{ $fullname }}-"}" + export MONGODB_ADVERTISED_PORT_NUMBER=$(echo '{{ .Values.externalAccess.service.nodePorts }}' | tr -d '[]' | cut -d ' ' -f "$(($ID + 1))") + {{- if .Values.externalAccess.service.domain }} + export MONGODB_ADVERTISED_HOSTNAME={{ .Values.externalAccess.service.domain }} + {{- else }} + export MONGODB_ADVERTISED_HOSTNAME=$MY_POD_HOST_IP + {{- end }} + {{- end }} + {{- end }} + + {{- if .Values.replicaSetConfigurationSettings.enabled }} + # placed here before root password env is overwritten + # makes no assumption about starting state + # ensures that any stepDown or non-default starting state is handled + /scripts/replicaSetConfigurationSettings.sh & + {{- end }} + + echo "Advertised Hostname: $MONGODB_ADVERTISED_HOSTNAME" + echo "Advertised Port: $MONGODB_ADVERTISED_PORT_NUMBER" + + if [[ "$MY_POD_NAME" = "{{ $fullname }}-0" ]]; then + echo "Pod name matches initial primary pod name, configuring node as a primary" + export MONGODB_REPLICA_SET_MODE="primary" + else + echo "Pod name doesn't match initial primary pod name, configuring node as a secondary" + export MONGODB_REPLICA_SET_MODE="secondary" + export MONGODB_INITIAL_PRIMARY_ROOT_USER="$MONGODB_ROOT_USER" + export MONGODB_INITIAL_PRIMARY_ROOT_PASSWORD="$MONGODB_ROOT_PASSWORD" + export MONGODB_INITIAL_PRIMARY_PORT_NUMBER="$MONGODB_PORT_NUMBER" + export MONGODB_ROOT_PASSWORD="" + export MONGODB_EXTRA_USERNAMES="" + export MONGODB_EXTRA_DATABASES="" + export MONGODB_EXTRA_PASSWORDS="" + export MONGODB_ROOT_PASSWORD_FILE="" + export MONGODB_EXTRA_USERNAMES_FILE="" + export MONGODB_EXTRA_DATABASES_FILE="" + export MONGODB_EXTRA_PASSWORDS_FILE="" + fi + + exec /opt/bitnami/scripts/mongodb/entrypoint.sh /opt/bitnami/scripts/mongodb/run.sh + setup-hidden.sh: |- + #!/bin/bash + + . /opt/bitnami/scripts/mongodb-env.sh + + {{- if .Values.externalAccess.hidden.enabled }} + {{- if eq .Values.externalAccess.hidden.service.type "LoadBalancer" }} + {{- if .Values.externalAccess.autoDiscovery.enabled }} + export MONGODB_ADVERTISED_HOSTNAME="$(<${SHARED_FILE})" + {{- else }} + ID="${MY_POD_NAME#"{{ $fullname }}-hidden-"}" + export MONGODB_ADVERTISED_HOSTNAME=$(echo '{{ .Values.externalAccess.hidden.service.loadBalancerIPs }}' | tr -d '[]' | cut -d ' ' -f "$(($ID + 1))") + {{- end }} + {{- else if eq .Values.externalAccess.hidden.service.type "NodePort" }} + ID="${MY_POD_NAME#"{{ $fullname }}-hidden-"}" + export MONGODB_ADVERTISED_PORT_NUMBER=$(echo '{{ .Values.externalAccess.hidden.service.nodePorts }}' | tr -d '[]' | cut -d ' ' -f "$(($ID + 1))") + {{- if .Values.externalAccess.hidden.service.domain }} + export MONGODB_ADVERTISED_HOSTNAME={{ .Values.externalAccess.hidden.service.domain }} + {{- else }} + export MONGODB_ADVERTISED_HOSTNAME=$MY_POD_HOST_IP + {{- end }} + {{- end }} + {{- end }} + + {{- if .Values.replicaSetConfigurationSettings.enabled }} + # placed here before root password env is overwritten + # makes no assumption about starting state + # ensures that any stepDown or non-default starting state is handled + /scripts/replicaSetConfigurationSettings.sh & + {{- end }} + + echo "Advertised Hostname: $MONGODB_ADVERTISED_HOSTNAME" + echo "Advertised Port: $MONGODB_ADVERTISED_PORT_NUMBER" + echo "Configuring node as a hidden node" + export MONGODB_REPLICA_SET_MODE="hidden" + export MONGODB_INITIAL_PRIMARY_ROOT_USER="$MONGODB_ROOT_USER" + export MONGODB_INITIAL_PRIMARY_ROOT_PASSWORD="$MONGODB_ROOT_PASSWORD" + export MONGODB_INITIAL_PRIMARY_PORT_NUMBER="$MONGODB_PORT_NUMBER" + export MONGODB_ROOT_PASSWORD="" + export MONGODB_EXTRA_USERNAMES="" + export MONGODB_EXTRA_DATABASES="" + export MONGODB_EXTRA_PASSWORDS="" + export MONGODB_ROOT_PASSWORD_FILE="" + export MONGODB_EXTRA_USERNAMES_FILE="" + export MONGODB_EXTRA_DATABASES_FILE="" + export MONGODB_EXTRA_PASSWORDS_FILE="" + exec /opt/bitnami/scripts/mongodb/entrypoint.sh /opt/bitnami/scripts/mongodb/run.sh + {{- if .Values.replicaSetConfigurationSettings.enabled }} + replicaSetConfigurationSettings.sh: |- + #!/bin/bash + # This script to be called when pod starts. + # This script sets rs settings which can not be applied via conf file + + function logger () + #$1 is the line to be logged + { + echo "replicaSetConfigurationSettings.sh -- ${1}" >&1 + } + + SLEEP_PERIOD=10 + + {{- if and .Values.auth.enabled .Values.auth.rootPassword }} + usernameAndPassword="-u root -p ${MONGODB_ROOT_PASSWORD}" + {{- else }} + usernameAndPassword="" + {{- end }} + + # load Values.replicaSetConfigurationSettings.configuration into associtive array which makes iterating and string manipulation easy + declare -A desiredRsConf + {{ range $setting, $value := .Values.replicaSetConfigurationSettings.configuration -}} + {{ printf "desiredRsConf[%s]='%v'" $setting $value }} + {{ end }} + + rsConfWriteAttempts=0 + rs_conf_configured_ok=unknown + + while [[ "${rs_conf_configured_ok}" != "true" ]]; do + + # give the rs setup a chance to succeed before attempting to read or configure + sleep ${SLEEP_PERIOD} + + counter=0 + while ! mongo ${usernameAndPassword} --eval 'rs.conf()'; do + counter=$((${counter} +1)) + logger "not yet able to read rs.conf settings from the currently running rs (after ${counter} attempts)" + sleep ${SLEEP_PERIOD} + done + counter=$((${counter} +1)) + logger "rs.conf settings have been read from the currently running rs (after ${counter} attempts)" + + # read rs.conf again and store it. settings format is '"" : ,' + currentRsConf=$(mongo ${usernameAndPassword} --eval 'rs.conf()') + + desiredEqualsactual=unknown + settingsToConfigure="" + for key in ${!desiredRsConf[@]}; do + value=${desiredRsConf[$key]} + if ! $(echo "\"${currentRsConf}"\" | grep -q -e "\"${key}\" : ${value},"); then + logger "rs conf setting: ${key} value will be set to: ${value}" + settingsToConfigure="${settingsToConfigure}cfg.settings.${key} = ${value}; " + desiredEqualsactual=false + else + logger "rs conf: ${key} is already at desired value: ${value}" + fi + done + + if [[ "${desiredEqualsactual}" != "false" ]]; then + logger "replicaSetConfigurationSettings match the settings of the currently running rs" + desiredEqualsactual=true + rs_conf_configured_ok=true + logger "Current settings match desired settings (There have been ${rsConfWriteAttempts} attempts to write to mongoDB rs configuration)" + exit + fi + + # apply the settings only if this member is currently the mongo replicaset PRIMARY + # it might take a little time before any pod is PRIMARY + isMaster=unknown + if ! mongo ${usernameAndPassword} --eval 'rs.isMaster()' | grep -q "ismaster\" : true"; then + isMaster=false + logger "This node is not yet PRIMARY - replicaSetConfigurationSettings will only be set on the member that is currently PRIMARY" + else + isMaster=true + logger "This node is PRIMARY" + fi + + if [[ "${isMaster}" == "true" ]]; then + logger "This node is currently PRIMARY - will apply rs.conf settings" + + # avoiding tricky string substitution with single quotes by making the eval string a set of vars + rsconf="cfg = rs.conf();" + rsreconf="rs.reconfig(cfg);" + rsCommand="${rsconf} ${settingsToConfigure} ${rsreconf}" + + mongo ${usernameAndPassword} --eval "${rsCommand}" + if [ $? -ne 0 ]; then + logger "Failed to apply mongodb cfg.settings configuration" + else + logger "mongodb replicaset cfg.settings configuration applied" + logger "Will check rs conf" + # don't exit just yet - the settings will be checked in the next loop + fi + rsConfWriteAttempts=$((${rsConfWriteAttempts} + 1 )) + fi + done + {{- end }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/replicaset/statefulset.yaml b/packages/shipa/charts/charts/mongodb/templates/replicaset/statefulset.yaml new file mode 100644 index 000000000..6fb98e59a --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/replicaset/statefulset.yaml @@ -0,0 +1,604 @@ +{{- if eq .Values.architecture "replicaset" }} +{{- $replicaCount := int .Values.replicaCount }} +{{- $loadBalancerIPListLength := len .Values.externalAccess.service.loadBalancerIPs }} +{{- if not (and .Values.externalAccess.enabled (not .Values.externalAccess.autoDiscovery.enabled) (not (eq $replicaCount $loadBalancerIPListLength )) (eq .Values.externalAccess.service.type "LoadBalancer")) }} +apiVersion: {{ include "common.capabilities.statefulset.apiVersion" . }} +kind: StatefulSet +metadata: + name: {{ include "mongodb.fullname" . }} + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: mongodb + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.labels }} + {{- include "common.tplvalues.render" (dict "value" .Values.labels "context" $) | nindent 4 }} + {{- end }} + {{- if or .Values.annotations .Values.commonAnnotations }} + annotations: + {{- if .Values.annotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.annotations "context" $) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} + {{- end }} +spec: + serviceName: {{ include "mongodb.service.nameOverride" . }} + podManagementPolicy: {{ .Values.podManagementPolicy }} + replicas: {{ .Values.replicaCount }} + updateStrategy: + type: {{ .Values.strategyType }} + {{- if (eq "OnDelete" .Values.strategyType) }} + rollingUpdate: null + {{- end }} + selector: + matchLabels: {{- include "common.labels.matchLabels" . | nindent 6 }} + app.kubernetes.io/component: mongodb + template: + metadata: + labels: {{- include "common.labels.standard" . | nindent 8 }} + app.kubernetes.io/component: mongodb + {{- if .Values.podLabels }} + {{- include "common.tplvalues.render" (dict "value" .Values.podLabels "context" $) | nindent 8 }} + {{- end }} + {{- if or (include "mongodb.createConfigmap" .) .Values.podAnnotations }} + annotations: + {{- if (include "mongodb.createConfigmap" .) }} + checksum/configuration: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }} + {{- end }} + {{- if .Values.podAnnotations }} + {{- include "common.tplvalues.render" (dict "value" .Values.podAnnotations "context" $) | nindent 8 }} + {{- end }} + {{- end }} + spec: + {{- include "mongodb.imagePullSecrets" . | nindent 6 }} + {{- if .Values.schedulerName }} + schedulerName: "{{ .Values.schedulerName }}" + {{- end }} + serviceAccountName: {{ template "mongodb.serviceAccountName" . }} + {{- if .Values.hostAliases }} + hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.hostAliases "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.affinity }} + affinity: {{- include "common.tplvalues.render" (dict "value" .Values.affinity "context" $) | nindent 8 }} + {{- else }} + affinity: + podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.podAffinityPreset "component" "mongodb" "context" $) | nindent 10 }} + podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.podAntiAffinityPreset "component" "mongodb" "context" $) | nindent 10 }} + nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.nodeAffinityPreset.type "key" .Values.nodeAffinityPreset.key "values" .Values.nodeAffinityPreset.values) | nindent 10 }} + {{- end }} + {{- if .Values.nodeSelector }} + nodeSelector: {{- include "common.tplvalues.render" (dict "value" .Values.nodeSelector "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.tolerations }} + tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.tolerations "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.topologySpreadConstraints }} + topologySpreadConstraints: {{- include "common.tplvalues.render" (dict "value" .Values.topologySpreadConstraints "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.priorityClassName }} + priorityClassName: {{ .Values.priorityClassName }} + {{- end }} + {{- if .Values.runtimeClassName }} + runtimeClassName: {{ .Values.runtimeClassName }} + {{- end }} + {{- if .Values.podSecurityContext.enabled }} + securityContext: {{- omit .Values.podSecurityContext "enabled" | toYaml | nindent 8 }} + {{- end }} + {{- if or .Values.initContainers (and .Values.volumePermissions.enabled .Values.persistence.enabled) (and .Values.externalAccess.enabled .Values.externalAccess.autoDiscovery.enabled) .Values.tls.enabled }} + initContainers: + {{- if .Values.initContainers }} + {{- include "common.tplvalues.render" (dict "value" .Values.initContainers "context" $) | nindent 8 }} + {{- end }} + {{- if and .Values.volumePermissions.enabled .Values.persistence.enabled }} + - name: volume-permissions + image: {{ include "mongodb.volumePermissions.image" . }} + imagePullPolicy: {{ .Values.volumePermissions.image.pullPolicy | quote }} + command: + - /bin/bash + - -ec + args: + - | + mkdir -p {{ .Values.persistence.mountPath }}{{- if .Values.persistence.subPath }}/{{ .Values.persistence.subPath }}{{- end }} + {{- if and .Values.podSecurityContext.enabled .Values.containerSecurityContext.enabled }} + chown -R "{{ .Values.containerSecurityContext.runAsUser }}:{{ .Values.podSecurityContext.fsGroup }}" "{{ .Values.persistence.mountPath }}{{- if .Values.persistence.subPath }}/{{ .Values.persistence.subPath }}{{- end }}" + {{- end }} + {{- if eq ( toString ( .Values.volumePermissions.securityContext.runAsUser )) "auto" }} + securityContext: {{- omit .Values.volumePermissions.securityContext "runAsUser" | toYaml | nindent 12 }} + {{- else }} + securityContext: {{- .Values.volumePermissions.securityContext | toYaml | nindent 12 }} + {{- end }} + {{- if .Values.volumePermissions.resources }} + resources: {{- toYaml .Values.volumePermissions.resources | nindent 12 }} + {{- end }} + volumeMounts: + - name: datadir + mountPath: {{ .Values.persistence.mountPath }} + {{- end }} + {{- if .Values.tls.enabled }} + - name: generate-tls-certs + image: {{ include "mongodb.tls.image" . }} + imagePullPolicy: {{ .Values.tls.image.pullPolicy | quote }} + env: + - name: MY_POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: MY_POD_HOST_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + volumeMounts: + - name: certs-volume + mountPath: /certs/CAs + - name: certs + mountPath: /certs + command: + - sh + - "-c" + - | + /bin/bash <<'EOF' + my_hostname=$(hostname) + svc={{ include "mongodb.service.nameOverride" . }} + cp /certs/CAs/* /certs/ + cat >/certs/openssl.cnf < /certs/mongodb.pem + cd /certs/ + shopt -s extglob + rm -rf !(mongodb-ca-cert|mongodb.pem|CAs|openssl.cnf) + chmod 0600 mongodb-ca-cert mongodb.pem + EOF + {{- end }} + {{- if and .Values.externalAccess.enabled .Values.externalAccess.autoDiscovery.enabled (eq .Values.externalAccess.service.type "LoadBalancer") }} + - name: auto-discovery + image: {{ include "mongodb.externalAccess.autoDiscovery.image" . }} + imagePullPolicy: {{ .Values.externalAccess.autoDiscovery.image.pullPolicy | quote }} + command: + - /scripts/auto-discovery.sh + env: + - name: MY_POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: SHARED_FILE + value: "/shared/info.txt" + {{- if .Values.externalAccess.autoDiscovery.resources }} + resources: {{- toYaml .Values.externalAccess.autoDiscovery.resources | nindent 12 }} + {{- end }} + volumeMounts: + - name: shared + mountPath: /shared + - name: scripts + mountPath: /scripts/auto-discovery.sh + subPath: auto-discovery.sh + {{- end }} + {{- end }} + containers: + - name: mongodb + image: {{ include "mongodb.image" . }} + imagePullPolicy: {{ .Values.image.pullPolicy | quote }} + {{- if .Values.containerSecurityContext.enabled }} + securityContext: {{- omit .Values.containerSecurityContext "enabled" | toYaml | nindent 12 }} + {{- end }} + {{- if .Values.diagnosticMode.enabled }} + command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }} + {{- else if .Values.command }} + command: {{- include "common.tplvalues.render" (dict "value" .Values.command "context" $) | nindent 12 }} + {{- else }} + command: + - /scripts/setup.sh + {{- end }} + {{- if .Values.diagnosticMode.enabled }} + args: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.args "context" $) | nindent 12 }} + {{- else if .Values.args }} + args: {{- include "common.tplvalues.render" (dict "value" .Values.args "context" $) | nindent 12 }} + {{- end }} + env: + - name: BITNAMI_DEBUG + value: {{ ternary "true" "false" (or .Values.image.debug .Values.diagnosticMode.enabled) | quote }} + {{- if and .Values.externalAccess.enabled .Values.externalAccess.autoDiscovery.enabled (eq .Values.externalAccess.service.type "LoadBalancer") }} + - name: SHARED_FILE + value: "/shared/info.txt" + {{- end }} + - name: MY_POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: MY_POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: MY_POD_HOST_IP + valueFrom: + fieldRef: + fieldPath: status.hostIP + - name: K8S_SERVICE_NAME + value: "{{ include "mongodb.service.nameOverride" . }}" + - name: MONGODB_INITIAL_PRIMARY_HOST + value: "{{ include "mongodb.fullname" . }}-0.$(K8S_SERVICE_NAME).$(MY_POD_NAMESPACE).svc.{{ .Values.clusterDomain }}" + - name: MONGODB_REPLICA_SET_NAME + value: {{ .Values.replicaSetName | quote }} + {{- if and .Values.replicaSetHostnames (not .Values.externalAccess.enabled) }} + - name: MONGODB_ADVERTISED_HOSTNAME + value: "$(MY_POD_NAME).$(K8S_SERVICE_NAME).$(MY_POD_NAMESPACE).svc.{{ .Values.clusterDomain }}" + {{- end }} + {{- $customUsers := include "mongodb.customUsers" . -}} + {{- $customDatabases := include "mongodb.customDatabases" . -}} + {{- if not (empty $customUsers) }} + - name: MONGODB_EXTRA_USERNAMES + value: {{ $customUsers | quote }} + {{- end }} + {{- if not (empty $customDatabases) }} + - name: MONGODB_EXTRA_DATABASES + value: {{ $customDatabases | quote }} + {{- end }} + {{- if .Values.auth.enabled }} + {{- if and (not (empty $customUsers)) (not (empty $customDatabases)) }} + - name: MONGODB_EXTRA_PASSWORDS + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-passwords + {{- end }} + - name: MONGODB_ROOT_USER + value: {{ .Values.auth.rootUser | quote }} + - name: MONGODB_ROOT_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-root-password + - name: MONGODB_REPLICA_SET_KEY + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-replica-set-key + {{- end }} + {{- if and .Values.metrics.enabled (not (empty .Values.metrics.username)) }} + - name: MONGODB_METRICS_USERNAME + value: {{ .Values.metrics.username | quote }} + {{- if .Values.auth.enabled }} + - name: MONGODB_METRICS_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-metrics-password + {{- end }} + {{- end }} + - name: ALLOW_EMPTY_PASSWORD + value: {{ ternary "no" "yes" .Values.auth.enabled | quote }} + - name: MONGODB_SYSTEM_LOG_VERBOSITY + value: {{ .Values.systemLogVerbosity | quote }} + - name: MONGODB_DISABLE_SYSTEM_LOG + value: {{ ternary "yes" "no" .Values.disableSystemLog | quote }} + - name: MONGODB_DISABLE_JAVASCRIPT + value: {{ ternary "yes" "no" .Values.disableJavascript | quote }} + - name: MONGODB_ENABLE_JOURNAL + value: {{ ternary "yes" "no" .Values.enableJournal | quote }} + - name: MONGODB_ENABLE_IPV6 + value: {{ ternary "yes" "no" .Values.enableIPv6 | quote }} + - name: MONGODB_ENABLE_DIRECTORY_PER_DB + value: {{ ternary "yes" "no" .Values.directoryPerDB | quote }} + {{- $extraFlags := .Values.extraFlags | join " " -}} + {{- if .Values.tls.enabled }} + {{- $extraFlags = printf "--tlsMode=%s --tlsCertificateKeyFile=/certs/mongodb.pem --tlsCAFile=/certs/mongodb-ca-cert %s" .Values.tls.mode $extraFlags }} + {{- end }} + {{- if ne $extraFlags "" }} + - name: MONGODB_EXTRA_FLAGS + value: {{ $extraFlags | quote }} + {{- end }} + {{- if .Values.tls.enabled }} + - name: MONGODB_CLIENT_EXTRA_FLAGS + value: --tls --tlsCertificateKeyFile=/certs/mongodb.pem --tlsCAFile=/certs/mongodb-ca-cert + {{- end }} + {{- if .Values.extraEnvVars }} + {{- include "common.tplvalues.render" (dict "value" .Values.extraEnvVars "context" $) | nindent 12 }} + {{- end }} + {{- if or .Values.extraEnvVarsCM .Values.extraEnvVarsSecret }} + envFrom: + {{- if .Values.extraEnvVarsCM }} + - configMapRef: + name: {{ tpl .Values.extraEnvVarsCM . | quote }} + {{- end }} + {{- if .Values.extraEnvVarsSecret }} + - secretRef: + name: {{ tpl .Values.extraEnvVarsSecret . | quote }} + {{- end }} + {{- end }} + ports: + - containerPort: 27017 + name: mongodb + {{- if not .Values.diagnosticMode.enabled }} + {{- if .Values.livenessProbe.enabled }} + livenessProbe: + exec: + command: + - mongo + - --disableImplicitSessions + {{- if .Values.tls.enabled }} + - --tls + - --tlsCertificateKeyFile=/certs/mongodb.pem + - --tlsCAFile=/certs/mongodb-ca-cert + {{- end }} + - --eval + - "db.adminCommand('ping')" + initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.livenessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.livenessProbe.timeoutSeconds }} + successThreshold: {{ .Values.livenessProbe.successThreshold }} + failureThreshold: {{ .Values.livenessProbe.failureThreshold }} + {{- else if .Values.customLivenessProbe }} + livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customLivenessProbe "context" $) | nindent 12 }} + {{- end }} + {{- if .Values.readinessProbe.enabled }} + readinessProbe: + exec: + command: + - bash + - -ec + - | + {{- if .Values.tls.enabled }} + TLS_OPTIONS='--tls --tlsCertificateKeyFile=/certs/mongodb.pem --tlsCAFile=/certs/mongodb-ca-cert' + {{- end }} + # Run the proper check depending on the version + [[ $(mongo --version | grep "MongoDB shell") =~ ([0-9]+\.[0-9]+\.[0-9]+) ]] && VERSION=${BASH_REMATCH[1]} + . /opt/bitnami/scripts/libversion.sh + VERSION_MAJOR="$(get_sematic_version "$VERSION" 1)" + VERSION_MINOR="$(get_sematic_version "$VERSION" 2)" + VERSION_PATCH="$(get_sematic_version "$VERSION" 3)" + if [[ "$VERSION_MAJOR" -ge 4 ]] && [[ "$VERSION_MINOR" -ge 4 ]] && [[ "$VERSION_PATCH" -ge 2 ]]; then + mongo --disableImplicitSessions $TLS_OPTIONS --eval 'db.hello().isWritablePrimary || db.hello().secondary' | grep -q 'true' + else + mongo --disableImplicitSessions $TLS_OPTIONS --eval 'db.isMaster().ismaster || db.isMaster().secondary' | grep -q 'true' + fi + initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.readinessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.readinessProbe.timeoutSeconds }} + successThreshold: {{ .Values.readinessProbe.successThreshold }} + failureThreshold: {{ .Values.readinessProbe.failureThreshold }} + {{- else if .Values.customReadinessProbe }} + readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customReadinessProbe "context" $) | nindent 12 }} + {{- end }} + {{- if .Values.startupProbe.enabled }} + startupProbe: + exec: + command: + - bash + - -ec + - | + {{- if .Values.tls.enabled }} + TLS_OPTIONS='--tls --tlsCertificateKeyFile=/certs/mongodb.pem --tlsCAFile=/certs/mongodb-ca-cert' + {{- end }} + mongo --disableImplicitSessions $TLS_OPTIONS --eval 'db.hello().isWritablePrimary || db.hello().secondary' | grep -q 'true' + initialDelaySeconds: {{ .Values.startupProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.startupProbe.periodSeconds }} + timeoutSeconds: {{ .Values.startupProbe.timeoutSeconds }} + successThreshold: {{ .Values.startupProbe.successThreshold }} + failureThreshold: {{ .Values.startupProbe.failureThreshold }} + {{- else if .Values.customStartupProbe }} + startupProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customStartupProbe "context" $) | nindent 12 }} + {{- end }} + {{- end }} + {{- if .Values.resources }} + resources: {{- toYaml .Values.resources | nindent 12 }} + {{- end }} + volumeMounts: + - name: datadir + mountPath: {{ .Values.persistence.mountPath }} + subPath: {{ .Values.persistence.subPath }} + {{- if or .Values.initdbScriptsConfigMap .Values.initdbScripts }} + - name: custom-init-scripts + mountPath: /docker-entrypoint-initdb.d + {{- end }} + {{- if or .Values.configuration .Values.existingConfigmap }} + - name: config + mountPath: /opt/bitnami/mongodb/conf/mongodb.conf + subPath: mongodb.conf + {{- end }} + - name: scripts + mountPath: /scripts/setup.sh + subPath: setup.sh + {{ if .Values.replicaSetConfigurationSettings.enabled }} + - name: scripts + mountPath: /scripts/replicaSetConfigurationSettings.sh + subPath: replicaSetConfigurationSettings.sh + {{- end }} + {{- if and .Values.externalAccess.enabled .Values.externalAccess.autoDiscovery.enabled (eq .Values.externalAccess.service.type "LoadBalancer") }} + - name: shared + mountPath: /shared + {{- end }} + {{- if .Values.tls.enabled }} + - name: certs + mountPath: /certs + {{- end }} + {{- if .Values.extraVolumeMounts }} + {{- toYaml .Values.extraVolumeMounts | nindent 12 }} + {{- end }} + {{- if .Values.metrics.enabled }} + - name: metrics + image: {{ template "mongodb.metrics.image" . }} + imagePullPolicy: {{ .Values.metrics.image.pullPolicy | quote }} + {{- if .Values.containerSecurityContext.enabled }} + securityContext: {{- omit .Values.containerSecurityContext "enabled" | toYaml | nindent 12 }} + {{- end }} + {{- if .Values.diagnosticMode.enabled }} + command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }} + {{- else }} + command: + - /bin/bash + - -ec + {{- end }} + {{- if .Values.diagnosticMode.enabled }} + args: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.args "context" $) | nindent 12 }} + {{- else }} + args: + - | + /bin/mongodb_exporter --web.listen-address ":{{ .Values.metrics.containerPort }}" --mongodb.uri "{{ include "mongodb.mongodb_exporter.uri" . }}" {{ .Values.metrics.extraFlags }} + {{- end }} + env: + {{- if .Values.auth.enabled }} + {{- if not .Values.metrics.username }} + - name: MONGODB_ROOT_USER + value: {{ .Values.auth.rootUser | quote }} + - name: MONGODB_ROOT_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-root-password + {{- else }} + - name: MONGODB_METRICS_USERNAME + value: {{ .Values.metrics.username | quote }} + - name: MONGODB_METRICS_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-metrics-password + {{- end }} + {{- end }} + volumeMounts: + {{- if .Values.tls.enabled }} + - name: certs + mountPath: /certs + {{- end }} + ports: + - name: metrics + containerPort: {{ .Values.metrics.containerPort }} + {{- if not .Values.diagnosticMode.enabled }} + {{- if .Values.metrics.livenessProbe.enabled }} + livenessProbe: + httpGet: + path: / + port: metrics + initialDelaySeconds: {{ .Values.metrics.livenessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.metrics.livenessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.metrics.livenessProbe.timeoutSeconds }} + failureThreshold: {{ .Values.metrics.livenessProbe.failureThreshold }} + successThreshold: {{ .Values.metrics.livenessProbe.successThreshold }} + {{- end }} + {{- if .Values.metrics.readinessProbe.enabled }} + readinessProbe: + httpGet: + path: / + port: metrics + initialDelaySeconds: {{ .Values.metrics.readinessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.metrics.readinessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.metrics.readinessProbe.timeoutSeconds }} + failureThreshold: {{ .Values.metrics.readinessProbe.failureThreshold }} + successThreshold: {{ .Values.metrics.readinessProbe.successThreshold }} + {{- end }} + {{- end }} + {{- if .Values.metrics.resources }} + resources: {{- toYaml .Values.metrics.resources | nindent 12 }} + {{- end }} + {{- end }} + {{- if .Values.sidecars }} + {{- include "common.tplvalues.render" (dict "value" .Values.sidecars "context" $) | nindent 8 }} + {{- end }} + volumes: + {{- if or .Values.initdbScriptsConfigMap .Values.initdbScripts }} + - name: custom-init-scripts + configMap: + name: {{ template "mongodb.initdbScriptsCM" . }} + {{- end }} + {{- if or .Values.configuration .Values.existingConfigmap }} + - name: config + configMap: + name: {{ include "mongodb.configmapName" . }} + {{- end }} + {{- if and .Values.externalAccess.enabled .Values.externalAccess.autoDiscovery.enabled (eq .Values.externalAccess.service.type "LoadBalancer") }} + - name: shared + emptyDir: {} + {{- end }} + - name: scripts + configMap: + name: {{ include "mongodb.fullname" . }}-scripts + defaultMode: 0755 + {{- if .Values.extraVolumes }} + {{- toYaml .Values.extraVolumes | nindent 8 }} + {{- end }} + {{- if .Values.tls.enabled }} + - name: certs + emptyDir: {} + - name: certs-volume + secret: + secretName: {{ template "mongodb.tlsSecretName" . }} + items: + - key: mongodb-ca-cert + path: mongodb-ca-cert + mode: 0600 + - key: mongodb-ca-key + path: mongodb-ca-key + mode: 0600 + {{- end }} + {{- if not .Values.persistence.enabled }} + - name: datadir + {{- if .Values.persistence.medium }} + emptyDir: + medium: {{ .Values.persistence.medium | quote }} + {{- else }} + emptyDir: {} + {{- end }} + {{- else }} + volumeClaimTemplates: + - metadata: + name: datadir + {{- if .Values.persistence.annotations }} + annotations: {{- include "common.tplvalues.render" (dict "value" .Values.persistence.annotations "context" $) | nindent 10 }} + {{- end }} + spec: + accessModes: + {{- range .Values.persistence.accessModes }} + - {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.persistence.size | quote }} + {{- if .Values.persistence.volumeClaimTemplates.requests }} + {{- include "common.tplvalues.render" (dict "value" .Values.persistence.volumeClaimTemplates.requests "context" $) | nindent 12 }} + {{- end }} + {{- if .Values.persistence.volumeClaimTemplates.dataSource }} + dataSource: {{- include "common.tplvalues.render" (dict "value" .Values.persistence.volumeClaimTemplates.dataSource "context" $) | nindent 10 }} + {{- end }} + {{- if .Values.persistence.volumeClaimTemplates.selector }} + selector: {{- include "common.tplvalues.render" (dict "value" .Values.persistence.volumeClaimTemplates.selector "context" $) | nindent 10 }} + {{- end }} + {{ include "common.storage.class" (dict "persistence" .Values.persistence "global" .Values.global) }} + {{- end }} +{{- end }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/replicaset/svc.yaml b/packages/shipa/charts/charts/mongodb/templates/replicaset/svc.yaml new file mode 100644 index 000000000..7b357e9b2 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/replicaset/svc.yaml @@ -0,0 +1,35 @@ +{{- if and (eq .Values.architecture "replicaset") .Values.externalAccess.enabled (eq .Values.externalAccess.service.type "ClusterIP") }} + +{{- $fullName := include "mongodb.fullname" . }} +{{- $replicaCount := .Values.replicaCount | int }} +{{- $root := . }} + +{{- range $i, $e := until $replicaCount }} +{{- $targetPod := printf "%s-%d" (printf "%s" $fullName) $i }} +{{- $_ := set $ "targetPod" $targetPod }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ $fullName }}-{{ $i }} + namespace: {{ include "mongodb.namespace" $ }} + labels: {{- include "common.labels.standard" $ | nindent 4 }} + app.kubernetes.io/component: mongodb + {{- if $root.Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" $root.Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if $root.Values.service.annotations }} + annotations: {{- include "common.tplvalues.render" (dict "value" $root.Values.service.annotations "context" $) | nindent 4 }} + {{- end }} +spec: + type: ClusterIP + ports: + - name: {{ $root.Values.service.portName }} + port: {{ $root.Values.service.port }} + targetPort: mongodb + selector: {{- include "common.labels.matchLabels" $ | nindent 4 }} + app.kubernetes.io/component: mongodb + statefulset.kubernetes.io/pod-name: {{ $targetPod }} +--- +{{- end }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/role.yaml b/packages/shipa/charts/charts/mongodb/templates/role.yaml new file mode 100644 index 000000000..950654b06 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/role.yaml @@ -0,0 +1,30 @@ +{{- if .Values.rbac.create }} +apiVersion: {{ include "common.capabilities.rbac.apiVersion" . }} +kind: Role +metadata: + name: {{ include "mongodb.fullname" . }} + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} +rules: + - apiGroups: + - "" + resources: + - services + verbs: + - get + - list + - watch +{{- if .Values.rbac.role.rules }} +{{- toYaml .Values.rbac.role.rules | nindent 2 }} +{{- end -}} +{{- $pspAvailable := (semverCompare "<1.25-0" (include "common.capabilities.kubeVersion" .)) -}} +{{- if and $pspAvailable .Values.podSecurityPolicy.create }} + - apiGroups: ['{{ template "podSecurityPolicy.apiGroup" . }}'] + resources: ['podsecuritypolicies'] + verbs: ['use'] + resourceNames: [{{ include "mongodb.fullname" . }}] +{{- end -}} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/rolebinding.yaml b/packages/shipa/charts/charts/mongodb/templates/rolebinding.yaml new file mode 100644 index 000000000..714058ff8 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/rolebinding.yaml @@ -0,0 +1,19 @@ +{{- if and .Values.serviceAccount.create .Values.rbac.create }} +apiVersion: {{ include "common.capabilities.rbac.apiVersion" . }} +kind: RoleBinding +metadata: + name: {{ include "mongodb.fullname" . }} + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} +roleRef: + kind: Role + name: {{ include "mongodb.fullname" . }} + apiGroup: rbac.authorization.k8s.io +subjects: + - kind: ServiceAccount + name: {{ include "mongodb.serviceAccountName" . }} + namespace: {{ include "mongodb.namespace" . }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/secrets-ca.yaml b/packages/shipa/charts/charts/mongodb/templates/secrets-ca.yaml new file mode 100644 index 000000000..bf0815828 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/secrets-ca.yaml @@ -0,0 +1,37 @@ +{{- if (include "mongodb.createTlsSecret" .) }} +{{- $fullname := include "mongodb.fullname" . }} +{{- $releaseNamespace := .Release.Namespace }} +{{- $clusterDomain := .Values.clusterDomain }} +{{- $cn := printf "%s.%s.svc.%s" $fullname .Release.Namespace $clusterDomain }} +apiVersion: v1 +kind: Secret +metadata: + name: {{ template "mongodb.tlsSecretName" . }} + namespace: {{ template "mongodb.namespace" . }} + labels: + {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: mongodb + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} +type: Opaque +data: + {{- if or .Values.tls.caCert .Values.tls.caKey (not .Values.tls.autoGenerated) }} + {{- $ca := buildCustomCert (required "A valid .Values.tls.caCert is required!" .Values.tls.caCert) (required "A valid .Values.tls.caKey is required!" .Values.tls.caKey) }} + {{- $cert := genSignedCert $cn nil nil 3650 $ca }} + {{- $pem := printf "%s%s" $cert.Cert $cert.Key }} + mongodb-ca-cert: {{ b64enc $ca.Cert }} + mongodb-ca-key: {{ b64enc $ca.Key }} + client-pem: {{ b64enc $pem }} + {{- else }} + {{- $ca:= genCA "myMongo-ca" 3650 }} + {{- $cert := genSignedCert $cn nil nil 3650 $ca }} + {{- $pem := printf "%s%s" $cert.Cert $cert.Key }} + mongodb-ca-cert: {{ b64enc $ca.Cert }} + mongodb-ca-key: {{ b64enc $ca.Key }} + client-pem: {{ b64enc $pem }} + {{- end }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/secrets.yaml b/packages/shipa/charts/charts/mongodb/templates/secrets.yaml new file mode 100644 index 000000000..b2c160271 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/secrets.yaml @@ -0,0 +1,51 @@ +{{- if (include "mongodb.createSecret" .) }} +apiVersion: v1 +kind: Secret +metadata: + name: {{ include "mongodb.fullname" . }} + namespace: {{ template "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: mongodb + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} +type: Opaque +data: + {{- if .Values.auth.rootPassword }} + mongodb-root-password: {{ .Values.auth.rootPassword | toString | b64enc | quote }} + {{- else }} + mongodb-root-password: {{ randAlphaNum 10 | b64enc | quote }} + {{- end }} + {{- $customUsers := include "mongodb.customUsers" . -}} + {{- $customDatabases := include "mongodb.customDatabases" . -}} + {{- $customPasswords := include "mongodb.customPasswords" . -}} + {{- if and (not (empty $customUsers)) (not (empty $customDatabases)) }} + {{- if not (empty $customPasswords) }} + mongodb-passwords: {{ $customPasswords | toString | b64enc | quote }} + {{- else }} + {{- $customUsersList := splitList "," $customUsers }} + {{- $customPasswordsList := list }} + {{- range $customUsersList }} + {{- $customPasswordsList = append $customPasswordsList (randAlphaNum 10) }} + {{- end }} + mongodb-passwords: {{ (join "," $customPasswordsList) | b64enc | quote }} + {{- end }} + {{- end }} + {{- if .Values.metrics.username }} + {{- if .Values.metrics.password }} + mongodb-metrics-password: {{ .Values.metrics.password | toString | b64enc | quote }} + {{- else }} + mongodb-metrics-password: {{ randAlphaNum 10 | b64enc | quote }} + {{- end }} + {{- end }} + {{- if eq .Values.architecture "replicaset" }} + {{- if .Values.auth.replicaSetKey }} + mongodb-replica-set-key: {{ .Values.auth.replicaSetKey | toString | b64enc | quote }} + {{- else }} + mongodb-replica-set-key: {{ randAlphaNum 10 | b64enc | quote }} + {{- end }} + {{- end }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/serviceaccount.yaml b/packages/shipa/charts/charts/mongodb/templates/serviceaccount.yaml new file mode 100644 index 000000000..e5b3f724d --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/serviceaccount.yaml @@ -0,0 +1,22 @@ +{{- if .Values.serviceAccount.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "mongodb.serviceAccountName" . }} + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if or .Values.serviceAccount.annotations .Values.commonAnnotations }} + annotations: + {{- if .Values.serviceAccount.annotations }} + {{ toYaml .Values.serviceAccount.annotations | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} + {{- end }} +secrets: + - name: {{ template "mongodb.fullname" . }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/servicemonitor.yaml b/packages/shipa/charts/charts/mongodb/templates/servicemonitor.yaml new file mode 100644 index 000000000..e506b3031 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/servicemonitor.yaml @@ -0,0 +1,38 @@ +{{- if and .Values.metrics.enabled .Values.metrics.serviceMonitor.enabled }} +apiVersion: monitoring.coreos.com/v1 +kind: ServiceMonitor +metadata: + name: {{ include "mongodb.fullname" . }} + namespace: {{ include "mongodb.serviceMonitor.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + {{- if .Values.metrics.serviceMonitor.additionalLabels }} + {{- include "common.tplvalues.render" (dict "value" .Values.metrics.serviceMonitor.additionalLabels "context" $) | nindent 4 }} + {{- end }} + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} +spec: + endpoints: + - port: http-metrics + {{- if .Values.metrics.serviceMonitor.interval }} + interval: {{ .Values.metrics.serviceMonitor.interval }} + {{- end }} + {{- if .Values.metrics.serviceMonitor.scrapeTimeout }} + scrapeTimeout: {{ .Values.metrics.serviceMonitor.scrapeTimeout }} + {{- end }} + {{- if .Values.metrics.serviceMonitor.relabelings }} + relabelings: {{- include "common.tplvalues.render" ( dict "value" .Values.metrics.serviceMonitor.relabelings "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.metrics.serviceMonitor.metricRelabelings }} + metricRelabelings: {{- include "common.tplvalues.render" ( dict "value" .Values.metrics.serviceMonitor.metricRelabelings "context" $) | nindent 8 }} + {{- end }} + namespaceSelector: + matchNames: + - "{{ include "mongodb.namespace" . }}" + selector: + matchLabels: {{- include "common.labels.matchLabels" . | nindent 6 }} + app.kubernetes.io/component: metrics +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/standalone/dep-sts.yaml b/packages/shipa/charts/charts/mongodb/templates/standalone/dep-sts.yaml new file mode 100644 index 000000000..6deb7cbb8 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/standalone/dep-sts.yaml @@ -0,0 +1,517 @@ +{{- if not (eq .Values.architecture "replicaset") }} +apiVersion: {{ if .Values.useStatefulSet }}{{ include "common.capabilities.statefulset.apiVersion" . }}{{- else }}{{ include "common.capabilities.deployment.apiVersion" . }}{{- end }} +kind: {{ if .Values.useStatefulSet }}StatefulSet{{- else }}Deployment{{- end }} +metadata: + name: {{ include "mongodb.fullname" . }} + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: mongodb + {{- if .Values.labels }} + {{- include "common.tplvalues.render" (dict "value" .Values.labels "context" $) | nindent 4 }} + {{- end }} + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if or .Values.annotations .Values.commonAnnotations }} + annotations: + {{- if .Values.annotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.annotations "context" $) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} + {{- end }} +spec: + replicas: 1 + {{- if .Values.useStatefulSet }} + serviceName: {{ include "mongodb.fullname" . }} + updateStrategy: + {{- else }} + strategy: + {{- end }} + {{- if .Values.useStatefulSet }} + type: {{ .Values.strategyType }} + {{- else }} + type: Recreate + {{- end -}} + {{- if or (and (not .Values.useStatefulSet) (eq "Recreate" .Values.strategyType)) (and .Values.useStatefulSet (eq "OnDelete" .Values.strategyType)) }} + rollingUpdate: null + {{- end }} + selector: + matchLabels: {{- include "common.labels.matchLabels" . | nindent 6 }} + app.kubernetes.io/component: mongodb + template: + metadata: + labels: {{- include "common.labels.standard" . | nindent 8 }} + app.kubernetes.io/component: mongodb + {{- if .Values.podLabels }} + {{- include "common.tplvalues.render" (dict "value" .Values.podLabels "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 8 }} + {{- end }} + {{- if or (include "mongodb.createConfigmap" .) .Values.podAnnotations }} + annotations: + {{- if (include "mongodb.createConfigmap" .) }} + checksum/configuration: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }} + {{- end }} + {{- if .Values.podAnnotations }} + {{- include "common.tplvalues.render" (dict "value" .Values.podAnnotations "context" $) | nindent 8 }} + {{- end }} + {{- end }} + spec: + {{- include "mongodb.imagePullSecrets" . | nindent 6 }} + {{- if .Values.schedulerName }} + schedulerName: "{{ .Values.schedulerName }}" + {{- end }} + serviceAccountName: {{ template "mongodb.serviceAccountName" . }} + {{- if .Values.affinity }} + affinity: {{- include "common.tplvalues.render" (dict "value" .Values.affinity "context" $) | nindent 8 }} + {{- else }} + affinity: + podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.podAffinityPreset "component" "mongodb" "context" $) | nindent 10 }} + podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.podAntiAffinityPreset "component" "mongodb" "context" $) | nindent 10 }} + nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.nodeAffinityPreset.type "key" .Values.nodeAffinityPreset.key "values" .Values.nodeAffinityPreset.values) | nindent 10 }} + {{- end }} + {{- if .Values.nodeSelector }} + nodeSelector: {{- include "common.tplvalues.render" (dict "value" .Values.nodeSelector "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.hostAliases }} + hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.hostAliases "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.tolerations }} + tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.tolerations "context" $) | nindent 8 }} + {{- end }} + {{- if .Values.priorityClassName }} + priorityClassName: {{ .Values.priorityClassName }} + {{- end }} + {{- if .Values.runtimeClassName }} + runtimeClassName: {{ .Values.runtimeClassName }} + {{- end }} + {{- if .Values.podSecurityContext.enabled }} + securityContext: {{- omit .Values.podSecurityContext "enabled" | toYaml | nindent 8 }} + {{- end }} + {{- if or .Values.initContainers (and .Values.volumePermissions.enabled .Values.persistence.enabled) .Values.tls.enabled }} + initContainers: + {{- if .Values.initContainers }} + {{- include "common.tplvalues.render" (dict "value" .Values.initContainers "context" $) | nindent 8 }} + {{- end }} + {{- if and .Values.volumePermissions.enabled .Values.persistence.enabled }} + - name: volume-permissions + image: {{ include "mongodb.volumePermissions.image" . }} + imagePullPolicy: {{ .Values.volumePermissions.image.pullPolicy | quote }} + command: + - /bin/bash + - -ec + args: + - | + mkdir -p {{ .Values.persistence.mountPath }}{{- if .Values.persistence.subPath }}/{{ .Values.persistence.subPath }}{{- end }} + {{- if and .Values.podSecurityContext.enabled .Values.containerSecurityContext.enabled }} + chown -R "{{ .Values.containerSecurityContext.runAsUser }}:{{ .Values.podSecurityContext.fsGroup }}" "{{ .Values.persistence.mountPath }}{{- if .Values.persistence.subPath }}/{{ .Values.persistence.subPath }}{{- end }}" + {{- end }} + {{- if eq ( toString ( .Values.volumePermissions.securityContext.runAsUser )) "auto" }} + securityContext: {{- omit .Values.volumePermissions.securityContext "runAsUser" | toYaml | nindent 12 }} + {{- else }} + securityContext: {{- .Values.volumePermissions.securityContext | toYaml | nindent 12 }} + {{- end }} + {{- if .Values.volumePermissions.resources }} + resources: {{- toYaml .Values.volumePermissions.resources | nindent 12 }} + {{- end }} + volumeMounts: + - name: datadir + mountPath: {{ .Values.persistence.mountPath }} + {{- end }} + {{- if .Values.tls.enabled }} + - name: generate-tls-certs + image: {{ include "mongodb.tls.image" . }} + imagePullPolicy: {{ .Values.tls.image.pullPolicy | quote }} + env: + - name: MY_POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + volumeMounts: + - name: certs-volume + mountPath: /certs/CAs + - name: certs + mountPath: /certs + command: + - sh + - "-c" + - | + /bin/bash <<'EOF' + my_hostname=$(hostname) + svc=$(echo -n "$my_hostname" | sed s/-[0-9]*$//)-headless + cp /certs/CAs/* /certs/ + cat >/certs/openssl.cnf < /certs/mongodb.pem + cd /certs/ + shopt -s extglob + rm -rf !(mongodb-ca-cert|mongodb.pem|CAs|openssl.cnf) + chmod 0600 mongodb-ca-cert mongodb.pem + EOF + {{- end }} + {{- end }} + containers: + - name: mongodb + image: {{ include "mongodb.image" . }} + imagePullPolicy: {{ .Values.image.pullPolicy | quote }} + {{- if .Values.containerSecurityContext.enabled }} + securityContext: {{- omit .Values.containerSecurityContext "enabled" | toYaml | nindent 12 }} + {{- end }} + {{- if .Values.diagnosticMode.enabled }} + command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }} + {{- else if .Values.command }} + command: {{- include "common.tplvalues.render" (dict "value" .Values.command "context" $) | nindent 12 }} + {{- end }} + {{- if .Values.diagnosticMode.enabled }} + args: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.args "context" $) | nindent 12 }} + {{- else if .Values.args }} + args: {{- include "common.tplvalues.render" (dict "value" .Values.args "context" $) | nindent 12 }} + {{- end }} + env: + - name: BITNAMI_DEBUG + value: {{ ternary "true" "false" (or .Values.image.debug .Values.diagnosticMode.enabled) | quote }} + {{- $customUsers := include "mongodb.customUsers" . -}} + {{- $customDatabases := include "mongodb.customDatabases" . -}} + {{- if not (empty $customUsers) }} + - name: MONGODB_EXTRA_USERNAMES + value: {{ $customUsers | quote }} + {{- end }} + {{- if not (empty $customDatabases) }} + - name: MONGODB_EXTRA_DATABASES + value: {{ $customDatabases | quote }} + {{- end }} + {{- if .Values.auth.enabled }} + {{- if and (not (empty $customUsers)) (not (empty $customDatabases)) }} + - name: MONGODB_EXTRA_PASSWORDS + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-passwords + {{- end }} + - name: MONGODB_ROOT_USER + value: {{ .Values.auth.rootUser | quote }} + - name: MONGODB_ROOT_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-root-password + {{- end }} + {{- if and .Values.metrics.enabled (not (empty .Values.metrics.username)) }} + - name: MONGODB_METRICS_USERNAME + value: {{ .Values.metrics.username | quote }} + {{- if .Values.auth.enabled }} + - name: MONGODB_METRICS_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-metrics-password + {{- end }} + {{- end }} + - name: ALLOW_EMPTY_PASSWORD + value: {{ ternary "no" "yes" .Values.auth.enabled | quote }} + - name: MONGODB_SYSTEM_LOG_VERBOSITY + value: {{ .Values.systemLogVerbosity | quote }} + - name: MONGODB_DISABLE_SYSTEM_LOG + value: {{ ternary "yes" "no" .Values.disableSystemLog | quote }} + - name: MONGODB_DISABLE_JAVASCRIPT + value: {{ ternary "yes" "no" .Values.disableJavascript | quote }} + - name: MONGODB_ENABLE_JOURNAL + value: {{ ternary "yes" "no" .Values.enableJournal | quote }} + - name: MONGODB_ENABLE_IPV6 + value: {{ ternary "yes" "no" .Values.enableIPv6 | quote }} + - name: MONGODB_ENABLE_DIRECTORY_PER_DB + value: {{ ternary "yes" "no" .Values.directoryPerDB | quote }} + {{- $extraFlags := .Values.extraFlags | join " " -}} + {{- if .Values.tls.enabled }} + {{- $extraFlags = printf "--tlsMode=%s --tlsCertificateKeyFile=/certs/mongodb.pem --tlsCAFile=/certs/mongodb-ca-cert %s" .Values.tls.mode $extraFlags }} + {{- end }} + {{- if ne $extraFlags "" }} + - name: MONGODB_EXTRA_FLAGS + value: {{ $extraFlags | quote }} + {{- end }} + {{- if .Values.tls.enabled }} + - name: MONGODB_CLIENT_EXTRA_FLAGS + value: --tls --tlsCertificateKeyFile=/certs/mongodb.pem --tlsCAFile=/certs/mongodb-ca-cert + {{- end }} + {{- if .Values.extraEnvVars }} + {{- include "common.tplvalues.render" (dict "value" .Values.extraEnvVars "context" $) | nindent 12 }} + {{- end }} + {{- if or .Values.extraEnvVarsCM .Values.extraEnvVarsSecret }} + envFrom: + {{- if .Values.extraEnvVarsCM }} + - configMapRef: + name: {{ tpl .Values.extraEnvVarsCM . | quote }} + {{- end }} + {{- if .Values.extraEnvVarsSecret }} + - secretRef: + name: {{ tpl .Values.extraEnvVarsSecret . | quote }} + {{- end }} + {{- end }} + ports: + - name: mongodb + containerPort: 27017 + {{- if not .Values.diagnosticMode.enabled }} + {{- if .Values.livenessProbe.enabled }} + livenessProbe: + exec: + command: + - mongo + - --disableImplicitSessions + {{- if .Values.tls.enabled }} + - --tls + - --tlsCertificateKeyFile=/certs/mongodb.pem + - --tlsCAFile=/certs/mongodb-ca-cert + {{- end }} + - --eval + - "db.adminCommand('ping')" + initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.livenessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.livenessProbe.timeoutSeconds }} + successThreshold: {{ .Values.livenessProbe.successThreshold }} + failureThreshold: {{ .Values.livenessProbe.failureThreshold }} + {{- else if .Values.customLivenessProbe }} + livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customLivenessProbe "context" $) | nindent 12 }} + {{- end }} + {{- end }} + {{- if not .Values.diagnosticMode.enabled }} + {{- if .Values.readinessProbe.enabled }} + readinessProbe: + exec: + command: + - bash + - -ec + - | + {{- if .Values.tls.enabled }} + TLS_OPTIONS='--tls --tlsCertificateKeyFile=/certs/mongodb.pem --tlsCAFile=/certs/mongodb-ca-cert' + {{- end }} + # Run the proper check depending on the version + [[ $(mongo --version | grep "MongoDB shell") =~ ([0-9]+\.[0-9]+\.[0-9]+) ]] && VERSION=${BASH_REMATCH[1]} + . /opt/bitnami/scripts/libversion.sh + VERSION_MAJOR="$(get_sematic_version "$VERSION" 1)" + VERSION_MINOR="$(get_sematic_version "$VERSION" 2)" + VERSION_PATCH="$(get_sematic_version "$VERSION" 3)" + if [[ "$VERSION_MAJOR" -ge 4 ]] && [[ "$VERSION_MINOR" -ge 4 ]] && [[ "$VERSION_PATCH" -ge 2 ]]; then + mongo --disableImplicitSessions $TLS_OPTIONS --eval 'db.hello().isWritablePrimary || db.hello().secondary' | grep -q 'true' + else + mongo --disableImplicitSessions $TLS_OPTIONS --eval 'db.isMaster().ismaster || db.isMaster().secondary' | grep -q 'true' + fi + initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.readinessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.readinessProbe.timeoutSeconds }} + successThreshold: {{ .Values.readinessProbe.successThreshold }} + failureThreshold: {{ .Values.readinessProbe.failureThreshold }} + {{- else if .Values.customReadinessProbe }} + readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customReadinessProbe "context" $) | nindent 12 }} + {{- end }} + {{- end }} + {{- if not .Values.diagnosticMode.enabled }} + {{- if .Values.startupProbe.enabled }} + startupProbe: + exec: + command: + - bash + - -ec + - | + {{- if .Values.tls.enabled }} + TLS_OPTIONS='--tls --tlsCertificateKeyFile=/certs/mongodb.pem --tlsCAFile=/certs/mongodb-ca-cert' + {{- end }} + mongo --disableImplicitSessions $TLS_OPTIONS --eval 'db.hello().isWritablePrimary || db.hello().secondary' | grep -q 'true' + initialDelaySeconds: {{ .Values.startupProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.startupProbe.periodSeconds }} + timeoutSeconds: {{ .Values.startupProbe.timeoutSeconds }} + successThreshold: {{ .Values.startupProbe.successThreshold }} + failureThreshold: {{ .Values.startupProbe.failureThreshold }} + {{- else if .Values.customStartupProbe }} + startupProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customStartupProbe "context" $) | nindent 12 }} + {{- end }} + {{- end }} + {{- if .Values.resources }} + resources: {{- toYaml .Values.resources | nindent 12 }} + {{- end }} + volumeMounts: + - name: datadir + mountPath: {{ .Values.persistence.mountPath }} + subPath: {{ .Values.persistence.subPath }} + {{- if or .Values.initdbScriptsConfigMap .Values.initdbScripts }} + - name: custom-init-scripts + mountPath: /docker-entrypoint-initdb.d + {{- end }} + {{- if or .Values.configuration .Values.existingConfigmap }} + - name: config + mountPath: /opt/bitnami/mongodb/conf/mongodb.conf + subPath: mongodb.conf + {{- end }} + {{- if .Values.tls.enabled }} + - name: certs + mountPath: /certs + {{- end }} + {{- if .Values.extraVolumeMounts }} + {{- toYaml .Values.extraVolumeMounts | nindent 12 }} + {{- end }} + {{- if .Values.metrics.enabled }} + - name: metrics + image: {{ template "mongodb.metrics.image" . }} + imagePullPolicy: {{ .Values.metrics.image.pullPolicy | quote }} + {{- if .Values.containerSecurityContext.enabled }} + securityContext: {{- omit .Values.containerSecurityContext "enabled" | toYaml | nindent 12 }} + {{- end }} + command: + - /bin/bash + - -ec + args: + - | + /bin/mongodb_exporter --web.listen-address ":{{ .Values.metrics.containerPort }}" --mongodb.uri "{{ include "mongodb.mongodb_exporter.uri" . }}" {{ .Values.metrics.extraFlags }} + env: + {{- if .Values.auth.enabled }} + {{- if not .Values.metrics.username }} + - name: MONGODB_ROOT_USER + value: {{ .Values.auth.rootUser | quote }} + - name: MONGODB_ROOT_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-root-password + {{- else }} + - name: MONGODB_METRICS_USERNAME + value: {{ .Values.metrics.username | quote }} + - name: MONGODB_METRICS_PASSWORD + valueFrom: + secretKeyRef: + name: {{ include "mongodb.secretName" . }} + key: mongodb-metrics-password + {{- end }} + {{- end }} + volumeMounts: + {{- if .Values.tls.enabled }} + - name: certs + mountPath: /certs + {{- end }} + ports: + - name: metrics + containerPort: {{ .Values.metrics.containerPort }} + {{- if not .Values.diagnosticMode.enabled }} + {{- if .Values.metrics.livenessProbe.enabled }} + livenessProbe: + httpGet: + path: / + port: metrics + initialDelaySeconds: {{ .Values.metrics.livenessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.metrics.livenessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.metrics.livenessProbe.timeoutSeconds }} + failureThreshold: {{ .Values.metrics.livenessProbe.failureThreshold }} + successThreshold: {{ .Values.metrics.livenessProbe.successThreshold }} + {{- end }} + {{- if .Values.metrics.readinessProbe.enabled }} + readinessProbe: + httpGet: + path: / + port: metrics + initialDelaySeconds: {{ .Values.metrics.readinessProbe.initialDelaySeconds }} + periodSeconds: {{ .Values.metrics.readinessProbe.periodSeconds }} + timeoutSeconds: {{ .Values.metrics.readinessProbe.timeoutSeconds }} + failureThreshold: {{ .Values.metrics.readinessProbe.failureThreshold }} + successThreshold: {{ .Values.metrics.readinessProbe.successThreshold }} + {{- end }} + {{- end }} + {{- if .Values.metrics.resources }} + resources: {{- toYaml .Values.metrics.resources | nindent 12 }} + {{- end }} + {{- end }} + {{- if .Values.sidecars }} + {{- include "common.tplvalues.render" (dict "value" .Values.sidecars "context" $) | nindent 8 }} + {{- end }} + volumes: + {{- if or .Values.initdbScriptsConfigMap .Values.initdbScripts }} + - name: custom-init-scripts + configMap: + name: {{ template "mongodb.initdbScriptsCM" . }} + {{- end }} + {{- if or .Values.configuration .Values.existingConfigmap }} + - name: config + configMap: + name: {{ include "mongodb.configmapName" . }} + {{- end }} + {{- if .Values.extraVolumes }} + {{- toYaml .Values.extraVolumes | nindent 8 }} + {{- end }} + {{- if .Values.tls.enabled }} + - name: certs + emptyDir: {} + - name: certs-volume + secret: + secretName: {{ template "mongodb.tlsSecretName" . }} + items: + - key: mongodb-ca-cert + path: mongodb-ca-cert + mode: 0600 + - key: mongodb-ca-key + path: mongodb-ca-key + mode: 0600 + {{- end }} + {{- if not .Values.persistence.enabled }} + - name: datadir + {{- if .Values.persistence.medium }} + emptyDir: + medium: {{ .Values.persistence.medium | quote }} + {{- else }} + emptyDir: {} + {{- end }} + {{- else if .Values.persistence.existingClaim }} + - name: datadir + persistentVolumeClaim: + claimName: {{ printf "%s" (tpl .Values.persistence.existingClaim .) }} + {{- else if not .Values.useStatefulSet }} + - name: datadir + persistentVolumeClaim: + claimName: {{ template "mongodb.fullname" . }} + {{- else }} + volumeClaimTemplates: + - metadata: + name: datadir + {{- if .Values.persistence.annotations }} + annotations: {{- include "common.tplvalues.render" (dict "value" .Values.persistence.annotations "context" $) | nindent 10 }} + {{- end }} + spec: + accessModes: + {{- range .Values.persistence.accessModes }} + - {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.persistence.size | quote }} + {{- if .Values.persistence.volumeClaimTemplates.selector }} + selector: {{- include "common.tplvalues.render" (dict "value" .Values.persistence.volumeClaimTemplates.selector "context" $) | nindent 10 }} + {{- end }} + {{ include "common.storage.class" (dict "persistence" .Values.persistence "global" .Values.global) }} + {{- end }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/standalone/pvc.yaml b/packages/shipa/charts/charts/mongodb/templates/standalone/pvc.yaml new file mode 100644 index 000000000..eb102240a --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/standalone/pvc.yaml @@ -0,0 +1,30 @@ +{{- if and .Values.persistence.enabled (not .Values.persistence.existingClaim) (not (eq .Values.architecture "replicaset")) (not .Values.useStatefulSet) }} +kind: PersistentVolumeClaim +apiVersion: v1 +metadata: + name: {{ include "mongodb.fullname" . }} + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: mongodb + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if or .Values.persistence.annotations .Values.commonAnnotations }} + annotations: + {{- if .Values.commonAnnotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} + {{- if .Values.persistence.annotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.persistence.annotations "context" $) | nindent 4 }} + {{- end }} + {{- end }} +spec: + accessModes: + {{- range .Values.persistence.accessModes }} + - {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.persistence.size | quote }} + {{ include "common.storage.class" (dict "persistence" .Values.persistence "global" .Values.global) }} +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/templates/standalone/svc.yaml b/packages/shipa/charts/charts/mongodb/templates/standalone/svc.yaml new file mode 100644 index 000000000..d32826d22 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/templates/standalone/svc.yaml @@ -0,0 +1,46 @@ +{{- if not (eq .Values.architecture "replicaset") }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "mongodb.fullname" . }} + namespace: {{ include "mongodb.namespace" . }} + labels: {{- include "common.labels.standard" . | nindent 4 }} + app.kubernetes.io/component: mongodb + {{- if .Values.commonLabels }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }} + {{- end }} + {{- if or .Values.service.annotations .Values.commonAnnotations }} + annotations: + {{- if .Values.service.annotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.service.annotations "context" $) | nindent 4 }} + {{- end }} + {{- if .Values.commonAnnotations }} + {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} + {{- end }} + {{- end }} +spec: + type: {{ .Values.service.type }} + {{- if and (eq .Values.service.type "ClusterIP") .Values.service.clusterIP }} + clusterIP: {{ .Values.service.clusterIP }} + {{- end }} + {{- if and (eq .Values.service.type "LoadBalancer") .Values.service.loadBalancerIP }} + loadBalancerIP: {{ .Values.service.loadBalancerIP }} + {{- end }} + {{- if .Values.service.externalIPs }} + externalIPs: {{ toYaml .Values.service.externalIPs | nindent 4 }} + {{- end }} + {{- if .Values.service.loadBalancerSourceRanges }} + loadBalancerSourceRanges: {{- toYaml .Values.service.loadBalancerSourceRanges | nindent 4 }} + {{- end }} + ports: + - name: {{ .Values.service.portName }} + port: {{ .Values.service.port }} + targetPort: mongodb + {{- if and (or (eq .Values.service.type "LoadBalancer") (eq .Values.service.type "NodePort")) .Values.service.nodePort }} + nodePort: {{ .Values.service.nodePort }} + {{- else if eq .Values.service.type "ClusterIP" }} + nodePort: null + {{- end }} + selector: {{- include "common.labels.matchLabels" . | nindent 4 }} + app.kubernetes.io/component: mongodb +{{- end }} diff --git a/packages/shipa/charts/charts/mongodb/values.schema.json b/packages/shipa/charts/charts/mongodb/values.schema.json new file mode 100644 index 000000000..be8e54b45 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/values.schema.json @@ -0,0 +1,173 @@ +{ + "$schema": "http://json-schema.org/schema#", + "type": "object", + "properties": { + "architecture": { + "type": "string", + "title": "MongoDB® architecture", + "form": true, + "description": "Allowed values: `standalone` or `replicaset`" + }, + "auth": { + "type": "object", + "title": "Authentication configuration", + "form": true, + "properties": { + "enabled": { + "type": "boolean", + "title": "Enable Authentication", + "form": true + }, + "rootUser": { + "type": "string", + "title": "MongoDB® admin user", + "form": true, + "description": "Name of the admin user. Default is root" + }, + "rootPassword": { + "type": "string", + "title": "MongoDB® admin password", + "form": true, + "description": "Defaults to a random 10-character alphanumeric string if not set", + "hidden": { + "value": false, + "path": "auth/enabled" + } + }, + "database": { + "type": "string", + "title": "MongoDB® custom database", + "description": "Name of the custom database to be created during the 1st initialization of MongoDB®", + "form": true + }, + "username": { + "type": "string", + "title": "MongoDB® custom user", + "description": "Name of the custom user to be created during the 1st initialization of MongoDB®. This user only has permissions on the MongoDB® custom database", + "form": true + }, + "password": { + "type": "string", + "title": "Password for MongoDB® custom user", + "form": true, + "description": "Defaults to a random 10-character alphanumeric string if not set", + "hidden": { + "value": false, + "path": "auth/enabled" + } + }, + "replicaSetKey": { + "type": "string", + "title": "Key used for replica set authentication", + "form": true, + "description": "Defaults to a random 10-character alphanumeric string if not set", + "hidden": { + "value": "standalone", + "path": "architecture" + } + } + } + }, + "replicaCount": { + "type": "integer", + "form": true, + "title": "Number of MongoDB® replicas", + "hidden": { + "value": "standalone", + "path": "architecture" + } + }, + "configuration": { + "type": "string", + "title": "MongoDB® Custom Configuration", + "form": true, + "render": "textArea" + }, + "arbiter": { + "type": "object", + "title": "Arbiter configuration", + "form": true, + "properties": { + "configuration": { + "type": "string", + "title": "Arbiter Custom Configuration", + "form": true, + "render": "textArea", + "hidden": { + "value": "standalone", + "path": "architecture" + } + } + } + }, + "persistence": { + "type": "object", + "title": "Persistence configuration", + "form": true, + "properties": { + "enabled": { + "type": "boolean", + "form": true, + "title": "Enable persistence", + "description": "Enable persistence using Persistent Volume Claims" + }, + "size": { + "type": "string", + "title": "Persistent Volume Size", + "form": true, + "render": "slider", + "sliderMin": 1, + "sliderMax": 100, + "sliderUnit": "Gi", + "hidden": { + "value": false, + "path": "persistence/enabled" + } + } + } + }, + "volumePermissions": { + "type": "object", + "hidden": { + "value": false, + "path": "persistence/enabled" + }, + "properties": { + "enabled": { + "type": "boolean", + "form": true, + "title": "Enable Init Containers", + "description": "Use an init container to set required folder permissions on the data volume before mounting it in the final destination" + } + } + }, + "metrics": { + "type": "object", + "form": true, + "title": "Prometheus metrics details", + "properties": { + "enabled": { + "type": "boolean", + "title": "Create Prometheus metrics exporter", + "description": "Create a side-car container to expose Prometheus metrics", + "form": true + }, + "serviceMonitor": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "title": "Create Prometheus Operator ServiceMonitor", + "description": "Create a ServiceMonitor to track metrics using Prometheus Operator", + "form": true, + "hidden": { + "value": false, + "path": "metrics/enabled" + } + } + } + } + } + } + } +} diff --git a/packages/shipa/charts/charts/mongodb/values.yaml b/packages/shipa/charts/charts/mongodb/values.yaml new file mode 100644 index 000000000..466a62588 --- /dev/null +++ b/packages/shipa/charts/charts/mongodb/values.yaml @@ -0,0 +1,1702 @@ +## @section Global parameters +## Global Docker image parameters +## Please, note that this will override the image parameters, including dependencies, configured to use the global value +## Current available global Docker image parameters: imageRegistry, imagePullSecrets and storageClass +## + +## @param global.imageRegistry Global Docker image registry +## @param global.imagePullSecrets Global Docker registry secret names as an array +## @param global.storageClass Global StorageClass for Persistent Volume(s) +## @param global.namespaceOverride Override the namespace for resource deployed by the chart, but can itself be overridden by the local namespaceOverride +## +global: + imageRegistry: "" + ## E.g. + ## imagePullSecrets: + ## - myRegistryKeySecretName + ## + imagePullSecrets: [] + storageClass: "" + namespaceOverride: "" + +## @section Common parameters +## + +## @param nameOverride String to partially override mongodb.fullname template (will maintain the release name) +## +nameOverride: "" +## @param fullnameOverride String to fully override mongodb.fullname template +## +fullnameOverride: "" +## @param clusterDomain Default Kubernetes cluster domain +## +clusterDomain: cluster.local +## @param extraDeploy Array of extra objects to deploy with the release +## extraDeploy: +## This needs to be uncommented and added to 'extraDeploy' in order to use the replicaset 'mongo-labeler' sidecar +## for dynamically discovering the mongodb primary pod +## suggestion is to use a hard-coded and predictable TCP port for the primary mongodb pod (here is 30001, choose your own) +## - apiVersion: v1 +## kind: Service +## metadata: +## name: mongodb-primary +## namespace: the-mongodb-namespace +## labels: +## app.kubernetes.io/component: mongodb +## app.kubernetes.io/instance: mongodb +## app.kubernetes.io/managed-by: Helm +## app.kubernetes.io/name: mongodb +## spec: +## type: NodePort +## externalTrafficPolicy: Cluster +## ports: +## - name: mongodb +## port: 30001 +## nodePort: 30001 +## protocol: TCP +## targetPort: mongodb +## selector: +## app.kubernetes.io/component: mongodb +## app.kubernetes.io/instance: mongodb +## app.kubernetes.io/name: mongodb +## primary: "true" +## +extraDeploy: [] +## @param commonLabels Add labels to all the deployed resources (sub-charts are not considered). Evaluated as a template +## +commonLabels: {} +## @param commonAnnotations Common annotations to add to all Mongo resources (sub-charts are not considered). Evaluated as a template +## +commonAnnotations: {} + +## Enable diagnostic mode in the deployment +## +diagnosticMode: + ## @param diagnosticMode.enabled Enable diagnostic mode (all probes will be disabled and the command will be overridden) + ## + enabled: false + ## @param diagnosticMode.command Command to override all containers in the deployment + ## + command: + - sleep + ## @param diagnosticMode.args Args to override all containers in the deployment + ## + args: + - infinity + +## @section MongoDB(®) parameters +## + +## Bitnami MongoDB(®) image +## ref: https://hub.docker.com/r/bitnami/mongodb/tags/ +## @param image.registry MongoDB(®) image registry +## @param image.repository MongoDB(®) image registry +## @param image.tag MongoDB(®) image tag (immutable tags are recommended) +## @param image.pullPolicy MongoDB(®) image pull policy +## @param image.pullSecrets Specify docker-registry secret names as an array +## @param image.debug Set to true if you would like to see extra information on logs +## +image: + registry: docker.io + repository: bitnami/mongodb + tag: 4.4.12-debian-10-r35 + ## Specify a imagePullPolicy + ## ref: https://kubernetes.io/docs/user-guide/images/#pre-pulling-images + ## + pullPolicy: IfNotPresent + ## Optionally specify an array of imagePullSecrets. + ## Secrets must be manually created in the namespace. + ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/ + ## e.g: + ## pullSecrets: + ## - myRegistryKeySecretName + ## + pullSecrets: [] + ## Set to true if you would like to see extra information on logs + ## + debug: false + +## @param schedulerName Name of the scheduler (other than default) to dispatch pods +## ref: https://kubernetes.io/docs/tasks/administer-cluster/configure-multiple-schedulers/ +## +schedulerName: "" +## @param architecture MongoDB(®) architecture (`standalone` or `replicaset`) +## +architecture: standalone +## @param useStatefulSet Set to true to use a StatefulSet instead of a Deployment (only when `architecture=standalone`) +## +useStatefulSet: false +## MongoDB(®) Authentication parameters +## +auth: + ## @param auth.enabled Enable authentication + ## ref: https://docs.mongodb.com/manual/tutorial/enable-authentication/ + ## + enabled: true + ## @param auth.rootUser MongoDB(®) root user + ## + rootUser: root + ## @param auth.rootPassword MongoDB(®) root password + ## ref: https://github.com/bitnami/bitnami-docker-mongodb/blob/master/README.md#setting-the-root-password-on-first-run + ## + rootPassword: "" + ## MongoDB(®) custom users and databases + ## ref: https://github.com/bitnami/bitnami-docker-mongodb/blob/master/README.md#creating-users-and-databases-on-first-run + ## @param auth.usernames List of custom users to be created during the initialization + ## @param auth.passwords List of passwords for the custom users set at `auth.usernames` + ## @param auth.databases List of custom databases to be created during the initialization + ## + usernames: [] + passwords: [] + databases: [] + ## @param auth.username DEPRECATED: use `auth.usernames` instead + ## @param auth.password DEPRECATED: use `auth.passwords` instead + ## @param auth.database DEPRECATED: use `auth.databases` instead + username: "" + password: "" + database: "" + ## @param auth.replicaSetKey Key used for authentication in the replicaset (only when `architecture=replicaset`) + ## + replicaSetKey: "" + ## @param auth.existingSecret Existing secret with MongoDB(®) credentials (keys: `mongodb-password`, `mongodb-root-password`, ` mongodb-replica-set-key`) + ## NOTE: When it's set the previous parameters are ignored. + ## + existingSecret: "" +tls: + ## @param tls.enabled Enable MongoDB(®) TLS support between nodes in the cluster as well as between mongo clients and nodes + ## + enabled: false + ## @param tls.autoGenerated Generate a custom CA and self-signed certificates + ## + autoGenerated: true + ## @param tls.existingSecret Existing secret with TLS certificates (keys: `mongodb-ca-cert`, `mongodb-ca-key`, `client-pem`) + ## NOTE: When it's set it will disable certificate creation + ## + existingSecret: "" + ## Add Custom CA certificate + ## @param tls.caCert Custom CA certificated (base64 encoded) + ## @param tls.caKey CA certificate private key (base64 encoded) + ## + caCert: "" + caKey: "" + ## Bitnami Nginx image + ## @param tls.image.registry Init container TLS certs setup image registry + ## @param tls.image.repository Init container TLS certs setup image repository + ## @param tls.image.tag Init container TLS certs setup image tag (immutable tags are recommended) + ## @param tls.image.pullPolicy Init container TLS certs setup image pull policy + ## @param tls.extraDnsNames Add extra dns names to the CA, can solve x509 auth issue for pod clients + ## + image: + registry: docker.io + repository: bitnami/nginx + tag: 1.21.6-debian-10-r30 + pullPolicy: IfNotPresent + ## e.g: + ## extraDnsNames + ## "DNS.6": "$my_host" + ## "DNS.7": "$test" + ## + extraDnsNames: [] + ## @param tls.mode Allows to set the tls mode which should be used when tls is enabled (options: `allowTLS`, `preferTLS`, `requireTLS`) + ## + mode: requireTLS +## @param hostAliases Add deployment host aliases +## https://kubernetes.io/docs/concepts/services-networking/add-entries-to-pod-etc-hosts-with-host-aliases/ +## +hostAliases: [] +## @param replicaSetName Name of the replica set (only when `architecture=replicaset`) +## Ignored when mongodb.architecture=standalone +## +replicaSetName: rs0 +## @param replicaSetHostnames Enable DNS hostnames in the replicaset config (only when `architecture=replicaset`) +## Ignored when mongodb.architecture=standalone +## Ignored when externalAccess.enabled=true +## +replicaSetHostnames: true +## @param enableIPv6 Switch to enable/disable IPv6 on MongoDB(®) +## ref: https://github.com/bitnami/bitnami-docker-mongodb/blob/master/README.md#enabling/disabling-ipv6 +## +enableIPv6: false +## @param directoryPerDB Switch to enable/disable DirectoryPerDB on MongoDB(®) +## ref: https://github.com/bitnami/bitnami-docker-mongodb/blob/master/README.md#enabling/disabling-directoryperdb +## +directoryPerDB: false +## MongoDB(®) System Log configuration +## ref: https://github.com/bitnami/bitnami-docker-mongodb#configuring-system-log-verbosity-level +## @param systemLogVerbosity MongoDB(®) system log verbosity level +## @param disableSystemLog Switch to enable/disable MongoDB(®) system log +## +systemLogVerbosity: 0 +disableSystemLog: false +## @param disableJavascript Switch to enable/disable MongoDB(®) server-side JavaScript execution +## ref: https://docs.mongodb.com/manual/core/server-side-javascript/ +## +disableJavascript: false +## @param enableJournal Switch to enable/disable MongoDB(®) Journaling +## ref: https://docs.mongodb.com/manual/reference/configuration-options/#mongodb-setting-storage.journal.enabled +## +enableJournal: true +## @param configuration MongoDB(®) configuration file to be used for Primary and Secondary nodes +## For documentation of all options, see: http://docs.mongodb.org/manual/reference/configuration-options/ +## Example: +## configuration: |- +## # where and how to store data. +## storage: +## dbPath: /bitnami/mongodb/data/db +## journal: +## enabled: true +## directoryPerDB: false +## # where to write logging data +## systemLog: +## destination: file +## quiet: false +## logAppend: true +## logRotate: reopen +## path: /opt/bitnami/mongodb/logs/mongodb.log +## verbosity: 0 +## # network interfaces +## net: +## port: 27017 +## unixDomainSocket: +## enabled: true +## pathPrefix: /opt/bitnami/mongodb/tmp +## ipv6: false +## bindIpAll: true +## # replica set options +## #replication: +## #replSetName: replicaset +## #enableMajorityReadConcern: true +## # process management options +## processManagement: +## fork: false +## pidFilePath: /opt/bitnami/mongodb/tmp/mongodb.pid +## # set parameter options +## setParameter: +## enableLocalhostAuthBypass: true +## # security options +## security: +## authorization: disabled +## #keyFile: /opt/bitnami/mongodb/conf/keyfile +## +configuration: "" +## @section replicaSetConfigurationSettings settings applied during runtime (not via configuration file) +## If enabled, these are applied by a script which is called within setup.sh +## for documentation see https://docs.mongodb.com/manual/reference/replica-configuration/#replica-set-configuration-fields +## @param replicaSetConfigurationSettings.enabled Enable MongoDB(®) Switch to enable/disable configuring MongoDB(®) run time rs.conf settings +## @param replicaSetConfigurationSettings.configuration run-time rs.conf settings +## +replicaSetConfigurationSettings: + enabled: false + configuration: {} +## chainingAllowed : false +## heartbeatTimeoutSecs : 10 +## heartbeatIntervalMillis : 2000 +## electionTimeoutMillis : 10000 +## catchUpTimeoutMillis : 30000 +## @param existingConfigmap Name of existing ConfigMap with MongoDB(®) configuration for Primary and Secondary nodes +## NOTE: When it's set the arbiter.configuration parameter is ignored +## +existingConfigmap: "" +## @param initdbScripts Dictionary of initdb scripts +## Specify dictionary of scripts to be run at first boot +## Example: +## initdbScripts: +## my_init_script.sh: | +## #!/bin/bash +## echo "Do something." +## +initdbScripts: {} +## @param initdbScriptsConfigMap Existing ConfigMap with custom initdb scripts +## +initdbScriptsConfigMap: "" +## Command and args for running the container (set to default if not set). Use array form +## @param command Override default container command (useful when using custom images) +## @param args Override default container args (useful when using custom images) +## +command: [] +args: [] +## @param extraFlags MongoDB(®) additional command line flags +## Example: +## extraFlags: +## - "--wiredTigerCacheSizeGB=2" +## +extraFlags: [] +## @param extraEnvVars Extra environment variables to add to MongoDB(®) pods +## E.g: +## extraEnvVars: +## - name: FOO +## value: BAR +## +extraEnvVars: [] +## @param extraEnvVarsCM Name of existing ConfigMap containing extra env vars +## +extraEnvVarsCM: "" +## @param extraEnvVarsSecret Name of existing Secret containing extra env vars (in case of sensitive data) +## +extraEnvVarsSecret: "" + +## @section MongoDB(®) statefulset parameters +## + +## @param annotations Additional labels to be added to the MongoDB(®) statefulset. Evaluated as a template +## +annotations: {} +## @param labels Annotations to be added to the MongoDB(®) statefulset. Evaluated as a template +## +labels: {} +## @param replicaCount Number of MongoDB(®) nodes (only when `architecture=replicaset`) +## Ignored when mongodb.architecture=standalone +## +replicaCount: 2 +## @param strategyType StrategyType for MongoDB(®) statefulset +## It can be set to RollingUpdate or Recreate by default. +## +strategyType: RollingUpdate +## @param podManagementPolicy Pod management policy for MongoDB(®) +## Should be initialized one by one when building the replicaset for the first time +## +podManagementPolicy: OrderedReady +## @param podAffinityPreset MongoDB(®) Pod affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` +## ref: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#inter-pod-affinity-and-anti-affinity +## +podAffinityPreset: "" +## @param podAntiAffinityPreset MongoDB(®) Pod anti-affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` +## ref: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#inter-pod-affinity-and-anti-affinity +## +podAntiAffinityPreset: soft +## Node affinity preset +## ref: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity +## +nodeAffinityPreset: + ## @param nodeAffinityPreset.type MongoDB(®) Node affinity preset type. Ignored if `affinity` is set. Allowed values: `soft` or `hard` + ## + type: "" + ## @param nodeAffinityPreset.key MongoDB(®) Node label key to match Ignored if `affinity` is set. + ## E.g. + ## key: "kubernetes.io/e2e-az-name" + ## + key: "" + ## @param nodeAffinityPreset.values MongoDB(®) Node label values to match. Ignored if `affinity` is set. + ## E.g. + ## values: + ## - e2e-az1 + ## - e2e-az2 + ## + values: [] +## @param affinity MongoDB(®) Affinity for pod assignment +## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity +## Note: podAffinityPreset, podAntiAffinityPreset, and nodeAffinityPreset will be ignored when it's set +## +affinity: {} +## @param nodeSelector MongoDB(®) Node labels for pod assignment +## ref: https://kubernetes.io/docs/user-guide/node-selection/ +## +nodeSelector: {} +## @param tolerations MongoDB(®) Tolerations for pod assignment +## ref: https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/ +## +tolerations: [] +## @param topologySpreadConstraints MongoDB(®) Spread Constraints for Pods +## ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-topology-spread-constraints/ +## +topologySpreadConstraints: [] +## @param podLabels MongoDB(®) pod labels +## ref: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ +## +podLabels: {} +## @param podAnnotations MongoDB(®) Pod annotations +## ref: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/ +## +podAnnotations: {} +## @param priorityClassName Name of the existing priority class to be used by MongoDB(®) pod(s) +## ref: https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/ +## +priorityClassName: "" +## @param runtimeClassName Name of the runtime class to be used by MongoDB(®) pod(s) +## ref: https://kubernetes.io/docs/concepts/containers/runtime-class/ +## +runtimeClassName: "" +## MongoDB(®) pods' Security Context. +## ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/#set-the-security-context-for-a-pod +## @param podSecurityContext.enabled Enable MongoDB(®) pod(s)' Security Context +## @param podSecurityContext.fsGroup Group ID for the volumes of the MongoDB(®) pod(s) +## @param podSecurityContext.sysctls sysctl settings of the MongoDB(®) pod(s)' +## +podSecurityContext: + enabled: true + fsGroup: 1001 + ## sysctl settings + ## Example: + ## sysctls: + ## - name: net.core.somaxconn + ## value: "10000" + ## + sysctls: [] +## MongoDB(®) containers' Security Context (main and metrics container). +## ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/#set-the-security-context-for-a-container +## @param containerSecurityContext.enabled Enable MongoDB(®) container(s)' Security Context +## @param containerSecurityContext.runAsUser User ID for the MongoDB(®) container +## @param containerSecurityContext.runAsNonRoot Set MongoDB(®) container's Security Context runAsNonRoot +## +containerSecurityContext: + enabled: true + runAsUser: 1001 + runAsNonRoot: true +## MongoDB(®) containers' resource requests and limits. +## ref: https://kubernetes.io/docs/user-guide/compute-resources/ +## We usually recommend not to specify default resources and to leave this as a conscious +## choice for the user. This also increases chances charts run on environments with little +## resources, such as Minikube. If you do want to specify resources, uncomment the following +## lines, adjust them as necessary, and remove the curly braces after 'resources:'. +## @param resources.limits The resources limits for MongoDB(®) containers +## @param resources.requests The requested resources for MongoDB(®) containers +## +resources: + ## Example: + ## limits: + ## cpu: 100m + ## memory: 128Mi + ## + limits: {} + ## Examples: + ## requests: + ## cpu: 100m + ## memory: 128Mi + ## + requests: {} +## MongoDB(®) pods' liveness probe. Evaluated as a template. +## ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes +## @param livenessProbe.enabled Enable livenessProbe +## @param livenessProbe.initialDelaySeconds Initial delay seconds for livenessProbe +## @param livenessProbe.periodSeconds Period seconds for livenessProbe +## @param livenessProbe.timeoutSeconds Timeout seconds for livenessProbe +## @param livenessProbe.failureThreshold Failure threshold for livenessProbe +## @param livenessProbe.successThreshold Success threshold for livenessProbe +## +livenessProbe: + enabled: true + initialDelaySeconds: 30 + periodSeconds: 10 + timeoutSeconds: 5 + failureThreshold: 6 + successThreshold: 1 +## MongoDB(®) pods' readiness probe. Evaluated as a template. +## ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes +## @param readinessProbe.enabled Enable readinessProbe +## @param readinessProbe.initialDelaySeconds Initial delay seconds for readinessProbe +## @param readinessProbe.periodSeconds Period seconds for readinessProbe +## @param readinessProbe.timeoutSeconds Timeout seconds for readinessProbe +## @param readinessProbe.failureThreshold Failure threshold for readinessProbe +## @param readinessProbe.successThreshold Success threshold for readinessProbe +## +readinessProbe: + enabled: true + initialDelaySeconds: 5 + periodSeconds: 10 + timeoutSeconds: 5 + failureThreshold: 6 + successThreshold: 1 +## Slow starting containers can be protected through startup probes +## Startup probes are available in Kubernetes version 1.16 and above +## ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-startup-probes +## @param startupProbe.enabled Enable startupProbe +## @param startupProbe.initialDelaySeconds Initial delay seconds for startupProbe +## @param startupProbe.periodSeconds Period seconds for startupProbe +## @param startupProbe.timeoutSeconds Timeout seconds for startupProbe +## @param startupProbe.failureThreshold Failure threshold for startupProbe +## @param startupProbe.successThreshold Success threshold for startupProbe +## +startupProbe: + enabled: false + initialDelaySeconds: 5 + periodSeconds: 10 + timeoutSeconds: 5 + successThreshold: 1 + failureThreshold: 30 +## @param customLivenessProbe Override default liveness probe for MongoDB(®) containers +## Ignored when livenessProbe.enabled=true +## +customLivenessProbe: {} +## @param customReadinessProbe Override default readiness probe for MongoDB(®) containers +## Ignored when readinessProbe.enabled=true +## +customReadinessProbe: {} +## @param customStartupProbe Override default startup probe for MongoDB(®) containers +## Ignored when startupProbe.enabled=true +## +customStartupProbe: {} +## @param initContainers Add additional init containers for the hidden node pod(s) +## Example: +## initContainers: +## - name: your-image-name +## image: your-image +## imagePullPolicy: Always +## ports: +## - name: portname +## containerPort: 1234 +## +initContainers: [] +## @param sidecars Add additional sidecar containers for the MongoDB(®) pod(s) +## Example: +## sidecars: +## - name: your-image-name +## image: your-image +## imagePullPolicy: Always +## ports: +## - name: portname +## containerPort: 1234 +## This is an optional 'mongo-labeler' sidecar container that tracks replica-set for the primary mongodb pod +## and labels it dynamically with ' primary: "true" ' in order for an extra-deployed service to always expose +## and attach to the primary pod, this needs to be uncommented along with the suggested 'extraDeploy' example +## and the suggested rbac example for the pod to be allowed adding labels to mongo replica pods +## search 'mongo-labeler' through this file to find the sections that needs to be uncommented to make it work +## +## - name: mongo-labeler +## image: korenlev/k8s-mongo-labeler-sidecar +## imagePullPolicy: Always +## env: +## - name: LABEL_SELECTOR +## value: "app.kubernetes.io/component=mongodb,app.kubernetes.io/instance=mongodb,app.kubernetes.io/name=mongodb" +## - name: NAMESPACE +## value: "the-mongodb-namespace" +## - name: DEBUG +## value: "true" +## +sidecars: [] +## @param extraVolumeMounts Optionally specify extra list of additional volumeMounts for the MongoDB(®) container(s) +## Examples: +## extraVolumeMounts: +## - name: extras +## mountPath: /usr/share/extras +## readOnly: true +## +extraVolumeMounts: [] +## @param extraVolumes Optionally specify extra list of additional volumes to the MongoDB(®) statefulset +## extraVolumes: +## - name: extras +## emptyDir: {} +## +extraVolumes: [] +## MongoDB(®) Pod Disruption Budget configuration +## ref: https://kubernetes.io/docs/tasks/run-application/configure-pdb/ +## +pdb: + ## @param pdb.create Enable/disable a Pod Disruption Budget creation for MongoDB(®) pod(s) + ## + create: false + ## @param pdb.minAvailable Minimum number/percentage of MongoDB(®) pods that must still be available after the eviction + ## + minAvailable: 1 + ## @param pdb.maxUnavailable Maximum number/percentage of MongoDB(®) pods that may be made unavailable after the eviction + ## + maxUnavailable: "" + +## @section Traffic exposure parameters +## + +## Service parameters +## +service: + ## @param service.nameOverride MongoDB(®) service name + ## + nameOverride: "" + ## @param service.type Kubernetes Service type + ## + type: ClusterIP + ## @param service.port MongoDB(®) service port + ## + port: 27017 + ## @param service.portName MongoDB(®) service port name + ## + portName: mongodb + ## @param service.nodePort Port to bind to for NodePort and LoadBalancer service types + ## ref: https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport + ## + nodePort: "" + ## @param service.clusterIP MongoDB(®) service cluster IP + ## e.g: + ## clusterIP: None + ## + clusterIP: "" + ## @param service.externalIPs Specify the externalIP value ClusterIP service type. + ## ref: https://kubernetes.io/docs/concepts/services-networking/service/#external-ips + ## + externalIPs: [] + ## @param service.loadBalancerIP loadBalancerIP for MongoDB(®) Service + ## ref: https://kubernetes.io/docs/concepts/services-networking/service/#loadbalancer + ## + loadBalancerIP: "" + ## @param service.loadBalancerSourceRanges Address(es) that are allowed when service is LoadBalancer + ## ref: https://kubernetes.io/docs/tasks/access-application-cluster/configure-cloud-provider-firewall/#restrict-access-for-loadbalancer-service + ## + loadBalancerSourceRanges: [] + ## @param service.annotations Provide any additional annotations that may be required + ## + annotations: {} +## External Access to MongoDB(®) nodes configuration +## +externalAccess: + ## @param externalAccess.enabled Enable Kubernetes external cluster access to MongoDB(®) nodes (only for replicaset architecture) + ## + enabled: false + ## External IPs auto-discovery configuration + ## An init container is used to auto-detect LB IPs or node ports by querying the K8s API + ## Note: RBAC might be required + ## + autoDiscovery: + ## @param externalAccess.autoDiscovery.enabled Enable using an init container to auto-detect external IPs by querying the K8s API + ## + enabled: false + ## Bitnami Kubectl image + ## ref: https://hub.docker.com/r/bitnami/kubectl/tags/ + ## @param externalAccess.autoDiscovery.image.registry Init container auto-discovery image registry + ## @param externalAccess.autoDiscovery.image.repository Init container auto-discovery image repository + ## @param externalAccess.autoDiscovery.image.tag Init container auto-discovery image tag (immutable tags are recommended) + ## @param externalAccess.autoDiscovery.image.pullPolicy Init container auto-discovery image pull policy + ## @param externalAccess.autoDiscovery.image.pullSecrets Init container auto-discovery image pull secrets + ## + image: + registry: docker.io + repository: bitnami/kubectl + tag: 1.23.4-debian-10-r7 + ## Specify a imagePullPolicy + ## Defaults to 'Always' if image tag is 'latest', else set to 'IfNotPresent' + ## ref: https://kubernetes.io/docs/user-guide/images/#pre-pulling-images + ## + pullPolicy: IfNotPresent + ## Optionally specify an array of imagePullSecrets (secrets must be manually created in the namespace) + ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/ + ## Example: + ## pullSecrets: + ## - myRegistryKeySecretName + ## + pullSecrets: [] + ## Init Container resource requests and limits + ## ref: https://kubernetes.io/docs/user-guide/compute-resources/ + ## We usually recommend not to specify default resources and to leave this as a conscious + ## choice for the user. This also increases chances charts run on environments with little + ## resources, such as Minikube. If you do want to specify resources, uncomment the following + ## lines, adjust them as necessary, and remove the curly braces after 'resources:'. + ## @param externalAccess.autoDiscovery.resources.limits Init container auto-discovery resource limits + ## @param externalAccess.autoDiscovery.resources.requests Init container auto-discovery resource requests + ## + resources: + ## Example: + ## limits: + ## cpu: 100m + ## memory: 128Mi + ## + limits: {} + ## Examples: + ## requests: + ## cpu: 100m + ## memory: 128Mi + ## + requests: {} + ## Parameters to configure K8s service(s) used to externally access MongoDB(®) + ## A new service per broker will be created + ## + service: + ## @param externalAccess.service.type Kubernetes Service type for external access. Allowed values: NodePort, LoadBalancer or ClusterIP + ## + type: LoadBalancer + ## @param externalAccess.service.port MongoDB(®) port used for external access when service type is LoadBalancer + ## + port: 27017 + ## @param externalAccess.service.loadBalancerIPs Array of load balancer IPs for MongoDB(®) nodes + ## Example: + ## loadBalancerIPs: + ## - X.X.X.X + ## - Y.Y.Y.Y + ## + loadBalancerIPs: [] + ## @param externalAccess.service.loadBalancerSourceRanges Address(es) that are allowed when service is LoadBalancer + ## ref: https://kubernetes.io/docs/tasks/access-application-cluster/configure-cloud-provider-firewall/#restrict-access-for-loadbalancer-service + ## Example: + ## loadBalancerSourceRanges: + ## - 10.10.10.0/24 + ## + loadBalancerSourceRanges: [] + ## @param externalAccess.service.nodePorts Array of node ports used to configure MongoDB(®) advertised hostname when service type is NodePort + ## Example: + ## nodePorts: + ## - 30001 + ## - 30002 + ## + nodePorts: [] + ## @param externalAccess.service.domain Domain or external IP used to configure MongoDB(®) advertised hostname when service type is NodePort + ## If not specified, the container will try to get the kubernetes node external IP + ## e.g: + ## domain: mydomain.com + ## + domain: "" + ## @param externalAccess.service.annotations Service annotations for external access + ## + annotations: {} + ## External Access to MongoDB(®) Hidden nodes configuration + ## + hidden: + ## @param externalAccess.hidden.enabled Enable Kubernetes external cluster access to MongoDB(®) hidden nodes + ## + enabled: false + ## Parameters to configure K8s service(s) used to externally access MongoDB(®) + ## A new service per broker will be created + ## + service: + ## @param externalAccess.hidden.service.type Kubernetes Service type for external access. Allowed values: NodePort or LoadBalancer + ## + type: LoadBalancer + ## @param externalAccess.hidden.service.port MongoDB(®) port used for external access when service type is LoadBalancer + ## + port: 27017 + ## @param externalAccess.hidden.service.loadBalancerIPs Array of load balancer IPs for MongoDB(®) nodes + ## Example: + ## loadBalancerIPs: + ## - X.X.X.X + ## - Y.Y.Y.Y + ## + loadBalancerIPs: [] + ## @param externalAccess.hidden.service.loadBalancerSourceRanges Address(es) that are allowed when service is LoadBalancer + ## ref: https://kubernetes.io/docs/tasks/access-application-cluster/configure-cloud-provider-firewall/#restrict-access-for-loadbalancer-service + ## Example: + ## loadBalancerSourceRanges: + ## - 10.10.10.0/24 + ## + loadBalancerSourceRanges: [] + ## @param externalAccess.hidden.service.nodePorts Array of node ports used to configure MongoDB(®) advertised hostname when service type is NodePort. Length must be the same as replicaCount + ## Example: + ## nodePorts: + ## - 30001 + ## - 30002 + ## + nodePorts: [] + ## @param externalAccess.hidden.service.domain Domain or external IP used to configure MongoDB(®) advertised hostname when service type is NodePort + ## If not specified, the container will try to get the kubernetes node external IP + ## e.g: + ## domain: mydomain.com + ## + domain: "" + ## @param externalAccess.hidden.service.annotations Service annotations for external access + ## + annotations: {} + +## @section Persistence parameters +## + +## Enable persistence using Persistent Volume Claims +## ref: https://kubernetes.io/docs/user-guide/persistent-volumes/ +## +persistence: + ## @param persistence.enabled Enable MongoDB(®) data persistence using PVC + ## + enabled: true + ## @param persistence.medium Provide a medium for `emptyDir` volumes. + ## Requires persistence.enabled: false + ## + medium: "" + ## @param persistence.existingClaim Provide an existing `PersistentVolumeClaim` (only when `architecture=standalone`) + ## Requires persistence.enabled: true + ## If defined, PVC must be created manually before volume will be bound + ## Ignored when mongodb.architecture=replicaset + ## + existingClaim: "" + ## @param persistence.storageClass PVC Storage Class for MongoDB(®) data volume + ## If defined, storageClassName: + ## If set to "-", storageClassName: "", which disables dynamic provisioning + ## If undefined (the default) or set to null, no storageClassName spec is + ## set, choosing the default provisioner. + ## + storageClass: "" + ## @param persistence.accessModes PV Access Mode + ## + accessModes: + - ReadWriteOnce + ## @param persistence.size PVC Storage Request for MongoDB(®) data volume + ## + size: 8Gi + ## @param persistence.annotations PVC annotations + ## + annotations: {} + ## @param persistence.mountPath Path to mount the volume at + ## MongoDB(®) images. + ## + mountPath: /bitnami/mongodb + ## @param persistence.subPath Subdirectory of the volume to mount at + ## and one PV for multiple services. + ## + subPath: "" + ## Fine tuning for volumeClaimTemplates + ## + volumeClaimTemplates: + ## @param persistence.volumeClaimTemplates.selector A label query over volumes to consider for binding (e.g. when using local volumes) + ## A label query over volumes to consider for binding (e.g. when using local volumes) + ## See https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.20/#labelselector-v1-meta for more details + ## + selector: {} + ## @param persistence.volumeClaimTemplates.requests Custom PVC requests attributes + ## Sometime cloud providers use additional requests attributes to provision custom storage instance + ## See https://cloud.ibm.com/docs/containers?topic=containers-file_storage#file_dynamic_statefulset + ## + requests: {} + ## @param persistence.volumeClaimTemplates.dataSource Add dataSource to the VolumeClaimTemplate + ## + dataSource: {} + +## @section RBAC parameters +## + +## ServiceAccount +## ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/ +## +serviceAccount: + ## @param serviceAccount.create Enable creation of ServiceAccount for MongoDB(®) pods + ## + create: true + ## @param serviceAccount.name Name of the created serviceAccount + ## If not set and create is true, a name is generated using the mongodb.fullname template + ## + name: "" + ## @param serviceAccount.annotations Additional Service Account annotations + ## + annotations: {} +## Role Based Access +## ref: https://kubernetes.io/docs/admin/authorization/rbac/ +## +rbac: + ## @param rbac.create Whether to create & use RBAC resources or not + ## binding MongoDB(®) ServiceAccount to a role + ## that allows MongoDB(®) pods querying the K8s API + ## this needs to be set to 'true' to enable the mongo-labeler sidecar primary mongodb discovery + ## + create: false + role: + ## @param rbac.role.rules Custom rules to create following the role specification + ## The example below needs to be uncommented to use the 'mongo-labeler' sidecar for dynamic discovery of the primary mongodb pod: + ## rules: + ## - apiGroups: + ## - "" + ## resources: + ## - pods + ## verbs: + ## - get + ## - list + ## - watch + ## - update + ## + rules: [] +## PodSecurityPolicy configuration +## Be sure to also set rbac.create to true, otherwise Role and RoleBinding won't be created. +## ref: https://kubernetes.io/docs/concepts/policy/pod-security-policy/ +## +podSecurityPolicy: + ## @param podSecurityPolicy.create Whether to create a PodSecurityPolicy. WARNING: PodSecurityPolicy is deprecated in Kubernetes v1.21 or later, unavailable in v1.25 or later + ## + create: false + ## @param podSecurityPolicy.allowPrivilegeEscalation Enable privilege escalation + ## Either use predefined policy with some adjustments or use `podSecurityPolicy.spec` + ## + allowPrivilegeEscalation: false + ## @param podSecurityPolicy.privileged Allow privileged + ## + privileged: false + ## @param podSecurityPolicy.spec Specify the full spec to use for Pod Security Policy + ## ref: https://kubernetes.io/docs/concepts/policy/pod-security-policy/ + ## Defining a spec ignores the above values. + ## + spec: {} + ## Example: + ## allowPrivilegeEscalation: false + ## fsGroup: + ## rule: 'MustRunAs' + ## ranges: + ## - min: 1001 + ## max: 1001 + ## hostIPC: false + ## hostNetwork: false + ## hostPID: false + ## privileged: false + ## readOnlyRootFilesystem: false + ## requiredDropCapabilities: + ## - ALL + ## runAsUser: + ## rule: 'MustRunAs' + ## ranges: + ## - min: 1001 + ## max: 1001 + ## seLinux: + ## rule: 'RunAsAny' + ## supplementalGroups: + ## rule: 'MustRunAs' + ## ranges: + ## - min: 1001 + ## max: 1001 + ## volumes: + ## - 'configMap' + ## - 'secret' + ## - 'emptyDir' + ## - 'persistentVolumeClaim' + ## + +## @section Volume Permissions parameters +## + +## Init Container parameters +## Change the owner and group of the persistent volume(s) mountpoint(s) to 'runAsUser:fsGroup' on each component +## values from the securityContext section of the component +## +volumePermissions: + ## @param volumePermissions.enabled Enable init container that changes the owner and group of the persistent volume(s) mountpoint to `runAsUser:fsGroup` + ## + enabled: false + ## @param volumePermissions.image.registry Init container volume-permissions image registry + ## @param volumePermissions.image.repository Init container volume-permissions image repository + ## @param volumePermissions.image.tag Init container volume-permissions image tag (immutable tags are recommended) + ## @param volumePermissions.image.pullPolicy Init container volume-permissions image pull policy + ## @param volumePermissions.image.pullSecrets Specify docker-registry secret names as an array + ## + image: + registry: docker.io + repository: bitnami/bitnami-shell + tag: 10-debian-10-r350 + ## Specify a imagePullPolicy + ## Defaults to 'Always' if image tag is 'latest', else set to 'IfNotPresent' + ## ref: https://kubernetes.io/docs/user-guide/images/#pre-pulling-images + ## + pullPolicy: IfNotPresent + ## Optionally specify an array of imagePullSecrets (secrets must be manually created in the namespace) + ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/ + ## Example: + ## pullSecrets: + ## - myRegistryKeySecretName + ## + pullSecrets: [] + ## Init Container resource requests and limits + ## ref: https://kubernetes.io/docs/user-guide/compute-resources/ + ## We usually recommend not to specify default resources and to leave this as a conscious + ## choice for the user. This also increases chances charts run on environments with little + ## resources, such as Minikube. If you do want to specify resources, uncomment the following + ## lines, adjust them as necessary, and remove the curly braces after 'resources:'. + ## @param volumePermissions.resources.limits Init container volume-permissions resource limits + ## @param volumePermissions.resources.requests Init container volume-permissions resource requests + ## + resources: + ## Example: + ## limits: + ## cpu: 100m + ## memory: 128Mi + ## + limits: {} + ## Examples: + ## requests: + ## cpu: 100m + ## memory: 128Mi + ## + requests: {} + ## Init container Security Context + ## Note: the chown of the data folder is done to containerSecurityContext.runAsUser + ## and not the below volumePermissions.securityContext.runAsUser + ## When runAsUser is set to special value "auto", init container will try to chwon the + ## data folder to autodetermined user&group, using commands: `id -u`:`id -G | cut -d" " -f2` + ## "auto" is especially useful for OpenShift which has scc with dynamic userids (and 0 is not allowed). + ## You may want to use this volumePermissions.securityContext.runAsUser="auto" in combination with + ## podSecurityContext.enabled=false,containerSecurityContext.enabled=false and shmVolume.chmod.enabled=false + ## @param volumePermissions.securityContext.runAsUser User ID for the volumePermissions container + ## + securityContext: + runAsUser: 0 + +## @section Arbiter parameters +## + +arbiter: + ## @param arbiter.enabled Enable deploying the arbiter + ## https://docs.mongodb.com/manual/tutorial/add-replica-set-arbiter/ + ## + enabled: true + ## @param arbiter.configuration Arbiter configuration file to be used + ## http://docs.mongodb.org/manual/reference/configuration-options/ + ## + configuration: "" + ## @param arbiter.hostAliases Add deployment host aliases + ## https://kubernetes.io/docs/concepts/services-networking/add-entries-to-pod-etc-hosts-with-host-aliases/ + ## + hostAliases: [] + ## @param arbiter.existingConfigmap Name of existing ConfigMap with Arbiter configuration + ## NOTE: When it's set the arbiter.configuration parameter is ignored + ## + existingConfigmap: "" + ## Command and args for running the container (set to default if not set). Use array form + ## @param arbiter.command Override default container command (useful when using custom images) + ## @param arbiter.args Override default container args (useful when using custom images) + ## + command: [] + args: [] + ## @param arbiter.extraFlags Arbiter additional command line flags + ## Example: + ## extraFlags: + ## - "--wiredTigerCacheSizeGB=2" + ## + extraFlags: [] + ## @param arbiter.extraEnvVars Extra environment variables to add to Arbiter pods + ## E.g: + ## extraEnvVars: + ## - name: FOO + ## value: BAR + ## + extraEnvVars: [] + ## @param arbiter.extraEnvVarsCM Name of existing ConfigMap containing extra env vars + ## + extraEnvVarsCM: "" + ## @param arbiter.extraEnvVarsSecret Name of existing Secret containing extra env vars (in case of sensitive data) + ## + extraEnvVarsSecret: "" + ## @param arbiter.annotations Additional labels to be added to the Arbiter statefulset + ## + annotations: {} + ## @param arbiter.labels Annotations to be added to the Arbiter statefulset + ## + labels: {} + ## @param arbiter.podAffinityPreset Arbiter Pod affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` + ## ref: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#inter-pod-affinity-and-anti-affinity + ## + podAffinityPreset: "" + ## @param arbiter.podAntiAffinityPreset Arbiter Pod anti-affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` + ## ref: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#inter-pod-affinity-and-anti-affinity + ## + podAntiAffinityPreset: soft + ## Node affinity preset + ## ref: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity + ## + nodeAffinityPreset: + ## @param arbiter.nodeAffinityPreset.type Arbiter Node affinity preset type. Ignored if `affinity` is set. Allowed values: `soft` or `hard` + ## + type: "" + ## @param arbiter.nodeAffinityPreset.key Arbiter Node label key to match Ignored if `affinity` is set. + ## E.g. + ## key: "kubernetes.io/e2e-az-name" + ## + key: "" + ## @param arbiter.nodeAffinityPreset.values Arbiter Node label values to match. Ignored if `affinity` is set. + ## E.g. + ## values: + ## - e2e-az1 + ## - e2e-az2 + ## + values: [] + ## @param arbiter.affinity Arbiter Affinity for pod assignment + ## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity + ## Note: arbiter.podAffinityPreset, arbiter.podAntiAffinityPreset, and arbiter.nodeAffinityPreset will be ignored when it's set + ## + affinity: {} + ## @param arbiter.nodeSelector Arbiter Node labels for pod assignment + ## ref: https://kubernetes.io/docs/user-guide/node-selection/ + ## + nodeSelector: {} + ## @param arbiter.tolerations Arbiter Tolerations for pod assignment + ## ref: https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/ + ## + tolerations: [] + ## @param arbiter.podLabels Arbiter pod labels + ## ref: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ + ## + podLabels: {} + ## @param arbiter.podAnnotations Arbiter Pod annotations + ## ref: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/ + ## + podAnnotations: {} + ## @param arbiter.priorityClassName Name of the existing priority class to be used by Arbiter pod(s) + ## ref: https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/ + ## + priorityClassName: "" + ## @param arbiter.runtimeClassName Name of the runtime class to be used by Arbiter pod(s) + ## ref: https://kubernetes.io/docs/concepts/containers/runtime-class/ + ## + runtimeClassName: "" + ## MongoDB(®) Arbiter pods' Security Context. + ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/#set-the-security-context-for-a-pod + ## @param arbiter.podSecurityContext.enabled Enable Arbiter pod(s)' Security Context + ## @param arbiter.podSecurityContext.fsGroup Group ID for the volumes of the Arbiter pod(s) + ## @param arbiter.podSecurityContext.sysctls sysctl settings of the Arbiter pod(s)' + ## + podSecurityContext: + enabled: true + fsGroup: 1001 + ## sysctl settings + ## Example: + ## sysctls: + ## - name: net.core.somaxconn + ## value: "10000" + ## + sysctls: [] + ## MongoDB(®) Arbiter containers' Security Context (only main container). + ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/#set-the-security-context-for-a-container + ## @param arbiter.containerSecurityContext.enabled Enable Arbiter container(s)' Security Context + ## @param arbiter.containerSecurityContext.runAsUser User ID for the Arbiter container + ## + containerSecurityContext: + enabled: true + runAsUser: 1001 + ## MongoDB(®) Arbiter containers' resource requests and limits. + ## ref: https://kubernetes.io/docs/user-guide/compute-resources/ + ## We usually recommend not to specify default resources and to leave this as a conscious + ## choice for the user. This also increases chances charts run on environments with little + ## resources, such as Minikube. If you do want to specify resources, uncomment the following + ## lines, adjust them as necessary, and remove the curly braces after 'resources:'. + ## @param arbiter.resources.limits The resources limits for Arbiter containers + ## @param arbiter.resources.requests The requested resources for Arbiter containers + ## + resources: + ## Example: + ## limits: + ## cpu: 100m + ## memory: 128Mi + ## + limits: {} + ## Examples: + ## requests: + ## cpu: 100m + ## memory: 128Mi + ## + requests: {} + ## MongoDB(®) Arbiter pods' liveness probe. Evaluated as a template. + ## ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes + ## @param arbiter.livenessProbe.enabled Enable livenessProbe + ## @param arbiter.livenessProbe.initialDelaySeconds Initial delay seconds for livenessProbe + ## @param arbiter.livenessProbe.periodSeconds Period seconds for livenessProbe + ## @param arbiter.livenessProbe.timeoutSeconds Timeout seconds for livenessProbe + ## @param arbiter.livenessProbe.failureThreshold Failure threshold for livenessProbe + ## @param arbiter.livenessProbe.successThreshold Success threshold for livenessProbe + ## + livenessProbe: + enabled: true + initialDelaySeconds: 30 + periodSeconds: 10 + timeoutSeconds: 5 + failureThreshold: 6 + successThreshold: 1 + ## MongoDB(®) Arbiter pods' readiness probe. Evaluated as a template. + ## ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes + ## @param arbiter.readinessProbe.enabled Enable readinessProbe + ## @param arbiter.readinessProbe.initialDelaySeconds Initial delay seconds for readinessProbe + ## @param arbiter.readinessProbe.periodSeconds Period seconds for readinessProbe + ## @param arbiter.readinessProbe.timeoutSeconds Timeout seconds for readinessProbe + ## @param arbiter.readinessProbe.failureThreshold Failure threshold for readinessProbe + ## @param arbiter.readinessProbe.successThreshold Success threshold for readinessProbe + ## + readinessProbe: + enabled: true + initialDelaySeconds: 5 + periodSeconds: 10 + timeoutSeconds: 5 + failureThreshold: 6 + successThreshold: 1 + ## @param arbiter.customLivenessProbe Override default liveness probe for Arbiter containers + ## Ignored when arbiter.livenessProbe.enabled=true + ## + customLivenessProbe: {} + ## @param arbiter.customReadinessProbe Override default readiness probe for Arbiter containers + ## Ignored when arbiter.readinessProbe.enabled=true + ## + customReadinessProbe: {} + ## @param arbiter.initContainers Add additional init containers for the Arbiter pod(s) + ## Example: + ## initContainers: + ## - name: your-image-name + ## image: your-image + ## imagePullPolicy: Always + ## ports: + ## - name: portname + ## containerPort: 1234 + ## + initContainers: [] + ## @param arbiter.sidecars Add additional sidecar containers for the Arbiter pod(s) + ## Example: + ## sidecars: + ## - name: your-image-name + ## image: your-image + ## imagePullPolicy: Always + ## ports: + ## - name: portname + ## containerPort: 1234 + ## + sidecars: [] + ## @param arbiter.extraVolumeMounts Optionally specify extra list of additional volumeMounts for the Arbiter container(s) + ## Examples: + ## extraVolumeMounts: + ## - name: extras + ## mountPath: /usr/share/extras + ## readOnly: true + ## + extraVolumeMounts: [] + ## @param arbiter.extraVolumes Optionally specify extra list of additional volumes to the Arbiter statefulset + ## extraVolumes: + ## - name: extras + ## emptyDir: {} + ## + extraVolumes: [] + ## MongoDB(®) Arbiter Pod Disruption Budget configuration + ## ref: https://kubernetes.io/docs/tasks/run-application/configure-pdb/ + ## + pdb: + ## @param arbiter.pdb.create Enable/disable a Pod Disruption Budget creation for Arbiter pod(s) + ## + create: false + ## @param arbiter.pdb.minAvailable Minimum number/percentage of Arbiter pods that should remain scheduled + ## + minAvailable: 1 + ## @param arbiter.pdb.maxUnavailable Maximum number/percentage of Arbiter pods that may be made unavailable + ## + maxUnavailable: "" + ## MongoDB(®) Arbiter service parameters + ## + service: + ## @param arbiter.service.nameOverride The arbiter service name + ## + nameOverride: "" + +## @section Hidden Node parameters +## + +hidden: + ## @param hidden.enabled Enable deploying the hidden nodes + ## https://docs.mongodb.com/manual/tutorial/configure-a-hidden-replica-set-member/ + ## + enabled: false + ## @param hidden.configuration Hidden node configuration file to be used + ## http://docs.mongodb.org/manual/reference/configuration-options/ + ## + configuration: "" + ## @param hidden.existingConfigmap Name of existing ConfigMap with Hidden node configuration + ## NOTE: When it's set the hidden.configuration parameter is ignored + ## + existingConfigmap: "" + ## Command and args for running the container (set to default if not set). Use array form + ## @param hidden.command Override default container command (useful when using custom images) + ## @param hidden.args Override default container args (useful when using custom images) + ## + command: [] + args: [] + ## @param hidden.extraFlags Hidden node additional command line flags + ## Example: + ## extraFlags: + ## - "--wiredTigerCacheSizeGB=2" + ## + extraFlags: [] + ## @param hidden.extraEnvVars Extra environment variables to add to Hidden node pods + ## E.g: + ## extraEnvVars: + ## - name: FOO + ## value: BAR + ## + extraEnvVars: [] + ## @param hidden.extraEnvVarsCM Name of existing ConfigMap containing extra env vars + ## + extraEnvVarsCM: "" + ## @param hidden.extraEnvVarsSecret Name of existing Secret containing extra env vars (in case of sensitive data) + ## + extraEnvVarsSecret: "" + ## @param hidden.annotations Additional labels to be added to thehidden node statefulset + ## + annotations: {} + ## @param hidden.labels Annotations to be added to the hidden node statefulset + ## + labels: {} + ## @param hidden.replicaCount Number of hidden nodes (only when `architecture=replicaset`) + ## Ignored when mongodb.architecture=standalone + ## + replicaCount: 1 + ## @param hidden.strategyType StrategyType for hidden node statefulset + ## It can be set to RollingUpdate or Recreate by default. + ## + strategyType: RollingUpdate + ## @param hidden.podManagementPolicy Pod management policy for hidden node + ## + podManagementPolicy: OrderedReady + ## @param hidden.podAffinityPreset Hidden node Pod affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` + ## ref: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#inter-pod-affinity-and-anti-affinity + ## + podAffinityPreset: "" + ## @param hidden.podAntiAffinityPreset Hidden node Pod anti-affinity preset. Ignored if `affinity` is set. Allowed values: `soft` or `hard` + ## ref: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#inter-pod-affinity-and-anti-affinity + ## + podAntiAffinityPreset: soft + ## Node affinity preset + ## ref: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity + ## Allowed values: soft, hard + ## + nodeAffinityPreset: + ## @param hidden.nodeAffinityPreset.type Hidden Node affinity preset type. Ignored if `affinity` is set. Allowed values: `soft` or `hard` + ## + type: "" + ## @param hidden.nodeAffinityPreset.key Hidden Node label key to match Ignored if `affinity` is set. + ## E.g. + ## key: "kubernetes.io/e2e-az-name" + ## + key: "" + ## @param hidden.nodeAffinityPreset.values Hidden Node label values to match. Ignored if `affinity` is set. + ## E.g. + ## values: + ## - e2e-az1 + ## - e2e-az2 + ## + values: [] + ## @param hidden.affinity Hidden node Affinity for pod assignment + ## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity + ## Note: podAffinityPreset, podAntiAffinityPreset, and nodeAffinityPreset will be ignored when it's set + ## + affinity: {} + ## @param hidden.nodeSelector Hidden node Node labels for pod assignment + ## ref: https://kubernetes.io/docs/user-guide/node-selection/ + ## + nodeSelector: {} + ## @param hidden.tolerations Hidden node Tolerations for pod assignment + ## ref: https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/ + ## + tolerations: [] + ## @param hidden.podLabels Hidden node pod labels + ## ref: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ + ## + podLabels: {} + ## @param hidden.podAnnotations Hidden node Pod annotations + ## ref: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/ + ## + podAnnotations: {} + ## @param hidden.priorityClassName Name of the existing priority class to be used by hidden node pod(s) + ## ref: https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/ + ## + priorityClassName: "" + ## @param hidden.runtimeClassName Name of the runtime class to be used by hidden node pod(s) + ## ref: https://kubernetes.io/docs/concepts/containers/runtime-class/ + ## + runtimeClassName: "" + ## MongoDB(®) Hidden containers' resource requests and limits. + ## ref: https://kubernetes.io/docs/user-guide/compute-resources/ + ## We usually recommend not to specify default resources and to leave this as a conscious + ## choice for the user. This also increases chances charts run on environments with little + ## resources, such as Minikube. If you do want to specify resources, uncomment the following + ## lines, adjust them as necessary, and remove the curly braces after 'resources:'. + ## @param hidden.resources.limits The resources limits for hidden node containers + ## @param hidden.resources.requests The requested resources for hidden node containers + ## + resources: + ## Example: + ## limits: + ## cpu: 100m + ## memory: 128Mi + ## + limits: {} + ## Examples: + ## requests: + ## cpu: 100m + ## memory: 128Mi + ## + requests: {} + ## MongoDB(®) Hidden pods' liveness probe. Evaluated as a template. + ## ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes + ## @param hidden.livenessProbe.enabled Enable livenessProbe + ## @param hidden.livenessProbe.initialDelaySeconds Initial delay seconds for livenessProbe + ## @param hidden.livenessProbe.periodSeconds Period seconds for livenessProbe + ## @param hidden.livenessProbe.timeoutSeconds Timeout seconds for livenessProbe + ## @param hidden.livenessProbe.failureThreshold Failure threshold for livenessProbe + ## @param hidden.livenessProbe.successThreshold Success threshold for livenessProbe + ## + livenessProbe: + enabled: true + initialDelaySeconds: 30 + periodSeconds: 10 + timeoutSeconds: 5 + failureThreshold: 6 + successThreshold: 1 + ## MongoDB(®) Hidden pods' readiness probe. Evaluated as a template. + ## ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes + ## @param hidden.readinessProbe.enabled Enable readinessProbe + ## @param hidden.readinessProbe.initialDelaySeconds Initial delay seconds for readinessProbe + ## @param hidden.readinessProbe.periodSeconds Period seconds for readinessProbe + ## @param hidden.readinessProbe.timeoutSeconds Timeout seconds for readinessProbe + ## @param hidden.readinessProbe.failureThreshold Failure threshold for readinessProbe + ## @param hidden.readinessProbe.successThreshold Success threshold for readinessProbe + ## + readinessProbe: + enabled: true + initialDelaySeconds: 5 + periodSeconds: 10 + timeoutSeconds: 5 + failureThreshold: 6 + successThreshold: 1 + ## @param hidden.customLivenessProbe Override default liveness probe for hidden node containers + ## Ignored when livenessProbe.enabled=true + ## + customLivenessProbe: {} + ## @param hidden.customReadinessProbe Override default readiness probe for hidden node containers + ## Ignored when readinessProbe.enabled=true + ## + customReadinessProbe: {} + ## @param hidden.initContainers Add init containers to the MongoDB(®) Hidden pods. + ## Example: + ## initContainers: + ## - name: your-image-name + ## image: your-image + ## imagePullPolicy: Always + ## ports: + ## - name: portname + ## containerPort: 1234 + ## + initContainers: [] + ## @param hidden.sidecars Add additional sidecar containers for the hidden node pod(s) + ## Example: + ## sidecars: + ## - name: your-image-name + ## image: your-image + ## imagePullPolicy: Always + ## ports: + ## - name: portname + ## containerPort: 1234 + ## + sidecars: [] + ## @param hidden.extraVolumeMounts Optionally specify extra list of additional volumeMounts for the hidden node container(s) + ## Examples: + ## extraVolumeMounts: + ## - name: extras + ## mountPath: /usr/share/extras + ## readOnly: true + ## + extraVolumeMounts: [] + ## @param hidden.extraVolumes Optionally specify extra list of additional volumes to the hidden node statefulset + ## extraVolumes: + ## - name: extras + ## emptyDir: {} + ## + extraVolumes: [] + ## MongoDB(®) Hidden Pod Disruption Budget configuration + ## ref: https://kubernetes.io/docs/tasks/run-application/configure-pdb/ + ## + pdb: + ## @param hidden.pdb.create Enable/disable a Pod Disruption Budget creation for hidden node pod(s) + ## + create: false + ## @param hidden.pdb.minAvailable Minimum number/percentage of hidden node pods that should remain scheduled + ## + minAvailable: 1 + ## @param hidden.pdb.maxUnavailable Maximum number/percentage of hidden node pods that may be made unavailable + ## + maxUnavailable: "" + ## Enable persistence using Persistent Volume Claims + ## ref: https://kubernetes.io/docs/user-guide/persistent-volumes/ + ## + persistence: + ## @param hidden.persistence.enabled Enable hidden node data persistence using PVC + ## + enabled: true + ## @param hidden.persistence.medium Provide a medium for `emptyDir` volumes. + ## Requires hidden.persistence.enabled: false + ## + medium: "" + ## @param hidden.persistence.storageClass PVC Storage Class for hidden node data volume + ## If defined, storageClassName: + ## If set to "-", storageClassName: "", which disables dynamic provisioning + ## If undefined (the default) or set to null, no storageClassName spec is + ## set, choosing the default provisioner. + ## + storageClass: "" + ## @param hidden.persistence.accessModes PV Access Mode + ## + accessModes: + - ReadWriteOnce + ## @param hidden.persistence.size PVC Storage Request for hidden node data volume + ## + size: 8Gi + ## @param hidden.persistence.annotations PVC annotations + ## + annotations: {} + ## @param hidden.persistence.mountPath The path the volume will be mounted at, useful when using different MongoDB(®) images. + ## + mountPath: /bitnami/mongodb + ## @param hidden.persistence.subPath The subdirectory of the volume to mount to, useful in dev environments + ## and one PV for multiple services. + ## + subPath: "" + ## Fine tuning for volumeClaimTemplates + ## + volumeClaimTemplates: + ## @param hidden.persistence.volumeClaimTemplates.selector A label query over volumes to consider for binding (e.g. when using local volumes) + ## See https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.20/#labelselector-v1-meta for more details + ## + selector: {} + ## @param hidden.persistence.volumeClaimTemplates.dataSource Set volumeClaimTemplate dataSource + ## + dataSource: {} + +## @section Metrics parameters +## + +metrics: + ## @param metrics.enabled Enable using a sidecar Prometheus exporter + ## + enabled: false + ## Bitnami MongoDB(®) Promtheus Exporter image + ## ref: https://hub.docker.com/r/bitnami/mongodb-exporter/tags/ + ## @param metrics.image.registry MongoDB(®) Prometheus exporter image registry + ## @param metrics.image.repository MongoDB(®) Prometheus exporter image repository + ## @param metrics.image.tag MongoDB(®) Prometheus exporter image tag (immutable tags are recommended) + ## @param metrics.image.pullPolicy MongoDB(®) Prometheus exporter image pull policy + ## @param metrics.image.pullSecrets Specify docker-registry secret names as an array + ## + image: + registry: docker.io + repository: bitnami/mongodb-exporter + tag: 0.30.0-debian-10-r83 + pullPolicy: IfNotPresent + ## Optionally specify an array of imagePullSecrets. + ## Secrets must be manually created in the namespace. + ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/ + ## e.g: + ## pullSecrets: + ## - myRegistryKeySecretName + ## + pullSecrets: [] + + ## @param metrics.username String with username for the metrics exporter + ## If undefined the root user will be used for the metrics exporter + username: "" + ## @param metrics.password String with password for the metrics exporter + ## If undefined but metrics.username is defined, a random password will be generated + password: "" + ## @param metrics.extraFlags String with extra flags to the metrics exporter + ## ref: https://github.com/percona/mongodb_exporter/blob/master/mongodb_exporter.go + ## + extraFlags: "" + ## @param metrics.extraUri Additional URI options of the metrics service + ## ref: https://docs.mongodb.com/manual/reference/connection-string + ## + extraUri: "" + ## Metrics exporter container resource requests and limits + ## ref: https://kubernetes.io/docs/user-guide/compute-resources/ + ## We usually recommend not to specify default resources and to leave this as a conscious + ## choice for the user. This also increases chances charts run on environments with little + ## resources, such as Minikube. If you do want to specify resources, uncomment the following + ## lines, adjust them as necessary, and remove the curly braces after 'resources:'. + ## @param metrics.resources.limits The resources limits for Prometheus exporter containers + ## @param metrics.resources.requests The requested resources for Prometheus exporter containers + ## + resources: + ## Example: + ## limits: + ## cpu: 100m + ## memory: 128Mi + ## + limits: {} + ## Examples: + ## requests: + ## cpu: 100m + ## memory: 128Mi + ## + requests: {} + ## @param metrics.containerPort Port of the Prometheus metrics container + ## + containerPort: 9216 + ## Prometheus Exporter service configuration + ## + service: + ## @param metrics.service.annotations [object] Annotations for Prometheus Exporter pods. Evaluated as a template. + ## ref: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/ + ## + annotations: + prometheus.io/scrape: "true" + prometheus.io/port: "{{ .Values.metrics.service.port }}" + prometheus.io/path: "/metrics" + ## @param metrics.service.type Type of the Prometheus metrics service + ## + type: ClusterIP + ## @param metrics.service.port Port of the Prometheus metrics service + ## + port: 9216 + ## Metrics exporter liveness probe + ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/#configure-probes) + ## @param metrics.livenessProbe.enabled Enable livenessProbe + ## @param metrics.livenessProbe.initialDelaySeconds Initial delay seconds for livenessProbe + ## @param metrics.livenessProbe.periodSeconds Period seconds for livenessProbe + ## @param metrics.livenessProbe.timeoutSeconds Timeout seconds for livenessProbe + ## @param metrics.livenessProbe.failureThreshold Failure threshold for livenessProbe + ## @param metrics.livenessProbe.successThreshold Success threshold for livenessProbe + ## + livenessProbe: + enabled: true + initialDelaySeconds: 15 + periodSeconds: 5 + timeoutSeconds: 5 + failureThreshold: 3 + successThreshold: 1 + ## Metrics exporter readiness probe + ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/#configure-probes) + ## @param metrics.readinessProbe.enabled Enable readinessProbe + ## @param metrics.readinessProbe.initialDelaySeconds Initial delay seconds for readinessProbe + ## @param metrics.readinessProbe.periodSeconds Period seconds for readinessProbe + ## @param metrics.readinessProbe.timeoutSeconds Timeout seconds for readinessProbe + ## @param metrics.readinessProbe.failureThreshold Failure threshold for readinessProbe + ## @param metrics.readinessProbe.successThreshold Success threshold for readinessProbe + ## + readinessProbe: + enabled: true + initialDelaySeconds: 5 + periodSeconds: 5 + timeoutSeconds: 1 + failureThreshold: 3 + successThreshold: 1 + ## Prometheus Service Monitor + ## ref: https://github.com/coreos/prometheus-operator + ## https://github.com/coreos/prometheus-operator/blob/master/Documentation/api.md + ## + serviceMonitor: + ## @param metrics.serviceMonitor.enabled Create ServiceMonitor Resource for scraping metrics using Prometheus Operator + ## + enabled: false + ## @param metrics.serviceMonitor.namespace Namespace which Prometheus is running in + ## + namespace: "" + ## @param metrics.serviceMonitor.interval Interval at which metrics should be scraped + ## + interval: 30s + ## @param metrics.serviceMonitor.scrapeTimeout Specify the timeout after which the scrape is ended + ## e.g: + ## scrapeTimeout: 30s + ## + scrapeTimeout: "" + ## @param metrics.serviceMonitor.relabellings RelabelConfigs to apply to samples before scraping. + ## + relabellings: [] + ## @param metrics.serviceMonitor.metricRelabelings MetricsRelabelConfigs to apply to samples before ingestion. + ## + metricRelabelings: [] + ## @param metrics.serviceMonitor.additionalLabels Used to pass Labels that are used by the Prometheus installed in your cluster to select Service Monitors to work with + ## ref: https://github.com/coreos/prometheus-operator/blob/master/Documentation/api.md#prometheusspec + ## + additionalLabels: {} + ## Custom PrometheusRule to be defined + ## ref: https://github.com/coreos/prometheus-operator#customresourcedefinitions + ## + prometheusRule: + ## @param metrics.prometheusRule.enabled Set this to true to create prometheusRules for Prometheus operator + ## + enabled: false + ## @param metrics.prometheusRule.additionalLabels Additional labels that can be used so prometheusRules will be discovered by Prometheus + ## + additionalLabels: {} + ## @param metrics.prometheusRule.namespace Namespace where prometheusRules resource should be created + ## + namespace: "" + ## @param metrics.prometheusRule.rules Rules to be created, check values for an example + ## ref: https://github.com/coreos/prometheus-operator/blob/master/Documentation/api.md#rulegroup + ## https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/ + ## + ## This is an example of a rule, you should add the below code block under the "rules" param, removing the brackets + ## - name: example + ## rules: + ## - alert: HighRequestLatency + ## expr: job:request_latency_seconds:mean5m{job="myjob"} > 0.5 + ## for: 10m + ## labels: + ## severity: page + ## annotations: + ## summary: High request latency + ## + rules: {} diff --git a/packages/shipa/charts/limits.yaml b/packages/shipa/charts/limits.yaml new file mode 100644 index 000000000..28b736eaa --- /dev/null +++ b/packages/shipa/charts/limits.yaml @@ -0,0 +1,9 @@ +apiVersion: v1 +kind: LimitRange +metadata: + name: limits +spec: + limits: + - defaultRequest: + cpu: 40m + type: Container diff --git a/packages/shipa/charts/questions.yaml b/packages/shipa/charts/questions.yaml new file mode 100644 index 000000000..d9c562bf7 --- /dev/null +++ b/packages/shipa/charts/questions.yaml @@ -0,0 +1,51 @@ +questions: +- variable: auth.adminUser + default: "" + required: true + type: string + label: Initial Admin User Name e.g acme@yourorg.com + group: "Initial Settings - Required" +- variable: auth.adminPassword + default: "" + type: password + required: true + label: Initial Admin Password/Secret + group: "Initial Settings - Required" +- variable: shipaCluster.ingress.type + default: "" + type: enum + required: false + label: Ingress Controller Type (Nginx is default / Shipa Managed. Others are reliant on your installation) [shipaCluster.ingress.type] + group: "Shipa Cluster - Optional" + options: + - "nginx" + - "istio" + - "traefik" +- variable: shipaCluster.ingress.serviceType + default: "" + type: enum + required: false + label: Cluster Service Type e.g ClusterIP [shipaCluster.ingress.serviceType] + group: "Shipa Cluster - Optional" + options: + - "ClusterIP" + - "NodePort" + - "LoadBalancer" +- variable: shipaCluster.ingress.clusterIp + default: "" + type: string + required: false + label: Cluster IP if using Shipa Managed Nginx ClusterIP Service Type [shipaCluster.ingress.clusterIp] + group: "Shipa Cluster - Optional" +- variable: shipaCluster.ingress.loadBalancerIp + default: "" + type: string + required: false + label: LoadBalancer IP if using Shipa Managed Nginx LoadBalancer Service Type [shipaCluster.ingress.loadBalancerIp] + group: "Shipa Cluster - Optional" +- variable: shipaCluster.ingress.nodePort + default: "" + type: string + required: false + label: NodePort if using Shipa Managed Nginx NodePort Service Type [shipaCluster.ingress.nodePort] + group: "Shipa Cluster - Optional" \ No newline at end of file diff --git a/packages/shipa/charts/scripts/bootstrap.sh b/packages/shipa/charts/scripts/bootstrap.sh new file mode 100644 index 000000000..74b216220 --- /dev/null +++ b/packages/shipa/charts/scripts/bootstrap.sh @@ -0,0 +1,166 @@ +#!/bin/sh + +set -euxo pipefail + +is_shipa_initialized() { + + # By default we create secret with empty certificates + # and save them to the secret as a result of the first run of boostrap.sh + + CA=$(kubectl get secret/shipa-certificates -o json | jq ".data[\"ca.pem\"]") + LENGTH=${#CA} + + if [ "$LENGTH" -gt "100" ]; then + return 0 + fi + return 1 +} + +echo "Waiting for nginx ingress to be ready" + +if [[ $WAIT_FOR_NGINX == "true" ]]; then + # This helper gets an IP address or DNS name of NGINX_SERVICE and prints it to /tmp/nginx-ip + /bin/bootstrap-helper --service-name=$NGINX_SERVICE --namespace=$POD_NAMESPACE --timeout=600 --filename=/tmp/nginx-ip + MAIN_INGRESS_IP=$(cat /tmp/nginx-ip) + HOST_ADDRESS=$(cat /tmp/nginx-ip) +else + MAIN_INGRESS_IP=$INGRESS_IP + HOST_ADDRESS=$INGRESS_IP +fi + + + +# If target CNAMEs are set by user in values.yaml, then use the first CNAME from the list as HOST_ADDRESS +# since Shipa host can be only one in the shipa.conf +if [ ! -z "$SHIPA_MAIN_TARGET" -a "$SHIPA_MAIN_TARGET" != " " ]; then + HOST_ADDRESS=$SHIPA_MAIN_TARGET +fi + + +echo "Prepare shipa.conf" +cp -v /etc/shipa-default/shipa.conf /etc/shipa/shipa.conf +sed -i "s/SHIPA_PUBLIC_IP/$HOST_ADDRESS/g" /etc/shipa/shipa.conf +sed -ie "s/SHIPA_ORGANIZATION_ID/$SHIPA_ORGANIZATION_ID/g" /etc/shipa/shipa.conf + +echo "shipa.conf: " +cat /etc/shipa/shipa.conf + +CERTIFICATES_DIRECTORY=/tmp/certs +mkdir $CERTIFICATES_DIRECTORY + +if is_shipa_initialized; then + +# migration for before API was assessable over any ingress controller +if [[ $INGRESS_TYPE == "nginx" ]]; then + echo "Refreshing API secrets" + # before we used TCP streaming on ports 8080 and 8081 and Shipa API was doing certificate checks + # today we let nginx do certificate checks + # because 80 and 443 are reserverd for Ingress and can't use TCP streaming, we need to create secret for nginx + # we want to create dedicated secret for nginx based on shipa-certificates secret + if [[ $WAIT_FOR_NGINX == "true" ]]; then + kubectl get secrets -n "$POD_NAMESPACE" shipa-certificates -o json | jq ".data[\"api-server.crt\"]" | xargs echo | base64 -d > $CERTIFICATES_DIRECTORY/api-server.pem + kubectl get secrets -n "$POD_NAMESPACE" shipa-certificates -o json | jq ".data[\"api-server.key\"]" | xargs echo | base64 -d > $CERTIFICATES_DIRECTORY/api-server-key.pem + + API_SERVER_CERT=$(cat $CERTIFICATES_DIRECTORY/api-server.pem | base64) + API_SERVER_KEY=$(cat $CERTIFICATES_DIRECTORY/api-server-key.pem | base64) + + kubectl -n $POD_NAMESPACE create secret tls $RELEASE_NAME-api-ingress-secret --key=$CERTIFICATES_DIRECTORY/api-server-key.pem --cert=$CERTIFICATES_DIRECTORY/api-server.pem --dry-run -o yaml | kubectl apply -f - + fi +fi + + echo "Skip bootstrapping because shipa is already initialized" + exit 0 +fi + +echo "Cert For: $MAIN_INGRESS_IP" +echo "Cert For: $SHIPA_API_CNAMES" + +# certificate generation for default domain +sed "s/SHIPA_PUBLIC_IP/$MAIN_INGRESS_IP/g" /scripts/csr-shipa-ca.json > $CERTIFICATES_DIRECTORY/csr-shipa-ca.json +sed "s/SHIPA_PUBLIC_IP/$MAIN_INGRESS_IP/g" /scripts/csr-docker-cluster.json > $CERTIFICATES_DIRECTORY/csr-docker-cluster.json +sed "s/SHIPA_PUBLIC_IP/$MAIN_INGRESS_IP/g" /scripts/csr-api-config.json > $CERTIFICATES_DIRECTORY/csr-api-config.json +sed "s/SHIPA_PUBLIC_IP/$MAIN_INGRESS_IP/g" /scripts/csr-api-server.json > $CERTIFICATES_DIRECTORY/csr-api-server.json + +# certificate generation for CNAMES +sed "s/SHIPA_API_CNAMES/$SHIPA_API_CNAMES/g" --in-place $CERTIFICATES_DIRECTORY/csr-docker-cluster.json +sed "s/SHIPA_API_CNAMES/$SHIPA_API_CNAMES/g" --in-place $CERTIFICATES_DIRECTORY/csr-api-server.json + +# certificate generation for Internal DNS so that internal services could connect to it. +sed "s/SHIPA_INTERNAL_DNS/$SHIPA_INTERNAL_DNS/g" --in-place $CERTIFICATES_DIRECTORY/csr-docker-cluster.json +sed "s/SHIPA_INTERNAL_DNS/$SHIPA_INTERNAL_DNS/g" --in-place $CERTIFICATES_DIRECTORY/csr-api-server.json + +jq 'fromstream(tostream | select(length == 1 or .[1] != ""))' $CERTIFICATES_DIRECTORY/csr-docker-cluster.json > $CERTIFICATES_DIRECTORY/file.tmp && mv $CERTIFICATES_DIRECTORY/file.tmp $CERTIFICATES_DIRECTORY/csr-docker-cluster.json +jq 'fromstream(tostream | select(length == 1 or .[1] != ""))' $CERTIFICATES_DIRECTORY/csr-api-server.json > $CERTIFICATES_DIRECTORY/file.tmp && mv $CERTIFICATES_DIRECTORY/file.tmp $CERTIFICATES_DIRECTORY/csr-api-server.json + +cp /scripts/csr-client-ca.json $CERTIFICATES_DIRECTORY/csr-client-ca.json + +cfssl gencert -initca $CERTIFICATES_DIRECTORY/csr-shipa-ca.json | cfssljson -bare $CERTIFICATES_DIRECTORY/ca +cfssl gencert -initca $CERTIFICATES_DIRECTORY/csr-client-ca.json | cfssljson -bare $CERTIFICATES_DIRECTORY/client-ca + +cfssl gencert \ + -ca=$CERTIFICATES_DIRECTORY/ca.pem \ + -ca-key=$CERTIFICATES_DIRECTORY/ca-key.pem \ + -profile=server \ + $CERTIFICATES_DIRECTORY/csr-docker-cluster.json | cfssljson -bare $CERTIFICATES_DIRECTORY/docker-cluster + +cfssl gencert \ + -ca=$CERTIFICATES_DIRECTORY/ca.pem \ + -ca-key=$CERTIFICATES_DIRECTORY/ca-key.pem \ + -config=$CERTIFICATES_DIRECTORY/csr-api-config.json \ + -profile=server \ + $CERTIFICATES_DIRECTORY/csr-api-server.json | cfssljson -bare $CERTIFICATES_DIRECTORY/api-server + +rm -f $CERTIFICATES_DIRECTORY/*.csr +rm -f $CERTIFICATES_DIRECTORY/*.json + +CA_CERT=$(cat $CERTIFICATES_DIRECTORY/ca.pem | base64) +CA_KEY=$(cat $CERTIFICATES_DIRECTORY/ca-key.pem | base64) + +CLIENT_CA_CERT=$(cat $CERTIFICATES_DIRECTORY/client-ca.pem | base64) +CLIENT_CA_KEY=$(cat $CERTIFICATES_DIRECTORY/client-ca-key.pem | base64) + +DOCKER_CLUSTER_CERT=$(cat $CERTIFICATES_DIRECTORY/docker-cluster.pem | base64) +DOCKER_CLUSTER_KEY=$(cat $CERTIFICATES_DIRECTORY/docker-cluster-key.pem | base64) + +API_SERVER_CERT=$(cat $CERTIFICATES_DIRECTORY/api-server.pem | base64) +API_SERVER_KEY=$(cat $CERTIFICATES_DIRECTORY/api-server-key.pem | base64) + +# all ingress controlelers require different type of secret to work with self signed +if [[ $INGRESS_TYPE == "nginx" ]]; then +kubectl -n $POD_NAMESPACE create secret tls $RELEASE_NAME-api-ingress-secret --key=$CERTIFICATES_DIRECTORY/api-server-key.pem --cert=$CERTIFICATES_DIRECTORY/api-server.pem --dry-run -o yaml | kubectl apply -f - +# restart nginx to reload secret +if [[ $WAIT_FOR_NGINX == "true" ]]; then + kubectl -n $POD_NAMESPACE rollout restart deployment $NGINX_DEPLOYMENT_NAME +fi +fi + +if [[ $INGRESS_TYPE == "traefik" ]]; then +openssl x509 -in $CERTIFICATES_DIRECTORY/api-server.pem -out $CERTIFICATES_DIRECTORY/api-server.crt +openssl pkey -in $CERTIFICATES_DIRECTORY/api-server-key.pem -out $CERTIFICATES_DIRECTORY/api-server.key +kubectl -n $POD_NAMESPACE create secret generic $RELEASE_NAME-api-ingress-secret --from-file=tls.crt=$CERTIFICATES_DIRECTORY/api-server.crt --from-file=tls.key=$CERTIFICATES_DIRECTORY/api-server.key --dry-run -o yaml | kubectl apply -f - +fi + +if [[ $INGRESS_TYPE == "istio" ]]; then +openssl x509 -in $CERTIFICATES_DIRECTORY/api-server.pem -out $CERTIFICATES_DIRECTORY/api-server.crt +openssl pkey -in $CERTIFICATES_DIRECTORY/api-server-key.pem -out $CERTIFICATES_DIRECTORY/api-server.key +kubectl -n istio-system create secret tls $RELEASE_NAME-api-ingress-secret --key=$CERTIFICATES_DIRECTORY/api-server.key --cert=$CERTIFICATES_DIRECTORY/api-server.crt --dry-run -o yaml | kubectl apply -f - +fi + +# FIXME: name of secret +kubectl get secrets shipa-certificates -o json \ + | jq ".data[\"ca.pem\"] |= \"$CA_CERT\"" \ + | jq ".data[\"ca-key.pem\"] |= \"$CA_KEY\"" \ + | jq ".data[\"client-ca.crt\"] |= \"$CLIENT_CA_CERT\"" \ + | jq ".data[\"client-ca.key\"] |= \"$CLIENT_CA_KEY\"" \ + | jq ".data[\"cert.pem\"] |= \"$DOCKER_CLUSTER_CERT\"" \ + | jq ".data[\"key.pem\"] |= \"$DOCKER_CLUSTER_KEY\"" \ + | jq ".data[\"api-server.crt\"] |= \"$API_SERVER_CERT\"" \ + | jq ".data[\"api-server.key\"] |= \"$API_SERVER_KEY\"" \ + | kubectl apply -f - + + +echo "CA:" +openssl x509 -in $CERTIFICATES_DIRECTORY/ca.pem -text -noout + +echo "Docker cluster:" +openssl x509 -in $CERTIFICATES_DIRECTORY/docker-cluster.pem -text -noout diff --git a/packages/shipa/charts/scripts/csr-api-config.json b/packages/shipa/charts/scripts/csr-api-config.json new file mode 100644 index 000000000..d6a798638 --- /dev/null +++ b/packages/shipa/charts/scripts/csr-api-config.json @@ -0,0 +1,17 @@ +{ + "signing": { + "default": { + "expiry": "168h" + }, + "profiles": { + "server": { + "expiry": "8760h", + "usages": [ + "signing", + "key encipherment", + "server auth" + ] + } + } + } +} \ No newline at end of file diff --git a/packages/shipa/charts/scripts/csr-api-server.json b/packages/shipa/charts/scripts/csr-api-server.json new file mode 100644 index 000000000..22fb7d2e2 --- /dev/null +++ b/packages/shipa/charts/scripts/csr-api-server.json @@ -0,0 +1,17 @@ +{ + "CN": "Shipa", + "hosts": [ + "SHIPA_PUBLIC_IP", + "SHIPA_API_CNAMES", + "SHIPA_INTERNAL_DNS" + ], + "key": { + "algo": "rsa", + "size": 2048 + }, + "names": [ + { + "O": "shipa" + } + ] +} \ No newline at end of file diff --git a/packages/shipa/charts/scripts/csr-client-ca.json b/packages/shipa/charts/scripts/csr-client-ca.json new file mode 100644 index 000000000..e2d36c7f8 --- /dev/null +++ b/packages/shipa/charts/scripts/csr-client-ca.json @@ -0,0 +1,12 @@ +{ + "CN": "Shipa", + "key": { + "algo": "rsa", + "size": 2048 + }, + "names": [ + { + "O": "shipa" + } + ] +} diff --git a/packages/shipa/charts/scripts/csr-docker-cluster.json b/packages/shipa/charts/scripts/csr-docker-cluster.json new file mode 100644 index 000000000..1b52fc79d --- /dev/null +++ b/packages/shipa/charts/scripts/csr-docker-cluster.json @@ -0,0 +1,17 @@ +{ + "CN": "Shipa docker cluster", + "hosts": [ + "SHIPA_PUBLIC_IP", + "SHIPA_API_CNAMES", + "SHIPA_INTERNAL_DNS" + ], + "key": { + "algo": "rsa", + "size": 2048 + }, + "names": [ + { + "O": "Shipa" + } + ] +} \ No newline at end of file diff --git a/packages/shipa/charts/scripts/csr-shipa-ca.json b/packages/shipa/charts/scripts/csr-shipa-ca.json new file mode 100644 index 000000000..e2d36c7f8 --- /dev/null +++ b/packages/shipa/charts/scripts/csr-shipa-ca.json @@ -0,0 +1,12 @@ +{ + "CN": "Shipa", + "key": { + "algo": "rsa", + "size": 2048 + }, + "names": [ + { + "O": "shipa" + } + ] +} diff --git a/packages/shipa/charts/scripts/init-job.sh b/packages/shipa/charts/scripts/init-job.sh new file mode 100644 index 000000000..a1cfc5cf2 --- /dev/null +++ b/packages/shipa/charts/scripts/init-job.sh @@ -0,0 +1,103 @@ +#!/bin/sh + +echo "Waiting for shipa api" + +until $(curl --output /dev/null --silent http://$SHIPA_ENDPOINT:$SHIPA_ENDPOINT_PORT); do + echo "." + sleep 1 +done + +SHIPA_CLIENT="/bin/shipa" +$SHIPA_CLIENT target add -s local $SHIPA_ENDPOINT --insecure --port=$SHIPA_ENDPOINT_PORT --disable-cert-validation +$SHIPA_CLIENT login <.shipa.cloud + it should be used instead of shipaApi.cnames, as we always want to have this default address +*/}} +{{- define "shipa.cnames" -}} +{{- if has (printf "api.%s.shipa.cloud" .Values.shipaCluster.ingress.ip) .Values.shipaApi.cnames }} +{{ join "," .Values.shipaApi.cnames }} +{{- else }} +{{- if .Values.shipaCluster.ingress.ip }} +{{ join "," (append .Values.shipaApi.cnames (printf "api.%s.shipa.cloud" .Values.shipaCluster.ingress.ip)) }} +{{- else }} +{{ join "," .Values.shipaApi.cnames }} +{{- end }} +{{- end }} +{{- end }} + +{{/* + for shipa managed nginx we use shipa-nginx-ingress as classname + for user managed nginx default is nginx, but user can modify it through values.yaml +*/}} +{{- define "shipa.defaultNginxClassName" }} +{{ if and (eq .Values.shipaCluster.ingress.type "nginx") (not .Values.shipaCluster.ingress.ip)}} +shipa-nginx-ingress +{{- else }} +nginx +{{- end }} +{{- end }} diff --git a/packages/shipa/charts/templates/api-istio-resources.yaml b/packages/shipa/charts/templates/api-istio-resources.yaml new file mode 100644 index 000000000..664621eb7 --- /dev/null +++ b/packages/shipa/charts/templates/api-istio-resources.yaml @@ -0,0 +1,296 @@ +{{ if eq .Values.shipaCluster.ingress.type "istio" }} +{{- if not .Values.shipaApi.secureIngressOnly }} +{{- range $i, $servicePort := .Values.shipaApi.servicePorts }} +{{- if $.Values.shipaCluster.ingress.apiAccessOnIngressIp }} +apiVersion: networking.istio.io/v1beta1 +kind: VirtualService +metadata: + annotations: + kubernetes.io/ingress.class: {{ default ( "istio" ) $.Values.shipaCluster.ingress.className }} +{{- if $.Values.shipaApi.customIngressAnnotations }} +{{ toYaml $.Values.shipaApi.customIngressAnnotations | indent 4 }} +{{- end }} + labels: {{- include "shipa.labels" $ | nindent 4 }} + name: {{ template "shipa.fullname" $ }}-api-http-virutal-service-{{ $i }} +spec: + gateways: + - {{ template "shipa.fullname" $ }}-api-http-gateway-{{ $i }} + hosts: + - "*" + http: + - route: + - destination: + host: {{ template "shipa.fullname" $ }}-api + port: + number: {{ $servicePort }} + weight: 100 +--- +apiVersion: networking.istio.io/v1beta1 +kind: Gateway +metadata: + labels: {{- include "shipa.labels" $ | nindent 4 }} + name: {{ template "shipa.fullname" $ }}-api-http-gateway-{{ $i }} +spec: + selector: + istio: ingressgateway + servers: + - hosts: + - "*" + port: + name: http + number: {{ $servicePort }} + protocol: HTTP +--- +{{- if empty $.Values.shipaApi.serviceSecurePorts }} +apiVersion: networking.istio.io/v1beta1 +kind: DestinationRule +metadata: + labels: {{- include "shipa.labels" $ | nindent 4 }} + name: {{ template "shipa.fullname" $ }}-api-rule-{{ $i }} +spec: + host: {{ template "shipa.fullname" $ }}-api + subsets: + - labels: + app: {{ template "shipa.fullname" $ }}-api + version: "1" + name: v1 +--- +{{- end }} +{{- end }} +{{- range $j, $cname := splitList "," (trimPrefix "\n" (include "shipa.cnames" $)) }} +apiVersion: networking.istio.io/v1beta1 +kind: VirtualService +metadata: + annotations: + kubernetes.io/ingress.class: {{ default ( "istio" ) $.Values.shipaCluster.ingress.className }} +{{- if $.Values.shipaApi.customIngressAnnotations }} +{{ toYaml $.Values.shipaApi.customIngressAnnotations | indent 4 }} +{{- end }} + labels: {{- include "shipa.labels" $ | nindent 4 }} + name: {{ template "shipa.fullname" $ }}-api-http-virutal-service-cname-{{ $i }}-{{ $j }} +spec: + gateways: + - {{ template "shipa.fullname" $ }}-api-http-gateway-cname-{{ $i }}-{{ $j }} + hosts: + - {{ $cname }} + http: + - route: + - destination: + host: {{ template "shipa.fullname" $ }}-api + port: + number: {{ $servicePort }} + weight: 100 +--- +apiVersion: networking.istio.io/v1beta1 +kind: Gateway +metadata: + labels: {{- include "shipa.labels" $ | nindent 4 }} + name: {{ template "shipa.fullname" $ }}-api-http-gateway-cname-{{ $i }}-{{ $j }} +spec: + selector: + istio: ingressgateway + servers: + - hosts: + - {{ $cname }} + port: + name: http + number: {{ $servicePort }} + protocol: HTTP +--- +{{- if empty $.Values.shipaApi.serviceSecurePorts }} +apiVersion: networking.istio.io/v1beta1 +kind: DestinationRule +metadata: + labels: {{- include "shipa.labels" $ | nindent 4 }} + name: {{ template "shipa.fullname" $ }}-api-rule-cname-{{ $i }}-{{ $j }} +spec: + host: {{ template "shipa.fullname" $ }}-api + subsets: + - labels: + app: {{ template "shipa.fullname" $ }}-api + version: "1" + name: v1 +--- +{{- end }} +{{- end }} +{{- end }} +{{- end }} +{{- range $i, $servicePort := .Values.shipaApi.serviceSecurePorts }} +{{- if $.Values.shipaCluster.ingress.apiAccessOnIngressIp }} +apiVersion: networking.istio.io/v1beta1 +kind: VirtualService +metadata: + annotations: + kubernetes.io/ingress.class: {{ default ( "istio" ) $.Values.shipaCluster.ingress.className }} +{{- if $.Values.shipaApi.customIngressAnnotations }} +{{ toYaml $.Values.shipaApi.customIngressAnnotations | indent 4 }} +{{- end }} + labels: {{- include "shipa.labels" $ | nindent 4 }} + name: {{ template "shipa.fullname" $ }}-api-https-virutal-service-{{ $i }} +spec: + gateways: + - {{ template "shipa.fullname" $ }}-api-https-gateway-{{ $i }} + hosts: + - "*" + http: + - route: + - destination: + host: {{ template "shipa.fullname" $ }}-api + port: + number: {{ $servicePort }} + weight: 100 +--- +apiVersion: networking.istio.io/v1beta1 +kind: Gateway +metadata: + labels: {{- include "shipa.labels" $ | nindent 4 }} + name: {{ template "shipa.fullname" $ }}-api-https-gateway-{{ $i }} +spec: + selector: + istio: ingressgateway + servers: + - hosts: + - "*" + port: + name: https + number: {{ $servicePort }} + protocol: HTTPS + tls: + mode: SIMPLE + {{ if $.Values.shipaApi.customSecretName}} + credentialName: {{ $.Values.shipaApi.customSecretName }} + {{- else }} + credentialName: {{ template "shipa.fullname" $ }}-api-ingress-secret + {{- end }} +--- +apiVersion: networking.istio.io/v1beta1 +kind: DestinationRule +metadata: + labels: {{- include "shipa.labels" $ | nindent 4 }} + name: {{ template "shipa.fullname" $ }}-api-rule-{{ $i }} +spec: + host: {{ template "shipa.fullname" $ }}-api + subsets: + - labels: + app: {{ template "shipa.fullname" $ }}-api + version: "1" + name: v1 + trafficPolicy: + loadBalancer: + simple: ROUND_ROBIN + portLevelSettings: + - port: + number: {{ $servicePort }} + tls: + mode: SIMPLE +--- +{{- end }} +{{- range $j, $cname := splitList "," (trimPrefix "\n" (include "shipa.cnames" $)) }} +apiVersion: networking.istio.io/v1beta1 +kind: VirtualService +metadata: + annotations: + kubernetes.io/ingress.class: {{ default ( "istio" ) $.Values.shipaCluster.ingress.className }} +{{- if $.Values.shipaApi.customIngressAnnotations }} +{{ toYaml $.Values.shipaApi.customIngressAnnotations | indent 4 }} +{{- end }} + labels: {{- include "shipa.labels" $ | nindent 4 }} + name: {{ template "shipa.fullname" $ }}-api-https-virutal-service-cname-{{ $i }}-{{ $j }} +spec: + gateways: + - {{ template "shipa.fullname" $ }}-api-https-gateway-cname-{{ $i }}-{{ $j }} + hosts: + - {{ $cname }} + http: + - route: + - destination: + host: {{ template "shipa.fullname" $ }}-api + port: + number: {{ $servicePort }} + weight: 100 +--- +apiVersion: networking.istio.io/v1beta1 +kind: Gateway +metadata: + labels: {{- include "shipa.labels" $ | nindent 4 }} + name: {{ template "shipa.fullname" $ }}-api-https-gateway-cname-{{ $i }}-{{ $j }} +spec: + selector: + istio: ingressgateway + servers: + - hosts: + - {{ $cname }} + port: + name: https + number: {{ $servicePort }} + protocol: HTTPS + tls: + mode: SIMPLE + {{ if $.Values.shipaApi.customSecretName}} + credentialName: {{ $.Values.shipaApi.customSecretName }} + {{- else }} + credentialName: {{ template "shipa.fullname" $ }}-api-ingress-secret + {{- end }} +--- +apiVersion: networking.istio.io/v1beta1 +kind: DestinationRule +metadata: + labels: {{- include "shipa.labels" $ | nindent 4 }} + name: {{ template "shipa.fullname" $ }}-api-rule-cname-{{ $i }}-{{ $j }} +spec: + host: {{ template "shipa.fullname" $ }}-api + subsets: + - labels: + app: {{ template "shipa.fullname" $ }}-api + version: "1" + name: v1 + trafficPolicy: + loadBalancer: + simple: ROUND_ROBIN + portLevelSettings: + - port: + number: {{ $servicePort }} + tls: + mode: SIMPLE +--- +{{- end }} +{{- end }} +{{- if or (.Values.tags.defaultDB) (.Values.tags.legacyMongoReplicaset) }} +apiVersion: security.istio.io/v1beta1 +kind: PeerAuthentication +metadata: + name: {{ template "shipa.fullname" $ }}-mongodb-peer +spec: + mtls: + mode: DISABLE +--- +apiVersion: networking.istio.io/v1beta1 +kind: DestinationRule +metadata: + name: {{ template "shipa.fullname" $ }}-mongo-rule +spec: +{{- if .Values.tags.defaultDB }} + host: "{{ template "shipa.fullname" $ }}-mongodb.{{ .Release.Namespace }}.svc.{{ .Values.shipaCluster.clusterDomain }}" +{{- else if .Values.tags.legacyMongoReplicaset }} + host: "{{ template "shipa.fullname" $ }}-mongodb-replicaset.{{ .Release.Namespace }}.svc.{{ .Values.shipaCluster.clusterDomain }}" +{{- end }} + trafficPolicy: + tls: + mode: DISABLE +{{ else }} +apiVersion: networking.istio.io/v1alpha3 +kind: ServiceEntry +metadata: + name: mongo +spec: + hosts: +{{- range $mongoShard := (splitList "," $.Values.externalMongodb.url) }} + - {{ trimSuffix ":27017" $mongoShard }} +{{- end }} + ports: + - number: 27017 + name: tls + protocol: TLS + resolution: DNS +{{- end }} +{{- end }} diff --git a/packages/shipa/charts/templates/api-nginx-resources.yaml b/packages/shipa/charts/templates/api-nginx-resources.yaml new file mode 100644 index 000000000..91527fa14 --- /dev/null +++ b/packages/shipa/charts/templates/api-nginx-resources.yaml @@ -0,0 +1,107 @@ +{{ if eq .Values.shipaCluster.ingress.type "nginx" }} +kind: ConfigMap +apiVersion: v1 +metadata: + name: {{ template "shipa.fullname" . }}-nginx-tcp-services + labels: {{- include "shipa.labels" . | nindent 4 }} + shipa.io/shipa-api-ingress-controller: "true" +data: +{{- if not .Values.shipaApi.secureIngressOnly }} +{{- range $servicePort := without (.Values.shipaApi.servicePorts | toStrings) "80" }} + {{ $servicePort }}: "{{ $.Release.Namespace }}/{{ include "shipa.fullname" $ }}-api:{{ $servicePort }}" +{{- end }} +{{- end }} +{{- range $secureContainerPort := without (.Values.shipaApi.serviceSecurePorts | toStrings) "443" }} + {{ $secureContainerPort }}: "{{ $.Release.Namespace }}/{{ include "shipa.fullname" $ }}-api:{{ $secureContainerPort }}" +{{- end }} +--- +{{- if has "80" (.Values.shipaApi.servicePorts | toStrings) }} +{{- if .Values.shipaCluster.ingress.apiAccessOnIngressIp }} +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: {{ template "shipa.fullname" . }}-api-http-ingress + labels: {{- include "shipa.labels" . | nindent 4 }} + annotations: +{{- if $.Values.shipaApi.customIngressAnnotations }} +{{ toYaml $.Values.shipaApi.customIngressAnnotations | indent 4 }} +{{- end }} + nginx.org/websocket-services: "{{ template "shipa.fullname" . }}-api" +{{- if and $.Values.shipaApi.secureIngressOnly (has "443" ($.Values.shipaApi.serviceSecurePorts | toStrings)) }} + nginx.ingress.kubernetes.io/force-ssl-redirect: "true" + nginx.ingress.kubernetes.io/ssl-redirect: "true" + ingress.kubernetes.io/force-ssl-redirect: "true" + ingress.kubernetes.io/ssl-redirect: "true" +{{- else }} + nginx.ingress.kubernetes.io/ssl-redirect: "false" + ingress.kubernetes.io/ssl-redirect: "false" +{{- end }} +spec: + ingressClassName: {{ default (include "shipa.defaultNginxClassName" . | trim) .Values.shipaCluster.ingress.className }} + rules: + - http: + paths: + - backend: + service: + name: {{ template "shipa.fullname" . }}-api + port: + number: 80 + path: / + pathType: Prefix +{{ if has "443" (.Values.shipaApi.serviceSecurePorts | toStrings) }} + tls: + - secretName: {{ template "shipa.fullname" . }}-api-ingress-secret +{{- end }} +{{- end }} +{{- end }} +--- +{{ if not (empty (trimPrefix "\n" (include "shipa.cnames" .))) }} +{{- range $i, $cname := splitList "," (trimPrefix "\n" (include "shipa.cnames" .)) }} +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: {{ template "shipa.fullname" $ }}-api-http-ingress-cname-{{ $i }} + labels: {{- include "shipa.labels" $ | nindent 4 }} + annotations: +{{- if $.Values.shipaApi.customIngressAnnotations }} +{{ toYaml $.Values.shipaApi.customIngressAnnotations | indent 4 }} +{{- end }} + {{- if and $.Values.shipaApi.secureIngressOnly (has "443" ($.Values.shipaApi.serviceSecurePorts | toStrings)) }} + nginx.ingress.kubernetes.io/force-ssl-redirect: "true" + nginx.ingress.kubernetes.io/ssl-redirect: "true" + ingress.kubernetes.io/force-ssl-redirect: "true" + ingress.kubernetes.io/ssl-redirect: "true" + {{- else }} + nginx.ingress.kubernetes.io/ssl-redirect: "false" + ingress.kubernetes.io/ssl-redirect: "false" + {{- end }} + nginx.org/websocket-services: "{{ template "shipa.fullname" $ }}-api" +spec: + ingressClassName: {{ default ( include "shipa.defaultNginxClassName" $ | trim) $.Values.shipaCluster.ingress.className }} + rules: + - host: {{ $cname }} + http: + paths: + - backend: + service: + name: {{ template "shipa.fullname" $ }}-api + port: + number: 80 + path: / + pathType: ImplementationSpecific +{{ if has "443" ($.Values.shipaApi.serviceSecurePorts | toStrings) }} +{{ if $.Values.shipaApi.customSecretName}} + tls: + - secretName: {{ $.Values.shipaApi.customSecretName }} + hosts: + - {{ $cname }} +{{- else }} + tls: + - secretName: {{ template "shipa.fullname" $ }}-api-ingress-secret + hosts: + - {{ $cname }} +{{- end }} +{{- end }} +{{- end }} +{{- end }} +{{- end }} diff --git a/packages/shipa/charts/templates/api-traefik-resources.yaml b/packages/shipa/charts/templates/api-traefik-resources.yaml new file mode 100644 index 000000000..a33223ace --- /dev/null +++ b/packages/shipa/charts/templates/api-traefik-resources.yaml @@ -0,0 +1,108 @@ +{{ if eq .Values.shipaCluster.ingress.type "traefik" }} +{{- if not .Values.shipaApi.secureIngressOnly }} +{{- range $i, $servicePort := .Values.shipaApi.servicePorts }} +{{- if $.Values.shipaCluster.ingress.apiAccessOnIngressIp }} +apiVersion: traefik.containo.us/v1alpha1 +kind: IngressRoute +metadata: + name: {{ template "shipa.fullname" $ }}-api-http-ingress-{{ $i }} + labels: {{- include "shipa.labels" $ | nindent 4 }} +{{- if $.Values.shipaApi.customIngressAnnotations }} + annotations: +{{ toYaml $.Values.shipaApi.customIngressAnnotations | indent 4 }} +{{- end }} +spec: + entryPoints: + - web + routes: + - match: PathPrefix(`/`) + kind: Rule + services: + - name: {{ template "shipa.fullname" $ }}-api + port: {{ $servicePort }} + scheme: http +--- +{{- end }} +{{- range $j, $cname := splitList "," (trimPrefix "\n" (include "shipa.cnames" $)) }} +apiVersion: traefik.containo.us/v1alpha1 +kind: IngressRoute +metadata: + name: {{ template "shipa.fullname" $ }}-api-http-ingress-cname-{{ $i }}-{{ $j }} + labels: {{- include "shipa.labels" $ | nindent 4 }} +{{- if $.Values.shipaApi.customIngressAnnotations }} + annotations: +{{ toYaml $.Values.shipaApi.customIngressAnnotations | indent 4 }} +{{- end }} +spec: + entryPoints: + - web + routes: + - match: Host(`{{ $cname }}`) + kind: Rule + services: + - name: {{ template "shipa.fullname" $ }}-api + port: {{ $servicePort }} + scheme: http +--- +{{- end }} +{{- end }} +{{- end }} +{{- if $.Values.shipaCluster.ingress.apiAccessOnIngressIp }} +apiVersion: traefik.containo.us/v1alpha1 +kind: IngressRoute +metadata: + name: {{ template "shipa.fullname" $ }}-api-https-ingress + labels: {{- include "shipa.labels" $ | nindent 4 }} +{{- if $.Values.shipaApi.customIngressAnnotations }} + annotations: +{{ toYaml $.Values.shipaApi.customIngressAnnotations | indent 4 }} +{{- end }} +spec: + entryPoints: + - websecure + routes: + - match: PathPrefix(`/`) + kind: Rule + services: + - name: {{ template "shipa.fullname" $ }}-api + port: {{ first .Values.shipaApi.servicePorts }} + scheme: http + tls: + {{ if $.Values.shipaApi.customSecretName}} + secretName: {{ $.Values.shipaApi.customSecretName }} + {{- else }} + secretName: {{ template "shipa.fullname" $ }}-api-ingress-secret + {{- end }} +--- +{{- end }} +{{- range $i, $cname := splitList "," (trimPrefix "\n" (include "shipa.cnames" $)) }} +apiVersion: traefik.containo.us/v1alpha1 +kind: IngressRoute +metadata: + name: {{ template "shipa.fullname" $ }}-api-https-ingress-cname-{{ $i }} + labels: {{- include "shipa.labels" $ | nindent 4 }} +{{- if $.Values.shipaApi.customIngressAnnotations }} + annotations: +{{ toYaml $.Values.shipaApi.customIngressAnnotations | indent 4}} +{{- end }} +spec: + entryPoints: + - websecure + routes: + - match: Host(`{{ $cname }}`) + kind: Rule + services: + - name: {{ template "shipa.fullname" $ }}-api + port: {{ first $.Values.shipaApi.servicePorts }} + scheme: http + tls: + {{ if $.Values.shipaApi.customSecretName}} + secretName: {{ $.Values.shipaApi.customSecretName }} + {{- else }} + secretName: {{ template "shipa.fullname" $ }}-api-ingress-secret + {{- end }} + domains: + - main: {{ $cname }} +--- +{{- end }} +{{- end }} \ No newline at end of file diff --git a/packages/shipa/charts/templates/clair-configmap.yaml b/packages/shipa/charts/templates/clair-configmap.yaml new file mode 100644 index 000000000..97a94abf5 --- /dev/null +++ b/packages/shipa/charts/templates/clair-configmap.yaml @@ -0,0 +1,86 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ template "shipa.fullname" . }}-clair-config + labels: {{- include "shipa.labels" . | nindent 4 }} +data: + config.template.yaml: |- + # + # This file is mounted to /clair-config/config.template.yaml and then processed by /entrypoint.sh + # + clair: + database: + # Database driver + type: pgsql + options: + # PostgreSQL Connection string + # https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING + {{- $host := (default (printf "%s-postgres.%s" (include "shipa.fullname" .) .Release.Namespace) .Values.postgres.source.host) }} + {{- $port := .Values.postgres.source.port }} + {{- $user := .Values.postgres.source.user }} + {{- $sslmode := .Values.postgres.source.sslmode }} + source: host={{ $host }} port={{ $port }} user={{ $user }} sslmode={{ $sslmode }} statement_timeout=60000 password=$POSTGRES_PASSWORD + + # Number of elements kept in the cache + # Values unlikely to change (e.g. namespaces) are cached in order to save prevent needless roundtrips to the database. + cachesize: 16384 + + # 32-bit URL-safe base64 key used to encrypt pagination tokens + # If one is not provided, it will be generated. + # Multiple clair instances in the same cluster need the same value. + paginationkey: + + api: + # v3 grpc/RESTful API server address + addr: "0.0.0.0:6060" + + # Health server address + # This is an unencrypted endpoint useful for load balancers to check to healthiness of the clair server. + healthaddr: "0.0.0.0:6061" + + # Deadline before an API request will respond with a 503 + timeout: 900s + + # Optional PKI configuration + # If you want to easily generate client certificates and CAs, try the following projects: + # https://github.com/coreos/etcd-ca + # https://github.com/cloudflare/cfssl + servername: + cafile: + keyfile: + certfile: + + updater: + # Frequency the database will be updated with vulnerabilities from the default data sources + # The value 0 disables the updater entirely. + interval: 2h + enabledupdaters: + - debian + - ubuntu + - rhel + - oracle + - alpine + - suse + + notifier: + # Number of attempts before the notification is marked as failed to be sent + attempts: 3 + + # Duration before a failed notification is retried + renotifyinterval: 2h + + http: + # Optional endpoint that will receive notifications via POST requests + endpoint: + + # Optional PKI configuration + # If you want to easily generate client certificates and CAs, try the following projects: + # https://github.com/cloudflare/cfssl + # https://github.com/coreos/etcd-ca + servername: + cafile: + keyfile: + certfile: + + # Optional HTTP Proxy: must be a valid URL (including the scheme). + proxy: diff --git a/packages/shipa/charts/templates/clair-deployment.yaml b/packages/shipa/charts/templates/clair-deployment.yaml new file mode 100644 index 000000000..c4258bf40 --- /dev/null +++ b/packages/shipa/charts/templates/clair-deployment.yaml @@ -0,0 +1,59 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ template "shipa.fullname" . }}-clair + labels: {{- include "shipa.labels" . | nindent 4 }} + annotations: + sidecar.istio.io/inject: "false" +spec: + selector: + matchLabels: + name: {{ template "shipa.fullname" . }}-clair + template: + metadata: + labels: + name: {{ template "shipa.fullname" . }}-clair + annotations: + sidecar.istio.io/inject: "false" + spec: + nodeSelector: + kubernetes.io/os: linux + containers: + - name: clair + {{- if .Values.clair.image }} + image: "{{ .Values.clair.image }}" + {{- else }} + image: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.clair.repositoryBasename }}:{{ .Values.clair.tag }}" + {{- end }} + imagePullPolicy: IfNotPresent + ports: + - name: clair + containerPort: 6060 + protocol: TCP + - name: health + containerPort: 6061 + protocol: TCP + volumeMounts: + - name: {{ template "shipa.fullname" . }}-clair-config + mountPath: /clair-config/ + - name: config-dir + mountPath: /etc/clair/ + env: + - name: POSTGRES_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-secret + key: postgres-password + {{- if .Values.imagePullSecrets }} + imagePullSecrets: + - name: {{ .Values.imagePullSecrets }} + {{- end }} + volumes: + - name: config-dir + emptyDir: {} + - name: {{ template "shipa.fullname" . }}-clair-config + configMap: + name: {{ template "shipa.fullname" . }}-clair-config + items: + - key: config.template.yaml + path: config.template.yaml diff --git a/packages/shipa/charts/templates/clair-service.yaml b/packages/shipa/charts/templates/clair-service.yaml new file mode 100644 index 000000000..a0bbd8faa --- /dev/null +++ b/packages/shipa/charts/templates/clair-service.yaml @@ -0,0 +1,18 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ template "shipa.fullname" . }}-clair + labels: {{- include "shipa.labels" . | nindent 4 }} +spec: + type: ClusterIP + selector: + name: {{ template "shipa.fullname" . }}-clair + ports: + - port: 6060 + targetPort: 6060 + protocol: TCP + name: clair + - port: 6061 + targetPort: 6061 + protocol: TCP + name: health diff --git a/packages/shipa/charts/templates/metrics-configmap.yaml b/packages/shipa/charts/templates/metrics-configmap.yaml new file mode 100644 index 000000000..b7cd013f5 --- /dev/null +++ b/packages/shipa/charts/templates/metrics-configmap.yaml @@ -0,0 +1,36 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ template "shipa.fullname" . }}-metrics-config + labels: {{- include "shipa.labels" . | nindent 4 }} +data: + prometheus.yml: |- + # + # DO NOT EDIT. Can be updated by shipa helm chart + # + global: + scrape_interval: 1m + + scrape_configs: + - job_name: "pushgateway" + honor_labels: true + scheme: http + static_configs: + - targets: ['127.0.0.1:9093'] + labels: + source: pushgateway + + - job_name: "traefik" + honor_labels: true + scheme: http + static_configs: + - targets: ['{{ template "shipa.fullname" . }}-traefik-internal.{{ .Release.Namespace }}:9095'] + + {{- if .Values.metrics.extraPrometheusConfiguration }} + # + # User defined extra configuration + # + {{- range $line, $value := ( split "\n" .Values.metrics.extraPrometheusConfiguration ) }} + {{ $value }} + {{- end }} + {{- end }} diff --git a/packages/shipa/charts/templates/metrics-deployment.yaml b/packages/shipa/charts/templates/metrics-deployment.yaml new file mode 100644 index 000000000..bb2770b6d --- /dev/null +++ b/packages/shipa/charts/templates/metrics-deployment.yaml @@ -0,0 +1,59 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ template "shipa.fullname" . }}-metrics + labels: {{- include "shipa.labels" . | nindent 4 }} + annotations: + sidecar.istio.io/inject: "false" +spec: + selector: + matchLabels: + name: {{ template "shipa.fullname" . }}-metrics + template: + metadata: + labels: + name: {{ template "shipa.fullname" . }}-metrics + annotations: + sidecar.istio.io/inject: "false" + spec: + nodeSelector: + kubernetes.io/os: linux + containers: + # Please do not scale metrics container. It doesn't use storage lock (--storage.tsdb.no-lockfile) + - name: metrics + {{- if .Values.metrics.image }} + image: "{{ .Values.metrics.image }}" + {{- else }} + image: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.metrics.repositoryBasename }}:{{ .Values.metrics.tag }}" + {{- end }} + imagePullPolicy: {{ .Values.metrics.pullPolicy }} + env: + - name: PROMETHEUS_ARGS + value: "--web.enable-admin-api {{ default ("--storage.tsdb.retention.time=1d") .Values.metrics.prometheusArgs }}" + - name: METRICS_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-secret + key: metrics-password + ports: + - name: prometheus + containerPort: 9090 + protocol: TCP + - name: pushgateway + containerPort: 9091 + protocol: TCP + volumeMounts: + - name: "{{ template "shipa.fullname" . }}-metrics-config" + mountPath: /etc/prometheus/config + + {{- if .Values.imagePullSecrets }} + imagePullSecrets: + - name: {{ .Values.imagePullSecrets }} + {{- end }} + volumes: + - name: {{ template "shipa.fullname" . }}-metrics-config + configMap: + name: {{ template "shipa.fullname" . }}-metrics-config + items: + - key: prometheus.yml + path: prometheus.yml diff --git a/packages/shipa/charts/templates/metrics-service.yaml b/packages/shipa/charts/templates/metrics-service.yaml new file mode 100644 index 000000000..2371f76bb --- /dev/null +++ b/packages/shipa/charts/templates/metrics-service.yaml @@ -0,0 +1,18 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ template "shipa.fullname" . }}-metrics + labels: {{- include "shipa.labels" . | nindent 4 }} +spec: + type: ClusterIP + selector: + name: {{ template "shipa.fullname" . }}-metrics + ports: + - port: 9090 + targetPort: 9090 + protocol: TCP + name: prometheus + - port: 9091 + targetPort: 9091 + protocol: TCP + name: pushgateway diff --git a/packages/shipa/charts/templates/nginx-configmap.yaml b/packages/shipa/charts/templates/nginx-configmap.yaml new file mode 100644 index 000000000..060f57594 --- /dev/null +++ b/packages/shipa/charts/templates/nginx-configmap.yaml @@ -0,0 +1,20 @@ +{{ if and (eq .Values.shipaCluster.ingress.type "nginx") (not .Values.shipaCluster.ingress.ip) }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ template "shipa.fullname" . }}-nginx + labels: {{- include "shipa.labels" . | nindent 4 }} + shipa.io/shipa-api-ingress-controller: "true" +data: + {{- if .Values.shipaCluster.ingress.config }} + {{- range $key, $value := .Values.shipaCluster.ingress.config }} + {{ $key }}: {{ $value }} + {{- end }} + {{- else }} + proxy-body-size: "512M" + proxy-read-timeout: "300" + proxy-connect-timeout: "300" + proxy-send-timeout: "300" + upstream-keepalive-timeout: "300" + {{- end }} +{{- end }} \ No newline at end of file diff --git a/packages/shipa/charts/templates/nginx-deployment.yaml b/packages/shipa/charts/templates/nginx-deployment.yaml new file mode 100644 index 000000000..cd2adb5af --- /dev/null +++ b/packages/shipa/charts/templates/nginx-deployment.yaml @@ -0,0 +1,99 @@ +{{ if and (eq .Values.shipaCluster.ingress.type "nginx") (not .Values.shipaCluster.ingress.ip) }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ template "shipa.fullname" . }}-nginx-ingress + labels: {{- include "shipa.labels" . | nindent 4 }} + shipa.io/shipa-api-ingress-controller: "true" + shipa.io/component: nginx + shipa.io/cluster: shipa-cluster + annotations: + sidecar.istio.io/inject: "false" +spec: + replicas: 1 + selector: + matchLabels: + name: {{ template "shipa.fullname" . }}-nginx-ingress + template: + metadata: + labels: + name: {{ template "shipa.fullname" . }}-nginx-ingress + shipa.io/component: nginx + shipa.io/cluster: shipa-cluster + annotations: + sidecar.istio.io/inject: "false" + prometheus.io/port: "10254" + prometheus.io/scrape: "true" + spec: + # wait up to 30 seconds for the drain of connections + terminationGracePeriodSeconds: 30 + serviceAccountName: {{ template "shipa.fullname" . }}-nginx-ingress-serviceaccount + nodeSelector: + kubernetes.io/os: linux + containers: + - name: nginx-ingress-controller + image: {{ .Values.shipaCluster.ingress.image }} + args: + - /nginx-ingress-controller + - --election-id={{ template "shipa.fullname" . }}-leader + - --configmap=$(POD_NAMESPACE)/{{ template "shipa.fullname" . }}-nginx + - --tcp-services-configmap=$(POD_NAMESPACE)/{{ template "shipa.fullname" . }}-nginx-tcp-services + - --publish-service=$(POD_NAMESPACE)/{{ template "shipa.fullname" . }}-ingress-nginx + - --ingress-class={{ default ( include "shipa.defaultNginxClassName" . | trim) .Values.shipaCluster.ingress.className }} + - --default-ssl-certificate={{ .Release.Namespace }}/{{ template "shipa.fullname" . }}-api-ingress-secret + - --controller-class=k8s.io/internal-ingress-nginx + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + add: + - NET_BIND_SERVICE + runAsUser: 101 + env: + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + ports: + {{- if not .Values.shipaApi.secureIngressOnly }} + {{ range $i, $servicePort := .Values.shipaApi.servicePorts }} + - name: shipa-{{ $i }} + containerPort: {{ $servicePort }} + protocol: TCP + {{- end }} + {{- end }} + {{ range $i, $servicePort := .Values.shipaApi.serviceSecurePorts }} + - name: shipa-secure-{{ $i }} + containerPort: {{ $servicePort }} + protocol: TCP + {{- end }} + livenessProbe: + failureThreshold: 3 + httpGet: + path: /healthz + port: 10254 + scheme: HTTP + initialDelaySeconds: 10 + periodSeconds: 10 + successThreshold: 1 + timeoutSeconds: 10 + readinessProbe: + failureThreshold: 3 + httpGet: + path: /healthz + port: 10254 + scheme: HTTP + periodSeconds: 10 + successThreshold: 1 + timeoutSeconds: 10 + lifecycle: + preStop: + exec: + command: + - /wait-shutdown +{{- end }} \ No newline at end of file diff --git a/packages/shipa/charts/templates/nginx-ingressclass.yaml b/packages/shipa/charts/templates/nginx-ingressclass.yaml new file mode 100644 index 000000000..5a09a4be5 --- /dev/null +++ b/packages/shipa/charts/templates/nginx-ingressclass.yaml @@ -0,0 +1,8 @@ +{{ if and (eq .Values.shipaCluster.ingress.type "nginx") (not .Values.shipaCluster.ingress.ip) }} +apiVersion: networking.k8s.io/v1 +kind: IngressClass +metadata: + name: {{ default ( include "shipa.defaultNginxClassName" . | trim) .Values.shipaCluster.ingress.className }} +spec: + controller: k8s.io/internal-ingress-nginx +{{- end }} \ No newline at end of file diff --git a/packages/shipa/charts/templates/nginx-rbac.yaml b/packages/shipa/charts/templates/nginx-rbac.yaml new file mode 100644 index 000000000..4d52e7e07 --- /dev/null +++ b/packages/shipa/charts/templates/nginx-rbac.yaml @@ -0,0 +1,131 @@ +{{ if and (eq .Values.shipaCluster.ingress.type "nginx") (not .Values.shipaCluster.ingress.ip) }} +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ template "shipa.fullname" . }}-nginx-ingress-clusterrole + labels: {{- include "shipa.labels" . | nindent 4 }} + shipa.io/shipa-api-ingress-controller: "true" +rules: + - apiGroups: + - "" + resources: + - configmaps + - endpoints + - nodes + - pods + - secrets + verbs: + - list + - watch + - apiGroups: + - "" + resources: + - configmaps + verbs: + - update + - apiGroups: + - "" + resources: + - nodes + verbs: + - get + - apiGroups: + - "" + resources: + - services + verbs: + - get + - list + - watch + - apiGroups: + - "" + resources: + - events + verbs: + - create + - patch + - apiGroups: + - "extensions" + - "networking.k8s.io" + resources: + - ingresses + - ingressclasses + verbs: + - get + - list + - watch + - apiGroups: + - "networking.k8s.io" + resources: + - ingresses/status + verbs: + - update + +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ template "shipa.fullname" . }}-nginx-ingress-role + labels: {{- include "shipa.labels" . | nindent 4 }} +rules: + - apiGroups: + - "" + resources: + - configmaps + - pods + - secrets + - namespaces + verbs: + - get + - apiGroups: + - "" + resources: + - configmaps + resourceNames: + - "{{ template "shipa.fullname" . }}-leader-nginx" + verbs: + - get + - update + - apiGroups: + - "" + resources: + - configmaps + verbs: + - create + - apiGroups: + - "" + resources: + - endpoints + verbs: + - get + +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ template "shipa.fullname" . }}-nginx-ingress-role-nisa-binding + labels: {{- include "shipa.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ template "shipa.fullname" . }}-nginx-ingress-role +subjects: + - kind: ServiceAccount + name: {{ template "shipa.fullname" . }}-nginx-ingress-serviceaccount + namespace: {{ .Release.Namespace }} + +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ template "shipa.fullname" . }}-nginx-ingress-clusterrole-nisa-binding + labels: {{- include "shipa.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ template "shipa.fullname" . }}-nginx-ingress-clusterrole +subjects: + - kind: ServiceAccount + name: {{ template "shipa.fullname" . }}-nginx-ingress-serviceaccount + namespace: {{ .Release.Namespace }} +{{- end }} \ No newline at end of file diff --git a/packages/shipa/charts/templates/nginx-service.yaml b/packages/shipa/charts/templates/nginx-service.yaml new file mode 100644 index 000000000..414d480bf --- /dev/null +++ b/packages/shipa/charts/templates/nginx-service.yaml @@ -0,0 +1,59 @@ +{{ if and (eq .Values.shipaCluster.ingress.type "nginx") (not .Values.shipaCluster.ingress.ip) }} +apiVersion: v1 +kind: Service +metadata: + name: {{ template "shipa.fullname" . }}-ingress-nginx + labels: {{- include "shipa.labels" . | nindent 4 }} + shipa.io/shipa-api-ingress-controller: "true" + annotations: +{{- if $.Values.shipaCluster.ingress.customNginxServiceAnnotations }} +{{ toYaml $.Values.shipaCluster.ingress.customNginxServiceAnnotations | indent 4 }} +{{- end }} +spec: + type: "{{ .Values.shipaCluster.ingress.serviceType }}" + {{- if eq .Values.shipaCluster.ingress.serviceType "LoadBalancer" }} + {{- if .Values.shipaCluster.ingress.loadBalancerIp }} + loadBalancerIP: "{{ .Values.shipaCluster.ingress.loadBalancerIp }}" + {{- end }} + {{- end }} + {{- if eq .Values.shipaCluster.ingress.serviceType "ClusterIP" }} + {{- if .Values.shipaCluster.ingress.clusterIp }} + clusterIP: "{{ .Values.shipaCluster.ingress.clusterIp }}" + {{- end }} + {{- end }} + selector: + name: {{ template "shipa.fullname" . }}-nginx-ingress + ports: + - name: http + port: 80 + protocol: TCP + targetPort: 80 + - name: https + port: 443 + protocol: TCP + targetPort: 443 + {{- if not .Values.shipaApi.secureIngressOnly }} + {{- range $i, $servicePort := without (.Values.shipaApi.servicePorts | toStrings) "80" }} + - port: {{ $servicePort }} + name: shipa-{{ $i }} + targetPort: {{ $.Values.shipaApi.port }} + protocol: TCP + {{- if eq $.Values.shipaCluster.ingress.serviceType "NodePort" }} + {{- if $.Values.shipaCluster.ingress.nodePort }} + nodePort: {{ $.Values.shipaCluster.ingress.nodePort }} + {{- end }} + {{- end }} + {{- end }} + {{- end }} + {{- range $i, $servicePort := without (.Values.shipaApi.serviceSecurePorts | toStrings) "443" }} + - port: {{ $servicePort }} + name: shipa-secure-{{ $i }} + targetPort: {{ $.Values.shipaApi.securePort }} + protocol: TCP + {{- if eq $.Values.shipaCluster.ingress.serviceType "NodePort" }} + {{- if $.Values.shipaCluster.ingress.nodePort }} + nodePort: {{ $.Values.shipaCluster.ingress.nodePort }} + {{- end }} + {{- end }} + {{- end }} +{{- end }} \ No newline at end of file diff --git a/packages/shipa/charts/templates/nginx-serviceaccount.yaml b/packages/shipa/charts/templates/nginx-serviceaccount.yaml new file mode 100644 index 000000000..ba9aafc09 --- /dev/null +++ b/packages/shipa/charts/templates/nginx-serviceaccount.yaml @@ -0,0 +1,8 @@ +{{ if and (eq .Values.shipaCluster.ingress.type "nginx") (not .Values.shipaCluster.ingress.ip) }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ template "shipa.fullname" . }}-nginx-ingress-serviceaccount + labels: {{- include "shipa.labels" . | nindent 4 }} + shipa.io/shipa-api-ingress-controller: "true" +{{- end }} diff --git a/packages/shipa/charts/templates/postgres-deployment.yaml b/packages/shipa/charts/templates/postgres-deployment.yaml new file mode 100644 index 000000000..0eb9d1188 --- /dev/null +++ b/packages/shipa/charts/templates/postgres-deployment.yaml @@ -0,0 +1,48 @@ +{{- if .Values.postgres.create }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ template "shipa.fullname" . }}-postgres + labels: {{- include "shipa.labels" . | nindent 4 }} + annotations: + sidecar.istio.io/inject: "false" +spec: + selector: + matchLabels: + name: {{ template "shipa.fullname" . }}-postgres + template: + metadata: + labels: + name: {{ template "shipa.fullname" . }}-postgres + annotations: + sidecar.istio.io/inject: "false" + spec: + nodeSelector: + kubernetes.io/os: linux + containers: + - name: postgres + image: {{ .Values.postgres.image }} + imagePullPolicy: IfNotPresent + ports: + - name: postgres + containerPort: 5432 + protocol: TCP + volumeMounts: + - name: data + mountPath: /var/lib/postgresql/data + subPath: postgres + env: + - name: POSTGRES_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-secret + key: postgres-password + {{- if .Values.imagePullSecrets }} + imagePullSecrets: + - name: {{ .Values.imagePullSecrets }} + {{- end }} + volumes: + - name: data + persistentVolumeClaim: + claimName: {{ template "shipa.fullname" . }}-postgres-pvc +{{- end }} diff --git a/packages/shipa/charts/templates/postgres-pvc.yaml b/packages/shipa/charts/templates/postgres-pvc.yaml new file mode 100644 index 000000000..caf8ef0ba --- /dev/null +++ b/packages/shipa/charts/templates/postgres-pvc.yaml @@ -0,0 +1,20 @@ +{{- if .Values.postgres.create }} +kind: PersistentVolumeClaim +apiVersion: v1 +metadata: + name: {{ template "shipa.fullname" . }}-postgres-pvc + labels: {{- include "shipa.labels" . | nindent 4 }} +spec: + accessModes: + - {{ .Values.postgres.persistence.accessMode | quote }} + resources: + requests: + storage: {{ .Values.postgres.persistence.size | quote }} + {{- if .Values.postgres.persistence.storageClass }} + {{- if (eq "-" .Values.postgres.persistence.storageClass) }} + storageClassName: "" + {{- else }} + storageClassName: "{{ .Values.postgres.persistence.storageClass }}" + {{- end }} + {{- end }} +{{- end }} diff --git a/packages/shipa/charts/templates/postgres-service.yaml b/packages/shipa/charts/templates/postgres-service.yaml new file mode 100644 index 000000000..01ef2dd61 --- /dev/null +++ b/packages/shipa/charts/templates/postgres-service.yaml @@ -0,0 +1,16 @@ +{{- if .Values.postgres.create }} +apiVersion: v1 +kind: Service +metadata: + name: {{ template "shipa.fullname" . }}-postgres + labels: {{- include "shipa.labels" . | nindent 4 }} +spec: + type: ClusterIP + selector: + name: {{ template "shipa.fullname" . }}-postgres + ports: + - port: 5432 + targetPort: 5432 + protocol: TCP + name: postgres +{{- end }} \ No newline at end of file diff --git a/packages/shipa/charts/templates/pre-upgrade-hook.yaml b/packages/shipa/charts/templates/pre-upgrade-hook.yaml new file mode 100644 index 000000000..7de157f86 --- /dev/null +++ b/packages/shipa/charts/templates/pre-upgrade-hook.yaml @@ -0,0 +1,84 @@ +{{- if .Values.tags.defaultDB }} +{{- if .Values.tags.legacyMongoReplicaset }} +{{- fail "tags.defaultDB and tags.legacyMongoReplicaset cannot both be set to true. See https://learn.shipa.io/docs/upgrading-self-managed-shipa" }} +{{- end }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ template "shipa.fullname" . }}-pre-upgrade-config + labels: {{- include "shipa.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": "pre-upgrade" + "helm.sh/hook-weight": "-1" +data: + pre-upgrade.sh: | +{{ .Files.Get "scripts/pre-upgrade.sh" | indent 4 }} +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: "{{ template "shipa.fullname" . }}-pre-upgrade-hook-{{ .Release.Revision }}" + labels: {{- include "shipa.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": "pre-upgrade" + "helm.sh/hook-weight": 0" + "helm.sh/hook-delete-policy": hook-succeeded + sidecar.istio.io/inject: "false" +spec: + backoffLimit: 0 + template: + metadata: + name: "{{ template "shipa.fullname" . }}-pre-upgrade-hook-{{ .Release.Revision }}" + labels: + shipa-hook: "pre-upgrade" + annotations: + sidecar.istio.io/inject: "false" + spec: + nodeSelector: + kubernetes.io/os: linux + terminationGracePeriodSeconds: 3 + {{- if .Values.rbac.enabled }} + serviceAccountName: {{ template "shipa.fullname" . }} + {{- else }} + serviceAccountName: default + {{- end }} + restartPolicy: Never + containers: + - name: pre-upgrade-hook + {{- if .Values.cli.image }} + image: "{{ .Values.cli.image }}" + {{- else }} + image: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.cli.repositoryBasename }}:{{ .Values.cli.tag }}" + {{- end }} + command: + - /scripts/pre-upgrade.sh + imagePullPolicy: {{ .Values.cli.pullPolicy }} + env: + - name: RELEASE_NAME + value: {{ template "shipa.fullname" . }} + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: PERSISTENCE_EXISTING_CLAIM + value: "{{ .Values.mongodb.persistence.existingClaim }}" + - name: PERSISTENCE_SIZE + value: "{{ .Values.mongodb.persistence.size }}" + volumeMounts: + - name: scripts + mountPath: /scripts + - name: scripts-out + mountPath: /etc/shipa/ + {{- if .Values.imagePullSecrets }} + imagePullSecrets: + - name: {{ .Values.imagePullSecrets }} + {{- end }} + volumes: + - name: scripts + configMap: + defaultMode: 0755 + name: {{ template "shipa.fullname" . }}-pre-upgrade-config + - name: scripts-out + emptyDir: {} + +{{- end }} \ No newline at end of file diff --git a/packages/shipa/charts/templates/shipa-api-configmap.yaml b/packages/shipa/charts/templates/shipa-api-configmap.yaml new file mode 100644 index 000000000..075235e1b --- /dev/null +++ b/packages/shipa/charts/templates/shipa-api-configmap.yaml @@ -0,0 +1,190 @@ +{{- if and (.Values.tags.defaultDB) (.Values.tags.legacyMongoReplicaset) }} +{{- fail "tags.defaultDB and tags.legacyMongoReplicaset cannot both be true.\n To use the legacy MongoDB chart set tags.defaultDB to false, tags.legacyMongoReplicaset to true,\n and if upgrading, provide mongodb.persistence.existingClaim to match the existing PVC, which can be found with:\n kubectl get pvc -A -l app=mongodb-replicaset -o jsonpath='{.items[].metadata.name}'\n To use the current MongoDB chart set tags.defaultDB to true, tags.legacyMongoReplicaset to false (these are the default values)" }} +{{- end }} +{{- if and (or .Values.tags.defaultDB .Values.tags.legacyMongoReplicaset) (and (.Values.externalMongodb.url) (ne .Values.externalMongodb.url "< database url >")) }} +{{- fail "externalMongodb.url cannot be set when either tags.defaultDB or tags.legacyMongoReplicaset are true.\n Either set tags.defaultDB and tags.legacyMongoReplicaset to false to use an external MongoDB instance, or remove the value for externalMongodb.url" }} +{{- end }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ template "shipa.fullname" . }}-api-config + labels: {{- include "shipa.labels" . | nindent 4 }} +data: + shipa.conf: |- + shipaVersion: {{ .Chart.Version }} + tls-listen: "0.0.0.0:{{ .Values.shipaApi.securePort }}" + listen: "0.0.0.0:{{ .Values.shipaApi.port }}" + host: https://SHIPA_PUBLIC_IP:{{ first .Values.shipaApi.serviceSecurePorts }} + host-internal: http://{{ template "shipa.fullname" . }}-api.{{ .Release.Namespace }}.svc.{{ .Values.shipaCluster.clusterDomain }}:{{ first .Values.shipaApi.servicePorts }} + use-internal-host: {{ .Values.shipaApi.useInternalHost }} + use-tls: true + shipaCloud: + enabled: {{ .Values.shipaCloud.enabled }} + tls: + server-cert: /certs/api-server.crt + server-key: /certs/api-server.key + + database: + {{- if or (.Values.tags.defaultDB) (.Values.tags.legacyMongoReplicaset) }} + {{- if eq .Values.shipaCluster.ingress.type "istio" }} + {{- if .Values.tags.defaultDB }} + url: {{ .Release.Name }}-mongodb.{{ .Release.Namespace }}.svc.{{ .Values.shipaCluster.clusterDomain }}:{{ .Values.mongodb.service.port }} + {{- else if .Values.tags.legacyMongoReplicaset }} + url: {{ .Release.Name }}-mongodb-replicaset.{{ .Release.Namespace }}.svc.{{ .Values.shipaCluster.clusterDomain }}:{{ .Values.mongodb.service.port }} + {{- end }} + {{ else }} + {{- if .Values.tags.defaultDB }} + url: {{ .Release.Name }}-mongodb:{{ .Values.mongodb.service.port }} + {{- else if .Values.tags.legacyMongoReplicaset }} + url: {{ .Release.Name }}-mongodb-replicaset:{{ .Values.mongodb.service.port }} + {{- end }} + {{- end }} + tls: false + {{ else }} + url: {{ .Values.externalMongodb.url }} + tls: {{ .Values.externalMongodb.tls.enable }} + {{- end }} + name: shipa + username: $DB_USERNAME + password: $DB_PASSWORD + organization: + id: SHIPA_ORGANIZATION_ID + dashboard: + enabled: $DASHBOARD_ENABLED + image: $DASHBOARD_IMAGE + envs: + SHIPA_ADMIN_USER: {{ .Values.auth.adminUser | quote }} + SHIPA_CLOUD: {{ .Values.shipaCloud.enabled | quote }} + SHIPA_TARGETS: {{ trimPrefix "\n" (include "shipa.cnames" .) }} + SHIPA_PAY_API_HOST: {{ .Values.shipaCloud.shipaPayApi.host }} + SHIPA_PAY_API_TOKEN: {{ .Values.shipaCloud.shipaPayApi.token }} + GOOGLE_RECAPTCHA_SITEKEY: {{ .Values.shipaCloud.googleRecaptcha.sitekey }} + GOOGLE_RECAPTCHA_SECRET: {{ .Values.shipaCloud.googleRecaptcha.secret }} + SMARTLOOK_PROJECT_KEY: {{ .Values.shipaCloud.smartlook.projectKey }} + LAUNCH_DARKLY_SDK_KEY: {{ .Values.shipaCloud.launchDarkly.sdkKey }} + SHIPA_API_INTERNAL_URL: http://{{ template "shipa.fullname" . }}-api.{{ .Release.Namespace }}.svc.{{ .Values.shipaCluster.clusterDomain }}:{{ first .Values.shipaApi.servicePorts }} + auth: + admin-email: {{ .Values.auth.adminUser | quote }} + dummy-domain: {{ .Values.auth.dummyDomain | quote }} + token-expire-days: 2 + hash-cost: 4 + user-registration: true + user-activation: + cert: LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUF6TXIwd3hETklDcm9JN3VEVkdoTgpFZytVbTdkQzk3NVZpM1l1NnJHUUdlc3ZwZTY5T2NhT0VxZHFML0NNWGVRMW1oTVFtUnplQnlxWEJ1Q2xOemphCjlEbjV2WTBlVnNIZUhuVTJ4bkkyV1dSR3JjUE1mRGJuRzlDSnNZQmdHd3A2eDcrYVR2RXZCRFBtS3YrcjdOcysKUXhhNzBFZEk4NTZLMWQyTTQ1U3RuZW1hcm51cjdOTDdGb2VsS1FWNGREd1hxU2EvVW1tdHdOOGNSTENUQ0N4NQpObkVya2UrTWo1RFFqTW5TUlRHbjFxOE91azlOUXRxNDlrbFMwMUhIQTJBWnR6ZExteTMrTktXRVZta3Z0cGgxClJseHBtZVQ5SERNbHI5aFI3U3BidnRHeVZVUG1pbXVYWFA4cXdOcHZab01Ka3hWRm4zbWNRVHRMbk8xa0Jjb1cKZVFJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg== + provisioner: kubernetes + metrics: + host: {{ template "shipa.fullname" . }}-metrics + password: $METRICS_PASSWORD + + # section contains configuration of Prometheus Metrics Exporter + prometheus-metrics-exporter: + {{- if .Values.prometheusMetricsExporter.image }} + image: "{{ .Values.prometheusMetricsExporter.image }}" + {{- else }} + image: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.prometheusMetricsExporter.repositoryBasename }}:{{ .Values.prometheusMetricsExporter.tag }}" + {{- end }} + + docker: + cluster: + storage: mongodb + mongo-database: cluster + collection: docker + registry-scheme: https + repository-namespace: shipa + router: traefik + deploy-cmd: /var/lib/shipa/deploy + run-cmd: + bin: /var/lib/shipa/start + port: "8888" + tls: + root-path: /certs + auto-scale: + enabled: true + run-interval: $DOCKER_AUTOSCALE_RUN_INTERVAL + routers: + traefik: + type: traefik + domain: shipa.cloud + istio: + type: istio + nginx: + type: nginx + serviceType: {{ .Values.shipaCluster.ingress.serviceType }} + ip: {{ .Values.shipaCluster.ingress.ip }} + queue: + mongo-database: queuedb + quota: + units-per-app: 4 + apps-per-user: 8 + log: + disable-syslog: true + use-stderr: true + clair: + server: http://{{ template "shipa.fullname" . }}-clair:6060 + disabled: false + kubernetes: + # pod name is used by a leader election thing as an identifier for the current shipa-api instance + pod-name: $POD_NAME + pod-namespace: $POD_NAMESPACE + core-services-address: SHIPA_PUBLIC_IP + use-pool-namespaces: true + remote-cluster-ingress: + http-port: 80 + https-port: 443 + protected-port: 31567 + service-type: LoadBalancer + ketch: + enabled: true + {{- if .Values.ketch.image }} + image: "{{ .Values.ketch.image }}" + {{- else }} + image: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.ketch.repositoryBasename }}:{{ .Values.ketch.tag }}" + {{- end }} + metrics-address: {{ .Values.ketch.metricsAddress }} + cert-manager: + install-url: {{ .Values.certManager.installUrl }} + + cluster-update: + # it's a default value that specifies if cluster-update operations can restart ingress controllers + ingress-restart-is-allowed: {{ .Values.shipaApi.allowRestartIngressControllers }} + + app-auto-discovery: + enabled: {{ .Values.shipaApi.appAutoDiscoveryEnabled }} + event-updates: {{ .Values.shipaController.enableEventUpdater }} + + debug: {{ .Values.shipaApi.debug }} + node-traefik: + image: {{ .Values.shipaNodeTraefik.image }} + user: {{ .Values.shipaNodeTraefik.user }} + password: $NODE_TRAEFIK_PASSWORD + certificates: + root: /certs/ + ca: ca.pem + ca-key: ca-key.pem + client-ca: client-ca.crt + client-ca-key: client-ca.key + is-ca-endpoint-disabled: {{ .Values.shipaApi.isCAEndpointDisabled }} + + shipa-controller: + {{- if .Values.shipaController.image }} + image: "{{ .Values.shipaController.image }}" + {{- else }} + image: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.shipaController.repositoryBasename }}:{{ .Values.shipaController.tag }}" + {{- end }} + + + agent: + image-repository: {{ .Values.images.shipaRepositoryDirname }} + repository-name: {{ .Values.agent.repositoryBasename }} + tag: {{ .Values.agent.tag }} + busybody: + {{- if .Values.busybody.image }} + image: "{{ .Values.busybody.image }}" + {{- else }} + image: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.busybody.repositoryBasename }}:{{ .Values.busybody.tag }}" + {{- end }} + socket: /var/run/docker.sock + + signatures: single # multiple/single + launch-darkly: + api-key: {{ .Values.shipaCloud.launchDarkly.sdkKey }} diff --git a/packages/shipa/charts/templates/shipa-api-deployment.yaml b/packages/shipa/charts/templates/shipa-api-deployment.yaml new file mode 100644 index 000000000..5fff2aae3 --- /dev/null +++ b/packages/shipa/charts/templates/shipa-api-deployment.yaml @@ -0,0 +1,241 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "shipa.fullname" . }}-api + labels: {{- include "shipa.labels" . | nindent 4 }} + annotations: + sidecar.istio.io/inject: {{ eq .Values.shipaCluster.ingress.type "istio" | quote }} + checksum/config: {{ include (print $.Template.BasePath "/shipa-api-configmap.yaml") . | sha256sum }} + checksum/secret: {{ include (print $.Template.BasePath "/shipa-secret.yaml") . | sha256sum }} + checksum/db-auth-secret: {{ include (print $.Template.BasePath "/shipa-db-auth-secrets.yaml") . | sha256sum }} +spec: +{{- if .Values.shipaApi.allowMigrationDowntime }} + strategy: + type: Recreate +{{- end }} + selector: + matchLabels: + {{- include "shipa.selectorLabels" . | nindent 6 }} + template: + metadata: + labels: + {{- include "shipa.selectorLabels" . | nindent 8 }} + annotations: + timestamp: "{{ date "20060102150405" now }}" + sidecar.istio.io/inject: {{ eq .Values.shipaCluster.ingress.type "istio" | quote }} + spec: + nodeSelector: + kubernetes.io/os: linux + {{- if .Values.rbac.enabled }} + serviceAccountName: {{ template "shipa.fullname" . }} + {{- else }} + serviceAccountName: default + {{- end }} + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + initContainers: + - name: bootstrap + {{- if .Values.cli.image }} + image: "{{ .Values.cli.image }}" + {{- else }} + image: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.cli.repositoryBasename }}:{{ .Values.cli.tag }}" + {{- end }} + command: + - /scripts/bootstrap.sh + imagePullPolicy: {{ .Values.cli.pullPolicy }} + volumeMounts: + - name: scripts + mountPath: /scripts + - name: shipa-conf + mountPath: /etc/shipa-default/ + - name: config-dir + mountPath: /etc/shipa/ + env: + - name: RELEASE_NAME + value: {{ template "shipa.fullname" . }} + - name: INGRESS_TYPE + value: {{ default ( "nginx" ) .Values.shipaCluster.ingress.type | quote }} + - name: NGINX_SERVICE + value: {{ template "shipa.fullname" . }}-ingress-nginx + - name: SHIPA_PORT + value: {{ first .Values.shipaApi.servicePorts | quote }} + - name: SHIPA_API_CNAMES + value: {{ join "\",\"" (splitList "," (trimPrefix "\n" (include "shipa.cnames" .)) ) | quote }} + - name: SHIPA_INTERNAL_DNS + value: "{{ template "shipa.fullname" . }}-api.{{ .Release.Namespace }}.svc.{{ .Values.shipaCluster.clusterDomain }}" + - name: SHIPA_ORGANIZATION_ID + valueFrom: + configMapKeyRef: + name: {{ template "shipa.fullname" . }}-defaults-configmap + key: shipa-org-id + - name: SHIPA_MAIN_TARGET + value: {{ template "shipa.GetMainTarget" . }} + - name: WAIT_FOR_NGINX + value: {{ and (eq .Values.shipaCluster.ingress.type "nginx") (not .Values.shipaCluster.ingress.ip) | quote }} + - name: INGRESS_IP + value: {{ .Values.shipaCluster.ingress.ip }} + - name: NGINX_DEPLOYMENT_NAME + value: {{ template "shipa.fullname" . }}-nginx-ingress + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: init + {{- if .Values.shipaApi.image }} + image: "{{ .Values.shipaApi.image }}" + {{- else }} + image: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.shipaApi.repositoryBasename }}:{{ .Values.shipaApi.tag }}" + {{- end }} + # this init container creates an admin user. + # Let's avoid having ENV variables with admin credentials in the main shipa container. + command: + - /bin/shipad + - root + - user + - create + - --ignore-if-exists + imagePullPolicy: {{ .Values.shipaApi.pullPolicy }} + volumeMounts: + - name: config-dir + mountPath: /etc/shipa/ + - name: certificates + mountPath: /certs/ + env: + - name: SHIPA_ADMIN_USER + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-api-init-secret + key: username + - name: SHIPA_ADMIN_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-api-init-secret + key: password + {{- if not (or (.Values.tags.defaultDB) (.Values.tags.legacyMongoReplicaset)) }} + {{- if and ( .Values.externalMongodb.auth.username ) ( .Values.externalMongodb.auth.password ) }} + - name: DB_USERNAME + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-db-auth-secret + key: username + - name: DB_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-db-auth-secret + key: password + {{- end }} + {{- end }} + containers: + - name: shipa + {{- if .Values.shipaApi.image }} + image: "{{ .Values.shipaApi.image }}" + {{- else }} + image: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.shipaApi.repositoryBasename }}:{{ .Values.shipaApi.tag }}" + {{- end }} + imagePullPolicy: {{ .Values.shipaApi.pullPolicy }} + env: + - name: METRICS_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-secret + key: metrics-password + - name: NODE_TRAEFIK_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-secret + key: node-traefik-password + - name: DASHBOARD_IMAGE + {{- if .Values.dashboard.image }} + value: "{{ .Values.dashboard.image }}" + {{- else }} + value: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.dashboard.repositoryBasename }}:{{ .Values.dashboard.tag }}" + {{- end }} + - name: DASHBOARD_ENABLED + value: "{{ .Values.dashboard.enabled }}" + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + {{- if not (or (.Values.tags.defaultDB) (.Values.tags.legacyMongoReplicaset)) }} + {{- if and ( .Values.externalMongodb.auth.username ) ( .Values.externalMongodb.auth.password ) }} + - name: DB_USERNAME + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-db-auth-secret + key: username + - name: DB_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-db-auth-secret + key: password + {{- end }} + {{- end }} + ports: + - name: shipa + containerPort: {{ .Values.shipaApi.port }} + protocol: TCP + - name: shipa-secure + containerPort: {{ .Values.shipaApi.securePort }} + protocol: TCP + livenessProbe: + httpGet: + path: / + port: {{ .Values.shipaApi.port }} + periodSeconds: 2 + failureThreshold: 4 + startupProbe: + httpGet: + path: / + port: {{ .Values.shipaApi.port }} + failureThreshold: 90 + periodSeconds: 2 + readinessProbe: + httpGet: + path: / + port: {{ .Values.shipaApi.port }} + periodSeconds: 3 + initialDelaySeconds: 5 + failureThreshold: 50 + successThreshold: 1 + resources: + {{- toYaml .Values.resources | nindent 12 }} + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: false + runAsNonRoot: true + capabilities: + drop: + - ALL + volumeMounts: + - name: config-dir + mountPath: /etc/shipa/ + readOnly: true + - name: certificates + mountPath: /certs/ + readOnly: true + {{- if .Values.imagePullSecrets }} + imagePullSecrets: + - name: {{ .Values.imagePullSecrets }} + {{- end }} + volumes: + - name: config-dir + emptyDir: {} + - name: shipa-conf + configMap: + name: {{ template "shipa.fullname" . }}-api-config + items: + - key: shipa.conf + path: shipa.conf + - name: certificates + secret: + secretName: shipa-certificates + - name: scripts + configMap: + defaultMode: 0755 + name: {{ template "shipa.fullname" . }}-api-init-config diff --git a/packages/shipa/charts/templates/shipa-api-init-configmap.yaml b/packages/shipa/charts/templates/shipa-api-init-configmap.yaml new file mode 100644 index 000000000..bd693df1c --- /dev/null +++ b/packages/shipa/charts/templates/shipa-api-init-configmap.yaml @@ -0,0 +1,56 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ template "shipa.fullname" . }}-api-init-config + labels: {{- include "shipa.labels" . | nindent 4 }} +data: + init-job.sh: | +{{ .Files.Get "scripts/init-job.sh" | indent 4 }} + bootstrap.sh: | +{{ .Files.Get "scripts/bootstrap.sh" | indent 4 }} + csr-docker-cluster.json: | +{{ .Files.Get "scripts/csr-docker-cluster.json" | indent 4 }} + csr-shipa-ca.json: | +{{ .Files.Get "scripts/csr-shipa-ca.json" | indent 4 }} + csr-client-ca.json: | +{{ .Files.Get "scripts/csr-client-ca.json" | indent 4 }} + csr-api-config.json: | +{{ .Files.Get "scripts/csr-api-config.json" | indent 4 }} + csr-api-server.json: | +{{ .Files.Get "scripts/csr-api-server.json" | indent 4 }} + default-framework-template.yaml: | + shipaFramework: shipa-framework + resources: + general: + setup: + force: false + default: true + public: true + provisioner: kubernetes + kubeNamespace: {{ .Release.Namespace }} + security: + disableScan: true + router: {{ default ( "nginx" ) .Values.shipaCluster.ingress.type }} + access: + append: + - shipa-admin-team + - shipa-system-team + default-cluster-template.yaml: | + cluster: + name: shipa-cluster + kubernetesPublicEndpoint: CLUSTER_ADDR + frameworks: + - shipa-framework + ingress: + ip: {{ .Values.shipaCluster.ingress.ip }} + serviceType: {{ default ( "LoadBalancer" ) .Values.shipaCluster.ingress.serviceType | quote }} + type: {{ default ( "nginx" ) .Values.shipaCluster.ingress.type }} + {{ if eq .Values.shipaCluster.ingress.type "nginx" }} + className: {{ default ( include "shipa.defaultNginxClassName" . | trim ) .Values.shipaCluster.ingress.className }} + {{- end }} + {{ if eq .Values.shipaCluster.ingress.type "traefik" }} + className: {{ default ("traefik") .Values.shipaCluster.ingress.className }} + {{- end }} + {{ if eq .Values.shipaCluster.ingress.type "istio" }} + className: {{ default ("istio") .Values.shipaCluster.ingress.className }} + {{- end }} diff --git a/packages/shipa/charts/templates/shipa-api-init-job.yaml b/packages/shipa/charts/templates/shipa-api-init-job.yaml new file mode 100644 index 000000000..a36008cf6 --- /dev/null +++ b/packages/shipa/charts/templates/shipa-api-init-job.yaml @@ -0,0 +1,115 @@ +apiVersion: batch/v1 +kind: Job +metadata: + name: "{{ template "shipa.fullname" . }}-init-job-{{ .Release.Revision }}" + labels: {{- include "shipa.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": "post-install" + sidecar.istio.io/inject: "false" +spec: + backoffLimit: 5 + template: + metadata: + name: "{{ template "shipa.fullname" . }}-init-job-{{ .Release.Revision }}" + annotations: + sidecar.istio.io/inject: "false" + spec: + nodeSelector: + kubernetes.io/os: linux + terminationGracePeriodSeconds: 3 + {{- if .Values.rbac.enabled }} + serviceAccountName: {{ template "shipa.fullname" . }} + {{- else }} + serviceAccountName: default + {{- end }} + restartPolicy: Never + containers: + - name: migrations + {{- if .Values.cli.image }} + image: "{{ .Values.cli.image }}" + {{- else }} + image: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.cli.repositoryBasename }}:{{ .Values.cli.tag }}" + {{- end }} + command: + - /scripts/init-job.sh + imagePullPolicy: {{ .Values.cli.pullPolicy }} + env: + - name: RELEASE_NAME + value: {{ template "shipa.fullname" . }} + - name: SHIPA_ENDPOINT + value: "{{ template "shipa.fullname" . }}-api.{{ .Release.Namespace }}.svc.{{ .Values.shipaCluster.clusterDomain }}" + - name: SHIPA_ENDPOINT_PORT + value: "{{ first .Values.shipaApi.servicePorts }}" + - name: USERNAME + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-api-init-secret + key: username + - name: PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-api-init-secret + key: password + - name: METRICS_SERVICE + value: {{ template "shipa.fullname" . }}-metrics + - name: INGRESS_TYPE + value: {{ default ( "nginx" ) .Values.shipaCluster.ingress.type | quote }} + - name: INGRESS_SERVICE_TYPE + value: {{ default ( "LoadBalancer" ) .Values.shipaCluster.serviceType | quote }} + - name: INGRESS_IP + value: {{ default ( "" ) .Values.shipaCluster.ip | quote }} + - name: INGRESS_DEBUG + value: {{ default ( "false" ) .Values.shipaCluster.debug | quote }} + - name: ISTIO_INGRESS_SERVICE_TYPE + value: {{ default ( "LoadBalancer" ) .Values.shipaCluster.istioServiceType | quote }} + - name: ISTIO_INGRESS_IP + value: {{ default ( "" ) .Values.shipaCluster.istioIp | quote }} + - name: DASHBOARD_IMAGE + {{- if .Values.dashboard.image }} + value: "{{ .Values.dashboard.image }}" + {{- else }} + value: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.dashboard.repositoryBasename }}:{{ .Values.dashboard.tag }}" + {{- end }} + - name: DASHBOARD_ENABLED + value: "{{ .Values.dashboard.enabled }}" + - name: SHIPA_CLOUD + value: {{ .Values.shipaCloud.enabled | quote }} + - name: SHIPA_PAY_API_HOST + value: {{ .Values.shipaCloud.shipaPayApi.host | quote }} + - name: SHIPA_PAY_API_TOKEN + value: {{ .Values.shipaCloud.shipaPayApi.token | quote }} + - name: GOOGLE_RECAPTCHA_SITEKEY + value: {{ .Values.shipaCloud.googleRecaptcha.sitekey | quote }} + - name: GOOGLE_RECAPTCHA_SECRET + value: {{ .Values.shipaCloud.googleRecaptcha.secret | quote }} + - name: SMARTLOOK_PROJECT_KEY + value: {{ .Values.shipaCloud.smartlook.projectKey | quote }} + - name: LAUNCH_DARKLY_SDK_KEY + value: {{ .Values.shipaCloud.launchDarkly.sdkKey | quote }} + - name: SHIPA_TARGETS + value: {{ trimPrefix "\n" (include "shipa.cnames" .) }} + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: METRICS_PASSWORD + valueFrom: + secretKeyRef: + name: {{ template "shipa.fullname" . }}-secret + key: metrics-password + volumeMounts: + - name: scripts + mountPath: /scripts + - name: scripts-out + mountPath: /etc/shipa/ + {{- if .Values.imagePullSecrets }} + imagePullSecrets: + - name: {{ .Values.imagePullSecrets }} + {{- end }} + volumes: + - name: scripts + configMap: + defaultMode: 0755 + name: {{ template "shipa.fullname" . }}-api-init-config + - name: scripts-out + emptyDir: {} diff --git a/packages/shipa/charts/templates/shipa-api-init-secrets.yaml b/packages/shipa/charts/templates/shipa-api-init-secrets.yaml new file mode 100644 index 000000000..497d76735 --- /dev/null +++ b/packages/shipa/charts/templates/shipa-api-init-secrets.yaml @@ -0,0 +1,16 @@ +{{- if or (.Release.IsInstall) (.Values.auth.adminUser) -}} +apiVersion: v1 +kind: Secret +metadata: + name: {{ template "shipa.fullname" . }}-api-init-secret + labels: {{- include "shipa.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": "pre-install" + "helm.sh/hook-delete-policy": "before-hook-creation" +data: + {{- if or (lt (len .Values.auth.adminPassword) 6) (gt (len .Values.auth.adminPassword) 50) }} + {{- fail "adminPassword must be between 6 and 50 characters" }} + {{- end }} + username: {{ required "Admin username is required! Use --set=auth.adminUser=..." .Values.auth.adminUser | toString | b64enc | quote }} + password: {{ required "Admin password is required! Use --set=auth.adminPassword=..." .Values.auth.adminPassword | toString | b64enc | quote }} +{{- end }} diff --git a/packages/shipa/charts/templates/shipa-api-rbac.yaml b/packages/shipa/charts/templates/shipa-api-rbac.yaml new file mode 100644 index 000000000..cf2109939 --- /dev/null +++ b/packages/shipa/charts/templates/shipa-api-rbac.yaml @@ -0,0 +1,98 @@ +{{- if .Values.rbac.enabled }} +kind: ServiceAccount +apiVersion: v1 +metadata: + name: {{ template "shipa.fullname" . }} + labels: {{- include "shipa.labels" . | nindent 4 }} +--- +kind: ClusterRole +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: {{ template "shipa.fullname" . }} + labels: {{- include "shipa.labels" . | nindent 4 }} +rules: + - apiGroups: + - autoscaling + resources: + - horizontalpodautoscalers + verbs: + - create + - delete + - get + - list + - patch + - update + - watch + - apiGroups: + - "" + - services + - extensions + - rbac.authorization.k8s.io + - apiextensions.k8s.io + - networking.k8s.io + - core + - apps + - shipa.io + - config.istio.io + - networking.istio.io + - rbac.istio.io + - authentication.istio.io + - cert-manager.io + - admissionregistration.k8s.io + - coordination.k8s.io + - theketch.io + - traefik.containo.us + resources: ["*"] + verbs: ["*"] + - apiGroups: ["*"] + resources: ["*"] + verbs: + - list + - get + - watch + - nonResourceURLs: ["*"] + verbs: + - list + - get + - watch +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ template "shipa.fullname" . }}-role + labels: {{- include "shipa.labels" . | nindent 4 }} +rules: + - apiGroups: + - coordination.k8s.io + resources: + - leases + verbs: ["*"] +--- +kind: ClusterRoleBinding +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: {{ template "shipa.fullname" . }} + labels: {{- include "shipa.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ template "shipa.fullname" . }} +subjects: +- kind: ServiceAccount + name: {{ template "shipa.fullname" . }} + namespace: {{ .Release.Namespace }} +--- +kind: RoleBinding +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: {{ template "shipa.fullname" . }} + labels: {{- include "shipa.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ template "shipa.fullname" . }}-role +subjects: + - kind: ServiceAccount + name: {{ template "shipa.fullname" . }} + namespace: {{ .Release.Namespace }} +{{- end }} diff --git a/packages/shipa/charts/templates/shipa-api-service.yaml b/packages/shipa/charts/templates/shipa-api-service.yaml new file mode 100644 index 000000000..dc7c0b42d --- /dev/null +++ b/packages/shipa/charts/templates/shipa-api-service.yaml @@ -0,0 +1,23 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "shipa.fullname" . }}-api + labels: + {{- include "shipa.labels" . | nindent 4 }} +spec: + type: ClusterIP + selector: + {{- include "shipa.selectorLabels" . | nindent 4 }} + ports: +{{- range $i, $servicePort := .Values.shipaApi.servicePorts }} + - targetPort: {{ $.Values.shipaApi.port }} + port: {{ $servicePort }} + protocol: TCP + name: shipa-{{ $i }} +{{- end }} +{{- range $i, $servicePort := .Values.shipaApi.serviceSecurePorts }} + - targetPort: {{ $.Values.shipaApi.securePort }} + port: {{ $servicePort }} + protocol: TCP + name: shipa-secure-{{ $i }} +{{- end }} diff --git a/packages/shipa/charts/templates/shipa-certificates-secret.yaml b/packages/shipa/charts/templates/shipa-certificates-secret.yaml new file mode 100644 index 000000000..42505db2b --- /dev/null +++ b/packages/shipa/charts/templates/shipa-certificates-secret.yaml @@ -0,0 +1,17 @@ +apiVersion: v1 +kind: Secret +metadata: + name: shipa-certificates + labels: {{- include "shipa.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": "pre-install" + "helm.sh/hook-delete-policy": "before-hook-creation" +data: + ca.pem: "" + ca-key.pem: "" + cert.pem: "" + key.pem: "" + api-server.crt: "" + api-server.key: "" + client-ca.crt: "" + client-ca.key: "" diff --git a/packages/shipa/charts/templates/shipa-db-auth-secrets.yaml b/packages/shipa/charts/templates/shipa-db-auth-secrets.yaml new file mode 100644 index 000000000..17e3e0038 --- /dev/null +++ b/packages/shipa/charts/templates/shipa-db-auth-secrets.yaml @@ -0,0 +1,14 @@ +{{- if not (or (.Values.tags.defaultDB) (.Values.tags.legacyMongoReplicaset)) }} +{{- if and ( .Values.externalMongodb.auth.username ) ( .Values.externalMongodb.auth.password ) }} +apiVersion: v1 +kind: Secret +metadata: + name: {{ template "shipa.fullname" . }}-db-auth-secret + labels: {{- include "shipa.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": "pre-install" +data: + username: {{ required "Database username is required! Use --set=externalMongodb.auth.username=..." .Values.externalMongodb.auth.username | toString | b64enc | quote }} + password: {{ required "Database password is required! Use --set=externalMongodb.auth.password=..." .Values.externalMongodb.auth.password | toString | b64enc | quote }} +{{- end }} +{{- end }} \ No newline at end of file diff --git a/packages/shipa/charts/templates/shipa-defaults-configmap.yaml b/packages/shipa/charts/templates/shipa-defaults-configmap.yaml new file mode 100644 index 000000000..55245b93f --- /dev/null +++ b/packages/shipa/charts/templates/shipa-defaults-configmap.yaml @@ -0,0 +1,10 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ template "shipa.fullname" . }}-defaults-configmap + labels: {{- include "shipa.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": "pre-install" + "helm.sh/hook-delete-policy": "before-hook-creation" +data: + shipa-org-id: {{ uuidv4 | replace "-" "" | quote }} diff --git a/packages/shipa/charts/templates/shipa-secret.yaml b/packages/shipa/charts/templates/shipa-secret.yaml new file mode 100644 index 000000000..7bed8a4f1 --- /dev/null +++ b/packages/shipa/charts/templates/shipa-secret.yaml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: Secret +metadata: + name: {{ template "shipa.fullname" . }}-secret + labels: {{- include "shipa.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": "pre-install" + "helm.sh/hook-delete-policy": "before-hook-creation" +data: + metrics-password: {{ default (randAlphaNum 15) .Values.metrics.password | toString | b64enc | quote }} + postgres-password: {{ default (randAlphaNum 15) .Values.postgres.source.password | toString | b64enc | quote }} + node-traefik-password: {{ default (randAlphaNum 15) .Values.shipaNodeTraefik.password | toString | b64enc | quote }} diff --git a/packages/shipa/charts/templates/shipa-uninstall-job-configmap.yaml b/packages/shipa/charts/templates/shipa-uninstall-job-configmap.yaml new file mode 100644 index 000000000..8967017c3 --- /dev/null +++ b/packages/shipa/charts/templates/shipa-uninstall-job-configmap.yaml @@ -0,0 +1,13 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ template "shipa.fullname" . }}-uninstall-job-config + labels: {{- include "shipa.uninstall-labels" . | nindent 4 }} + annotations: + "helm.sh/hook-delete-policy": hook-succeeded + "helm.sh/hook-weight": "1" + "helm.sh/hook": post-delete +data: + uninstall-job.sh: | +{{ .Files.Get "scripts/uninstall-job.sh" | indent 4 }} + diff --git a/packages/shipa/charts/templates/shipa-uninstall-job.yaml b/packages/shipa/charts/templates/shipa-uninstall-job.yaml new file mode 100644 index 000000000..8b9894858 --- /dev/null +++ b/packages/shipa/charts/templates/shipa-uninstall-job.yaml @@ -0,0 +1,52 @@ +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ template "shipa.fullname" . }}-uninstall + labels: {{- include "shipa.uninstall-labels" . | nindent 4 }} + annotations: + "helm.sh/hook": post-delete + "helm.sh/hook-weight": "5" + "helm.sh/hook-delete-policy": hook-succeeded + sidecar.istio.io/inject: "false" +spec: + template: + metadata: + name: "{{ template "shipa.fullname" . }}-uninstall-job-{{ .Release.Revision }}" + annotations: + sidecar.istio.io/inject: "false" + spec: + nodeSelector: + kubernetes.io/os: linux + {{- if .Values.rbac.enabled }} + serviceAccountName: {{ template "shipa.fullname" . }}-uninstall + {{- else }} + serviceAccountName: default + {{- end }} + restartPolicy: Never + containers: + - name: cleanup + {{- if .Values.cli.image }} + image: "{{ .Values.cli.image }}" + {{- else }} + image: "{{ .Values.images.shipaRepositoryDirname }}/{{ .Values.cli.repositoryBasename }}:{{ .Values.cli.tag }}" + {{- end }} + command: + - /scripts/uninstall-job.sh + imagePullPolicy: IfNotPresent + env: + - name: SELECTOR + value: "shipa.io/is-shipa=true" + - name: NAMESPACE_MOD + value: "-A" + - name: RELEASE_NAME + value: {{ template "shipa.fullname" . }} + - name: RELEASE_NAMESPACE + value: {{ .Release.Namespace }} + volumeMounts: + - name: scripts + mountPath: /scripts + volumes: + - name: scripts + configMap: + defaultMode: 0755 + name: {{ template "shipa.fullname" . }}-uninstall-job-config \ No newline at end of file diff --git a/packages/shipa/charts/templates/shipa-uninstall-rbac.yaml b/packages/shipa/charts/templates/shipa-uninstall-rbac.yaml new file mode 100644 index 000000000..cf12335a4 --- /dev/null +++ b/packages/shipa/charts/templates/shipa-uninstall-rbac.yaml @@ -0,0 +1,58 @@ +{{- if .Values.rbac.enabled }} +kind: ServiceAccount +apiVersion: v1 +metadata: + name: {{ template "shipa.fullname" . }}-uninstall + labels: {{- include "shipa.uninstall-labels" . | nindent 4 }} + annotations: + "helm.sh/hook-delete-policy": hook-succeeded + "helm.sh/hook-weight": "1" + "helm.sh/hook": post-delete +--- +kind: ClusterRole +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: {{ template "shipa.fullname" . }}-uninstall + labels: {{- include "shipa.uninstall-labels" . | nindent 4 }} + annotations: + "helm.sh/hook-delete-policy": hook-succeeded + "helm.sh/hook-weight": "1" + "helm.sh/hook": post-delete +rules: + - apiGroups: + - "" + - apps + - batch + - services + - extensions + - rbac.authorization.k8s.io + - networking.k8s.io + - apiextensions.k8s.io + - core + - shipa.io + - clusterroles + - ingresses + - endpoints + - networkpolicies + - namespaces + resources: ["*"] + verbs: ["*"] +--- +kind: ClusterRoleBinding +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: {{ template "shipa.fullname" . }}-uninstall + labels: {{- include "shipa.uninstall-labels" . | nindent 4 }} + annotations: + "helm.sh/hook-delete-policy": hook-succeeded + "helm.sh/hook-weight": "1" + "helm.sh/hook": post-delete +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ template "shipa.fullname" . }}-uninstall +subjects: +- kind: ServiceAccount + name: {{ template "shipa.fullname" . }}-uninstall + namespace: {{ .Release.Namespace }} +{{- end }} diff --git a/packages/shipa/charts/values.yaml b/packages/shipa/charts/values.yaml new file mode 100644 index 000000000..391130997 --- /dev/null +++ b/packages/shipa/charts/values.yaml @@ -0,0 +1,343 @@ +# Default values for shipa. +# This is a YAML-formatted file. +# Declare variables to be passed into your templates. + +auth: + dummyDomain: "@shipa.io" + +images: + # The base directory for Shipa Corp images. For Shipa Corp images this value has repositoryBasename and tag appended to it to determine the location to pull images from + # This does not affect non-Shipa Corp images, such as k8s.gcr.io/ingress-nginx/controller, docker.io/postgres, k8s.gcr.io/mongodb-install, docker.io/mongo, docker.io/busybox, and docker.io/traefik + shipaRepositoryDirname: docker.io/shipasoftware + +shipaApi: + port: "8080" + securePort: "8081" + servicePorts: + - "80" + serviceSecurePorts: + - "443" + repositoryBasename: api + tag: 12ae8d77648df4e61d4b1bf191c6c01f9686d704 + pullPolicy: Always + debug: false + cnames: [] + allowRestartIngressControllers: true + allowMigrationDowntime: true + appAutoDiscoveryEnabled: true + isCAEndpointDisabled: false + secureIngressOnly: false + useInternalHost: true + + # if set this secret will be used for api ingress controller resources instead of default one + # customSecretName: shipa-api-secret + + # if set these annotations will be appended for API ingress resources + # customIngressAnnotations: + # aaa: "bbb" + # ccc: "ddd" + +shipaCluster: + # use debug logs in traefik ingress controller + debug: false + + ingress: + # ingress controller type + # supported: (nginx, istio, traefik) + type: nginx + + # NGINX ingress controller image + # If the ingress controller type is nginx and no ingress controller ip address is provided, an ingress controller will be deployed using this image + image: k8s.gcr.io/ingress-nginx/controller:v1.1.0 + + # ingress controller serviceType + # when using shipa managed nginx, we reconcile looking for the right Host of LoadBalancer or ClusterIP based on what is provided here + # when using non user managed ingress controller we use this just to store it in DB + serviceType: LoadBalancer + + # ingress controller ip address + # if provided we assume user provided ingress controller should be used and create api resources for it + # ip: 10.100.10.11 + + # ingress controller class name. + # If undefined, in most places we set default: nginx, traefik, istio. If we detect that it's shipa managed nginx, we default to shipa-nginx-ingress + # className: shipa-nginx-ingress + + # if enabled we will create ingress controller resources to allow api to be accessible on root ip of ingress controller + # NOTE: all ingresses require Host targeting instead of Path targeting for TLS + # also if you use nginxinc/kubernetes-ingress, using Ingress without host is not allowed until this is resolved: https://github.com/nginxinc/kubernetes-ingress/issues/209 + apiAccessOnIngressIp: true + + # shipa managed nginx only configs: + + # ingress controller ClusterIp address + # if provided it will be used for shipa managed nginx ingress controller + # clusterIp: 10.100.10.11 + + # ingress controller LoadBalancerIp address + # if provided it will be used for shipa managed nginx ingress controller + # loadBalancerIp: 10.100.10.11 + + # if provided it will be used as node port for shipa managed nginx ingress controller + # nodePort: 31000 + + # if set these annotations will be appended for the Nginx ingress controller service resource + # customNginxServiceAnnotations: + # aaa: "bbb" + # ccc: "ddd" + # shipaCluster.ingress.customNginxServiceAnnotations example for configuring internet facing NLB in AWS: + # customNginxServiceAnnotations: + # service.beta.kubernetes.io/aws-load-balancer-type: nlb + # service.beta.kubernetes.io/aws-load-balancer-eip-allocations: eipalloc-abcd1234 + + clusterDomain: cluster.local + +# populate with docker hub username to use authenticated user. Secrets should be added to cluster outside shipa helm chart +# imagePullSecrets: "" + +dashboard: + enabled: true + repositoryBasename: dashboard + tag: ff17198a3343c07d8eccf0fa418da7136aa09244 + +postgres: + source: + ## Leave blank to default to {{ template "shipa.fullname" . }}-postgres.{{ .Release.Namespace }} e.g. shipa-postgres.shipa-system + host: + port: 5432 + user: postgres + ## Leave blank to generate a random value + password: + ## options for postgres.source.sslmode are "require", "verify-full", "verify-ca", or "disable + sslmode: disable + ## set postgres.create to false to avoid creating a postgres instance + create: true + ## If create is set to true, this is the image that will be used + image: docker.io/postgres:13 + persistence: + ## Persistent Volume Storage Class + ## If defined, storageClassName: + ## If set to "-", storageClassName: "", which disables dynamic provisioning + ## If undefined (the default) or set to null, no storageClassName spec is + ## set, choosing the default provisioner. + ## + ## storageClass: "" + accessMode: "ReadWriteOnce" + size: 10Gi + +cli: + repositoryBasename: cli + tag: 4a023b65e6023d8949bdae76a8c22706c66bfe50 + pullPolicy: Always + +metrics: + repositoryBasename: metrics + tag: v0.0.7 + pullPolicy: Always + + # Extra configuration to add to prometheus.yaml + # extraPrometheusConfiguration: | + # remote_read: + # - url: http://localhost:9268/read + # remote_write: + # - url: http://localhost:9268/write + extraPrometheusConfiguration: + #password: hardcoded + prometheusArgs: "--storage.tsdb.retention.time=1d" + +busybody: + repositoryBasename: bb + tag: 6e7d2fd228b6c3587476efce0ca982f48bccb856 + +shipaController: + repositoryBasename: shipa-controller + tag: c03c6bfb0e0ec07ad252a69401b736ab445ae431 + enableEventUpdater: false + +prometheusMetricsExporter: + repositoryBasename: prometheus-metrics-exporter + tag: b123eb79bdbe56f83812b5ad3cfb8bbb568b2e3d + +clair: + repositoryBasename: clair + tag: v2.1.7 + +shipaNodeTraefik: + # image: docker.io/traefik:v1.7.24 + user: admin + +# -------------------------------------------------------------------------- + +nameOverride: "" +fullnameOverride: "" + +serviceAccount: + # Specifies whether a service account should be created + create: true + # The name of the service account to use. + # If not set and create is true, a name is generated using the fullname template + name: + +rbac: + enabled: true + +# Connect your own instance of mongodb +externalMongodb: + # url must follow Standard Connection String Format as described here: https://docs.mongodb.com/manual/reference/connection-string/#standard-connection-string-format + # For a sharded cluster it should be a comma separated list of hosts: + # e.g. "mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017" + # Due to some limitations of the dependencies, we currently do not support url with 'DNS Seed List Connection Format'. + url: < database url > + auth: + username: < username > + password: < password > + # Enable/Disable TLS when connecting to external DB instance. + tls: + enable: true + +# tags are standard way to handle chart dependencies. +tags: + # Set defaultDB (and legacyMongoReplicaset) to 'false' when using external DB to not install default DB. + # It will also prevent creating Persistent Volumes. + # This cannot be used with tags.legacyMongoReplicaset + defaultDB: true + # Set legacyMongoReplicaset to 'true' in order to use the deprecated https://charts.helm.sh/stable/mongodb-replicaset chart as an internal MongoDB. + # This cannot be used with tags.defaultDB + legacyMongoReplicaset: false + +certManager: + installUrl: https://github.com/jetstack/cert-manager/releases/download/v1.5.3/cert-manager.yaml + +# Default DB config, enabled by setting tag.defaultDB to true. This is not intended for production use +# Full list of configuration values can be found at https://github.com/bitnami/charts/blob/d997058e6f9c99826242c0ae6d19ccc1cdc2106a/bitnami/mongodb/values.yaml +mongodb: + global: + imageRegistry: "" + imagePullSecrets: [] + image: + registry: docker.io + repository: bitnami/mongodb + tag: 5.0.6-debian-10-r29 + pullPolicy: IfNotPresent + pullSecrets: [] + persistence: + existingClaim: "" + size: "10Gi" + architecture: "standalone" + useStatefulSet: true + replicaSetName: rs0 + service: + port: 27017 + nodeSelector: + kubernetes.io/os: linux + arbiter: + podSecurityContext: + enabled: true + fsGroup: 999 + containerSecurityContext: + enabled: true + runAsUser: 999 + nodeSelector: + kubernetes.io/os: linux + auth: + enabled: false + tls: + enabled: false + image: + registry: docker.io + repository: bitnami/nginx + tag: 1.21.6-debian-10-r30 + pullPolicy: IfNotPresent + pullSecrets: [] + externalAccess: + enabled: false + autoDiscovery: + enabled: false + image: + registry: docker.io + repository: bitnami/kubectl + tag: 1.23.4-debian-10-r7 + pullPolicy: IfNotPresent + pullSecrets: [] + volumePermissions: + enabled: false + image: + registry: docker.io + repository: bitnami/bitnami-shell + tag: 10-debian-10-r350 + pullPolicy: IfNotPresent + pullSecrets: [] + metrics: + enabled: false + image: + registry: docker.io + repository: bitnami/mongodb-exporter + tag: 0.30.0-debian-10-r83 + pullPolicy: IfNotPresent + pullSecrets: [] + extraFlags: "--dbpath=/bitnami/mongodb" + containerSecurityContext: + enabled: true + runAsUser: 999 + runAsNonRoot: true + podSecurityContext: + enabled: true + fsGroup: 999 + +# Deprecated DB config (default DB for 1.6.2 and prior), enabled by setting tag.legacyMongoReplicaset to true. This is not intended for production use +mongodb-replicaset: + replicaSetName: rs0 + replicas: 1 + port: 27017 + nodeSelector: + kubernetes.io/os: linux + auth: + enabled: false + installImage: + repository: k8s.gcr.io/mongodb-install + tag: 0.6 + pullPolicy: IfNotPresent + image: + repository: docker.io/mongo + tag: 5.0 + pullPolicy: IfNotPresent + copyConfigImage: + repository: docker.io/busybox + tag: 1.29.3 + pullPolicy: IfNotPresent + persistentVolume: + ## Persistent Volume Storage Class + ## If defined, storageClassName: + ## If set to "-", storageClassName: "", which disables dynamic provisioning + ## If undefined (the default) or set to null, no storageClassName spec is + ## set, choosing the default provisioner. + ## + ## storageClass: "" + enabled: true + size: 10Gi + tls: + enabled: false + configmap: + +shipaCloud: + enabled: false + shipaPayApi: + host: "" + token: "" + googleRecaptcha: + sitekey: "" + secret: "" + smartlook: + projectKey: "" + launchDarkly: + sdkKey: "" + +ketch: + enabled: true + repositoryBasename: ketch + tag: e5a27aacde7adecb7332aa069726c61123163576 + metricsAddress: 127.0.0.1:8080 + +agent: + repositoryBasename: shipa-cluster-agent + tag: aee9eb9e8c513fb0bb32a731b641f8239e4a2a7d diff --git a/packages/shipa/generated-changes/patch/Chart.yaml.patch b/packages/shipa/generated-changes/patch/Chart.yaml.patch index d4807c5f8..9cda8ec0f 100644 --- a/packages/shipa/generated-changes/patch/Chart.yaml.patch +++ b/packages/shipa/generated-changes/patch/Chart.yaml.patch @@ -20,7 +20,7 @@ +maintainers: +- email: rlachhman@shipa.io + name: ravi - version: 1.7.0 + version: 1.7.1 +keywords: +- shipa +- deployment diff --git a/packages/shipa/package.yaml b/packages/shipa/package.yaml index f1ae106f1..37ec395ba 100644 --- a/packages/shipa/package.yaml +++ b/packages/shipa/package.yaml @@ -1,2 +1,2 @@ -url: https://shipa-charts.storage.googleapis.com/shipa-1.7.0.tgz +url: https://shipa-charts.storage.googleapis.com/shipa-1.7.1.tgz packageVersion: 00 \ No newline at end of file