Skip to content

Commit

Permalink
[swagger-ui] Add swagger-ui helm chart (#380)
Browse files Browse the repository at this point in the history
Co-authored-by: Jozef Volak <[email protected]>
  • Loading branch information
Jozefiel and Jozef Volak authored Jun 21, 2024
1 parent 8b0bfe2 commit e57accb
Show file tree
Hide file tree
Showing 14 changed files with 860 additions and 0 deletions.
23 changes: 23 additions & 0 deletions charts/swagger-ui/.helmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# 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
*.orig
*~
# Various IDEs
.project
.idea/
*.tmproj
.vscode/
16 changes: 16 additions & 0 deletions charts/swagger-ui/Chart.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
apiVersion: v2
name: swagger-ui
description: A Helm chart for Swagger UI
icon: https://avatars.githubusercontent.com/u/23452093?s=200&v=4
type: application
version: 0.1.0
appVersion: "v5.17.14"
engine: gotpl
maintainers:
- name: FRINX
email: [email protected]
url: https://frinx.io
annotations:
artifacthub.io/images: |
- name: swagger-ui
image: swaggerapi/swagger-ui
101 changes: 101 additions & 0 deletions charts/swagger-ui/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# swagger-ui

A Helm chart for Swagger UI

![Version: 0.1.0](https://img.shields.io/badge/Version-0.1.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: v5.17.14](https://img.shields.io/badge/AppVersion-v5.17.14-informational?style=flat-square)

## Get Repo Info

```console
helm repo add frinx https://FRINXio.github.io/helm-charts
helm repo update
```

## Install Chart

```console
helm install [RELEASE_NAME] frinx/swagger-ui

## Upgrading Chart

```console
helm upgrade [RELEASE_NAME] frinx/swagger-ui
```

## Uninstall Chart

```console
helm uninstall [RELEASE_NAME]
```

## Formatter script configuration

A Formatter script is used to reformat openapi documentation on the fly.
This is useful when swagger is deployed behind a reverse proxy.

Current functionality supports changing server definition, rewriting and whitelisting API endpoints.

Example of configuration:

```yaml
extraConfigMaps:
workflow-manager-filter:
server:
url: /api/workflow
api:
rewrite:
from: ^/api/ # support regex
to: "/"
whitelist:
"/api/metadata/taskdefs":
- "get"
- "post"
- "put"
"/api/metadata/taskdefs/{name}":
- "get"
- "delete"

```

## Values

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| affinity | object | `{}` | [Affinity for pod assignment](https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity) |
| autoscaling | object | `{"enabled":false,"maxReplicas":100,"minReplicas":1,"targetCPUUtilizationPercentage":80}` | [Autoscaling parameters](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) |
| env | object | `{"BASE_URL":"/swagger","URLS":"[{ url: \"./api/workflow-manager.json\", name: \"WorkflowManager\"}]"}` | Application environment variables |
| extraConfigMaps | object | `{"workflow-manager-filter":{"api":{"rewrite":{"from":"^/api/","to":"/"},"whitelist":{"/api/event":["get","post"],"/api/event/{name}":["delete","get"],"/api/external/postgres/{externalPayloadPath}":["get"],"/api/metadata/taskdefs":["get","post","put"],"/api/metadata/taskdefs/{name}":["get","delete"],"/api/metadata/workflow":["get","post","put"],"/api/metadata/workflow/{name}":["get"],"/api/metadata/workflow/{name}/{version}":["delete"],"/api/workflow":["post"],"/api/workflow/bulk/pause":["put"],"/api/workflow/bulk/restart":["post"],"/api/workflow/bulk/resume":["put"],"/api/workflow/bulk/retry":["post"],"/api/workflow/bulk/terminate":["post"],"/api/workflow/{name}":["delete"],"/api/workflow/{workflowId}/remove":["delete"],"/health":["get"]}},"enabled":true,"server":{"url":"/api/workflow"}}}` | Extra Config maps Define configuration for formetter script. |
| extraConfigMaps.workflow-manager-filter | object | `{"api":{"rewrite":{"from":"^/api/","to":"/"},"whitelist":{"/api/event":["get","post"],"/api/event/{name}":["delete","get"],"/api/external/postgres/{externalPayloadPath}":["get"],"/api/metadata/taskdefs":["get","post","put"],"/api/metadata/taskdefs/{name}":["get","delete"],"/api/metadata/workflow":["get","post","put"],"/api/metadata/workflow/{name}":["get"],"/api/metadata/workflow/{name}/{version}":["delete"],"/api/workflow":["post"],"/api/workflow/bulk/pause":["put"],"/api/workflow/bulk/restart":["post"],"/api/workflow/bulk/resume":["put"],"/api/workflow/bulk/retry":["post"],"/api/workflow/bulk/terminate":["post"],"/api/workflow/{name}":["delete"],"/api/workflow/{workflowId}/remove":["delete"],"/health":["get"]}},"enabled":true,"server":{"url":"/api/workflow"}}` | workflow-manager filter configuration |
| extraVolumes | object | `{}` | Additional volumes on the output Deployment definition |
| fullnameOverride | string | `""` | String to partially override app name |
| image.pullPolicy | string | `"IfNotPresent"` | Image pull policy |
| image.repository | string | `"swaggerapi/swagger-ui"` | swagger-ui image repository |
| image.tag | string | `""` | Overrides the image tag whose default is the chart appVersion. |
| imagePullSecrets | list | `[]` | [Image Pull Secrets](https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/) |
| ingress.annotations | object | `{}` | Additional annotations for the Ingress resource |
| ingress.className | string | `""` | IngressClass that will be be used to implement the Ingress |
| ingress.enabled | bool | `false` | Enable ingress |
| ingress.hosts | list | `[{"host":"chart-example.local","paths":[{"path":"/","pathType":"ImplementationSpecific"}]}]` | [Ingress Host](https://kubernetes.io/docs/concepts/services-networking/ingress/#the-ingress-resource) |
| ingress.labels | object | `{}` | Additional labels for the Ingress resource |
| ingress.tls | list | `[]` | |
| initContainers | object | `{}` | additional InitContainers |
| livenessProbe | object | `{"initialDelaySeconds":10,"periodSeconds":30,"timeoutSeconds":10}` | Liveness probe |
| manageApiDocs | object | `{"workflow-manager":{"enabled":true,"fetch":{"file":"workflow-manager.json","url":"https://raw.githubusercontent.com/FRINXio/conductor/swagger_docs/latest.json"},"formatConfigMap":"workflow-manager-filter"}}` | InitContainer configuration used to fetch and format openapi documentation Define service name, endpoint to documentation, output file name and extra config map with configuration for formatter script. |
| nameOverride | string | `""` | String to partially override app name |
| nodeSelector | object | `{}` | [Node labels for pod assignment](https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/) |
| podAnnotations | object | `{}` | Pod annotations |
| podLabels | object | `{}` | Pod labels |
| podSecurityContext | object | `{}` | Configure [Pods Security Context](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/#set-the-security-context-for-a-pod) |
| replicaCount | int | `1` | Number of replicas of the deployment. |
| resources | object | `{}` | [Container resources](https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/) |
| securityContext | object | `{}` | Security context |
| service.annotations | object | `{}` | Service annotations |
| service.loadBalancerIP | string | `nil` | Service [Load Balancer IP](https://kubernetes.io/docs/concepts/services-networking/service/#type-loadbalancer) |
| service.port | int | `8080` | Service port |
| service.type | string | `"ClusterIP"` | Service type |
| serviceAccount.annotations | object | `{}` | Annotations to add to the service account |
| serviceAccount.automount | bool | `true` | Automatically mount a ServiceAccount's API credentials? |
| serviceAccount.create | bool | `true` | Specifies whether a service account should be created |
| serviceAccount.name | string | `""` | The name of the service account to use. If not set and create is true, a name is generated using the fullname template |
| tolerations | list | `[]` | [Tolerations for pod assignment](https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/) |

63 changes: 63 additions & 0 deletions charts/swagger-ui/README.md.gotmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
{{ template "chart.header" . }}
{{ template "chart.description" . }}

{{ template "chart.versionBadge" . }}{{ template "chart.typeBadge" . }}{{ template "chart.appVersionBadge" . }}

## Get Repo Info

```console
helm repo add frinx https://FRINXio.github.io/helm-charts
helm repo update
```

## Install Chart

```console
helm install [RELEASE_NAME] frinx/{{ template "chart.name" . }}

## Upgrading Chart

```console
helm upgrade [RELEASE_NAME] frinx/{{ template "chart.name" . }}
```

## Uninstall Chart

```console
helm uninstall [RELEASE_NAME]
```

## Formatter script configuration

A Formatter script is used to reformat openapi documentation on the fly.
This is useful when swagger is deployed behind a reverse proxy.

Current functionality supports changing server definition, rewriting and whitelisting API endpoints.

Example of configuration:

```yaml
extraConfigMaps:
workflow-manager-filter:
server:
url: /api/workflow
api:
rewrite:
from: ^/api/ # support regex
to: "/"
whitelist:
"/api/metadata/taskdefs":
- "get"
- "post"
- "put"
"/api/metadata/taskdefs/{name}":
- "get"
- "delete"

```

{{ template "chart.requirementsSection" . }}

{{ template "chart.valuesSection" . }}

{{ template "helm-docs.versionFooter" . }}
87 changes: 87 additions & 0 deletions charts/swagger-ui/config/formatter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import argparse
import json
import re

import yaml


def load_openapi(filepath):
with open(filepath, 'r') as file:
if filepath.endswith('.yaml') or filepath.endswith('.yml'):
return yaml.safe_load(file)
elif filepath.endswith('.json'):
return json.load(file)
else:
raise ValueError("Unsupported file format. Use .json or .yaml/.yml.")

def load_config(config_filepath):
with open(config_filepath, 'r') as file:
return yaml.safe_load(file)

def save_openapi(data, filepath):
with open(filepath, 'w') as file:
if filepath.endswith('.yaml') or filepath.endswith('.yml'):
yaml.dump(data, file, sort_keys=False)
elif filepath.endswith('.json'):
json.dump(data, file, indent=2)
else:
raise ValueError("Unsupported file format. Use .json or .yaml/.yml.")

def filter_paths(openapi_data, whitelist):
paths = openapi_data.get('paths', {})
filtered_paths = {}
for path, methods in paths.items():
if path in whitelist:
filtered_methods = {method: data for method, data in methods.items() if method in whitelist[path]}
if filtered_methods:
filtered_paths[path] = filtered_methods
openapi_data['paths'] = filtered_paths
return openapi_data

def rewrite_paths(openapi_data, rewrite_from, rewrite_to):
paths = openapi_data.get('paths', {})
rewritten_paths = {}
for path, methods in paths.items():
new_path = re.sub(rewrite_from, rewrite_to, path)
rewritten_paths[new_path] = methods
openapi_data['paths'] = rewritten_paths
return openapi_data


def main():
parser = argparse.ArgumentParser(description='Filter OpenAPI endpoints based on a whitelist.')
parser.add_argument('input', help='Path to the input OpenAPI file (JSON or YAML)')
parser.add_argument('output', help='Path to the output filtered OpenAPI file (JSON or YAML)')
parser.add_argument('config', help='Path to the file with config definition')

args = parser.parse_args()

# Load OpenAPI document
openapi_data = load_openapi(args.input)

# Load configuration
config = load_config(args.config)

# Check if whitelist is defined and apply if applicable
whitelist = config.get('api', {}).get('whitelist', None)
if not whitelist:
filtered_openapi_data = openapi_data
else:
filtered_openapi_data = filter_paths(openapi_data, whitelist)

# Check if rewrite rules are defined and apply them if applicable
rewrite_rules = config.get('api', {}).get('rewrite', None)
if rewrite_rules:
rewrite_from = rewrite_rules.get('from', '')
rewrite_to = rewrite_rules.get('to', '')
filtered_openapi_data = rewrite_paths(filtered_openapi_data, rewrite_from, rewrite_to)

server_url = config.get('server', {}).get('url', None)
if server_url:
filtered_openapi_data['servers'] = [{'url': server_url}]

save_openapi(filtered_openapi_data, args.output)
print(f"Filtered OpenAPI document saved to {args.output}")

if __name__ == '__main__':
main()
22 changes: 22 additions & 0 deletions charts/swagger-ui/templates/NOTES.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
1. Get the application URL by running these commands:
{{- if .Values.ingress.enabled }}
{{- range $host := .Values.ingress.hosts }}
{{- range .paths }}
http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ .path }}
{{- end }}
{{- end }}
{{- else if contains "NodePort" .Values.service.type }}
export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "swagger-ui.fullname" . }})
export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}")
echo http://$NODE_IP:$NODE_PORT
{{- else if contains "LoadBalancer" .Values.service.type }}
NOTE: It may take a few minutes for the LoadBalancer IP to be available.
You can watch the status of by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "swagger-ui.fullname" . }}'
export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "swagger-ui.fullname" . }} --template "{{"{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}"}}")
echo http://$SERVICE_IP:{{ .Values.service.port }}
{{- else if contains "ClusterIP" .Values.service.type }}
export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "swagger-ui.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}")
export CONTAINER_PORT=$(kubectl get pod --namespace {{ .Release.Namespace }} $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}")
echo "Visit http://127.0.0.1:8080 to use your application"
kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:$CONTAINER_PORT
{{- end }}
62 changes: 62 additions & 0 deletions charts/swagger-ui/templates/_helpers.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{{/*
Expand the name of the chart.
*/}}
{{- define "swagger-ui.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 "swagger-ui.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 "swagger-ui.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}

{{/*
Common labels
*/}}
{{- define "swagger-ui.labels" -}}
helm.sh/chart: {{ include "swagger-ui.chart" . }}
{{ include "swagger-ui.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}

{{/*
Selector labels
*/}}
{{- define "swagger-ui.selectorLabels" -}}
app.kubernetes.io/name: {{ include "swagger-ui.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}

{{/*
Create the name of the service account to use
*/}}
{{- define "swagger-ui.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "swagger-ui.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}
Loading

0 comments on commit e57accb

Please sign in to comment.