From 9586d3536f7ac66eafd081603fba11617b5674d2 Mon Sep 17 00:00:00 2001 From: Tom Andrade Date: Fri, 20 Jan 2023 09:36:17 +0100 Subject: [PATCH] initial commit --- Dockerfile | 14 +++ LICENSE | 7 ++ README.md | 12 +++ charts/gecho/.helmignore | 23 +++++ charts/gecho/Chart.yaml | 6 ++ charts/gecho/templates/NOTES.txt | 22 +++++ charts/gecho/templates/_helpers.tpl | 62 ++++++++++++ charts/gecho/templates/deployment.yaml | 66 +++++++++++++ charts/gecho/templates/hpa.yaml | 28 ++++++ charts/gecho/templates/ingress.yaml | 61 ++++++++++++ charts/gecho/templates/service.yaml | 15 +++ charts/gecho/templates/serviceaccount.yaml | 12 +++ .../templates/tests/test-connection.yaml | 15 +++ charts/gecho/values.yaml | 84 +++++++++++++++++ go.mod | 10 ++ go.sum | 6 ++ main.go | 94 +++++++++++++++++++ 17 files changed, 537 insertions(+) create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 README.md create mode 100644 charts/gecho/.helmignore create mode 100644 charts/gecho/Chart.yaml create mode 100644 charts/gecho/templates/NOTES.txt create mode 100644 charts/gecho/templates/_helpers.tpl create mode 100644 charts/gecho/templates/deployment.yaml create mode 100644 charts/gecho/templates/hpa.yaml create mode 100644 charts/gecho/templates/ingress.yaml create mode 100644 charts/gecho/templates/service.yaml create mode 100644 charts/gecho/templates/serviceaccount.yaml create mode 100644 charts/gecho/templates/tests/test-connection.yaml create mode 100644 charts/gecho/values.yaml create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d28a8ff --- /dev/null +++ b/Dockerfile @@ -0,0 +1,14 @@ +FROM golang:1.19 as build + +ENV CGO_ENABLED=0 +WORKDIR /gecho + +COPY go.* main.go /gecho/ +RUN go get ./... && \ + go build + +FROM scratch + +COPY --from=build /gecho/gecho / + +ENTRYPOINT [ "/gecho" ] \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4d02d2b --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright 2023 Thomas Andrade + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..9c6c00b --- /dev/null +++ b/README.md @@ -0,0 +1,12 @@ +Gecho +============================== + +[![License](https://img.shields.io/badge/license-MIT-green.svg)](https://git.thebarrens.nu/wolvie/gecho/blob/master/LICENSE) + +A Simple echo server written in Go + +Usage +----- + +Just compile (or build the container image) and run the application, the only supported parameter is set by the `MAX_REQUESTS` environment variable which defaults to 500 if not set + diff --git a/charts/gecho/.helmignore b/charts/gecho/.helmignore new file mode 100644 index 0000000..0e8a0eb --- /dev/null +++ b/charts/gecho/.helmignore @@ -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/ diff --git a/charts/gecho/Chart.yaml b/charts/gecho/Chart.yaml new file mode 100644 index 0000000..d8a6325 --- /dev/null +++ b/charts/gecho/Chart.yaml @@ -0,0 +1,6 @@ +apiVersion: v2 +name: gecho +description: A Helm chart for Kubernetes +type: application +version: 0.1.0 +appVersion: "v0" diff --git a/charts/gecho/templates/NOTES.txt b/charts/gecho/templates/NOTES.txt new file mode 100644 index 0000000..ee3d29a --- /dev/null +++ b/charts/gecho/templates/NOTES.txt @@ -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 "gecho.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 "gecho.fullname" . }}' + export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "gecho.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 "gecho.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 }} diff --git a/charts/gecho/templates/_helpers.tpl b/charts/gecho/templates/_helpers.tpl new file mode 100644 index 0000000..d972bf7 --- /dev/null +++ b/charts/gecho/templates/_helpers.tpl @@ -0,0 +1,62 @@ +{{/* +Expand the name of the chart. +*/}} +{{- define "gecho.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 "gecho.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 "gecho.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Common labels +*/}} +{{- define "gecho.labels" -}} +helm.sh/chart: {{ include "gecho.chart" . }} +{{ include "gecho.selectorLabels" . }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{/* +Selector labels +*/}} +{{- define "gecho.selectorLabels" -}} +app.kubernetes.io/name: {{ include "gecho.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} + +{{/* +Create the name of the service account to use +*/}} +{{- define "gecho.serviceAccountName" -}} +{{- if .Values.serviceAccount.create }} +{{- default (include "gecho.fullname" .) .Values.serviceAccount.name }} +{{- else }} +{{- default "default" .Values.serviceAccount.name }} +{{- end }} +{{- end }} diff --git a/charts/gecho/templates/deployment.yaml b/charts/gecho/templates/deployment.yaml new file mode 100644 index 0000000..b9f5f3a --- /dev/null +++ b/charts/gecho/templates/deployment.yaml @@ -0,0 +1,66 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "gecho.fullname" . }} + labels: + {{- include "gecho.labels" . | nindent 4 }} +spec: + {{- if not .Values.autoscaling.enabled }} + replicas: {{ .Values.replicaCount }} + {{- end }} + selector: + matchLabels: + {{- include "gecho.selectorLabels" . | nindent 6 }} + template: + metadata: + {{- with .Values.podAnnotations }} + annotations: + {{- toYaml . | nindent 8 }} + {{- end }} + labels: + {{- include "gecho.selectorLabels" . | nindent 8 }} + spec: + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + serviceAccountName: {{ include "gecho.serviceAccountName" . }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + containers: + - name: {{ .Chart.Name }} + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + {{- if .Values.maxRequests }} + env: + - name: MAX_REQUESTS + value: {{ .Values.maxRequests }} + {{- end }} + ports: + - name: http + containerPort: 8080 + protocol: TCP + livenessProbe: + httpGet: + path: /healthz + port: 8080 + readinessProbe: + httpGet: + path: /healthz + port: 8080 + resources: + {{- toYaml .Values.resources | nindent 12 }} + {{- with .Values.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} diff --git a/charts/gecho/templates/hpa.yaml b/charts/gecho/templates/hpa.yaml new file mode 100644 index 0000000..a370bda --- /dev/null +++ b/charts/gecho/templates/hpa.yaml @@ -0,0 +1,28 @@ +{{- if .Values.autoscaling.enabled }} +apiVersion: autoscaling/v2beta1 +kind: HorizontalPodAutoscaler +metadata: + name: {{ include "gecho.fullname" . }} + labels: + {{- include "gecho.labels" . | nindent 4 }} +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: {{ include "gecho.fullname" . }} + minReplicas: {{ .Values.autoscaling.minReplicas }} + maxReplicas: {{ .Values.autoscaling.maxReplicas }} + metrics: + {{- if .Values.autoscaling.targetCPUUtilizationPercentage }} + - type: Resource + resource: + name: cpu + targetAverageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }} + {{- end }} + {{- if .Values.autoscaling.targetMemoryUtilizationPercentage }} + - type: Resource + resource: + name: memory + targetAverageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage }} + {{- end }} +{{- end }} diff --git a/charts/gecho/templates/ingress.yaml b/charts/gecho/templates/ingress.yaml new file mode 100644 index 0000000..5af8edf --- /dev/null +++ b/charts/gecho/templates/ingress.yaml @@ -0,0 +1,61 @@ +{{- if .Values.ingress.enabled -}} +{{- $fullName := include "gecho.fullname" . -}} +{{- $svcPort := .Values.service.port -}} +{{- if and .Values.ingress.className (not (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion)) }} + {{- if not (hasKey .Values.ingress.annotations "kubernetes.io/ingress.class") }} + {{- $_ := set .Values.ingress.annotations "kubernetes.io/ingress.class" .Values.ingress.className}} + {{- end }} +{{- end }} +{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion -}} +apiVersion: networking.k8s.io/v1 +{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}} +apiVersion: networking.k8s.io/v1beta1 +{{- else -}} +apiVersion: extensions/v1beta1 +{{- end }} +kind: Ingress +metadata: + name: {{ $fullName }} + labels: + {{- include "gecho.labels" . | nindent 4 }} + {{- with .Values.ingress.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + {{- if and .Values.ingress.className (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion) }} + ingressClassName: {{ .Values.ingress.className }} + {{- end }} + {{- if .Values.ingress.tls }} + tls: + {{- range .Values.ingress.tls }} + - hosts: + {{- range .hosts }} + - {{ . | quote }} + {{- end }} + secretName: {{ .secretName }} + {{- end }} + {{- end }} + rules: + {{- range .Values.ingress.hosts }} + - host: {{ .host | quote }} + http: + paths: + {{- range .paths }} + - path: {{ .path }} + {{- if and .pathType (semverCompare ">=1.18-0" $.Capabilities.KubeVersion.GitVersion) }} + pathType: {{ .pathType }} + {{- end }} + backend: + {{- if semverCompare ">=1.19-0" $.Capabilities.KubeVersion.GitVersion }} + service: + name: {{ $fullName }} + port: + number: {{ $svcPort }} + {{- else }} + serviceName: {{ $fullName }} + servicePort: {{ $svcPort }} + {{- end }} + {{- end }} + {{- end }} +{{- end }} diff --git a/charts/gecho/templates/service.yaml b/charts/gecho/templates/service.yaml new file mode 100644 index 0000000..7167243 --- /dev/null +++ b/charts/gecho/templates/service.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "gecho.fullname" . }} + labels: + {{- include "gecho.labels" . | nindent 4 }} +spec: + type: {{ .Values.service.type }} + ports: + - port: {{ .Values.service.port }} + targetPort: http + protocol: TCP + name: http + selector: + {{- include "gecho.selectorLabels" . | nindent 4 }} diff --git a/charts/gecho/templates/serviceaccount.yaml b/charts/gecho/templates/serviceaccount.yaml new file mode 100644 index 0000000..b0ff1c3 --- /dev/null +++ b/charts/gecho/templates/serviceaccount.yaml @@ -0,0 +1,12 @@ +{{- if .Values.serviceAccount.create -}} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "gecho.serviceAccountName" . }} + labels: + {{- include "gecho.labels" . | nindent 4 }} + {{- with .Values.serviceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +{{- end }} diff --git a/charts/gecho/templates/tests/test-connection.yaml b/charts/gecho/templates/tests/test-connection.yaml new file mode 100644 index 0000000..f4a4682 --- /dev/null +++ b/charts/gecho/templates/tests/test-connection.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Pod +metadata: + name: "{{ include "gecho.fullname" . }}-test-connection" + labels: + {{- include "gecho.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": test +spec: + containers: + - name: wget + image: busybox + command: ['wget'] + args: ['{{ include "gecho.fullname" . }}:{{ .Values.service.port }}'] + restartPolicy: Never diff --git a/charts/gecho/values.yaml b/charts/gecho/values.yaml new file mode 100644 index 0000000..ed4be44 --- /dev/null +++ b/charts/gecho/values.yaml @@ -0,0 +1,84 @@ +# Default values for gecho. +# This is a YAML-formatted file. +# Declare variables to be passed into your templates. + +replicaCount: 1 +maxRequests: "" + +image: + repository: docker.io/tandrade/gecho + pullPolicy: IfNotPresent + # Overrides the image tag whose default is the chart appVersion. + tag: "" + +imagePullSecrets: [] +nameOverride: "" +fullnameOverride: "" + +serviceAccount: + # Specifies whether a service account should be created + create: true + # Annotations to add to the service account + annotations: {} + # The name of the service account to use. + # If not set and create is true, a name is generated using the fullname template + name: "" + +podAnnotations: {} + +podSecurityContext: {} + # fsGroup: 2000 + +securityContext: {} + # capabilities: + # drop: + # - ALL + # readOnlyRootFilesystem: true + # runAsNonRoot: true + # runAsUser: 1000 + +service: + type: ClusterIP + port: 80 + targetPort: 8080 + +ingress: + enabled: false + className: "" + annotations: {} + # kubernetes.io/ingress.class: nginx + # kubernetes.io/tls-acme: "true" + hosts: + - host: chart-example.local + paths: + - path: / + pathType: ImplementationSpecific + tls: [] + # - secretName: chart-example-tls + # hosts: + # - chart-example.local + +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:'. + # limits: + # cpu: 100m + # memory: 128Mi + # requests: + # cpu: 100m + # memory: 128Mi + +autoscaling: + enabled: false + minReplicas: 1 + maxReplicas: 100 + targetCPUUtilizationPercentage: 80 + # targetMemoryUtilizationPercentage: 80 + +nodeSelector: {} + +tolerations: [] + +affinity: {} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..981c8cb --- /dev/null +++ b/go.mod @@ -0,0 +1,10 @@ +module github.com/wolviecb/gecho + +go 1.19 + +require ( + github.com/gorilla/handlers v1.5.1 + github.com/gorilla/mux v1.8.0 +) + +require github.com/felixge/httpsnoop v1.0.1 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..daba3c0 --- /dev/null +++ b/go.sum @@ -0,0 +1,6 @@ +github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8SPQ= +github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= +github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= diff --git a/main.go b/main.go new file mode 100644 index 0000000..ae52755 --- /dev/null +++ b/main.go @@ -0,0 +1,94 @@ +package main + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "os" + "strconv" + "sync" + + "github.com/gorilla/handlers" + "github.com/gorilla/mux" +) + +var ( + l int + C counter +) + +type counter struct { + mu sync.Mutex + n int +} + +func (c *counter) Add() { + c.mu.Lock() + c.n++ + c.mu.Unlock() +} + +func (c *counter) Get() int { + c.mu.Lock() + n := c.n + c.mu.Unlock() + return n +} + +func (c *counter) Reset() { + c.mu.Lock() + c.n = 0 + c.mu.Unlock() +} + +func getenv(k string, d int) int { + v := os.Getenv(k) + if len(v) == 0 { + return d + } + i, err := strconv.Atoi(v) + if err != nil { + log.Fatalf("Invalid Value, %s not a valid integer: %v", k, err) + } + return i +} + +func serve() bool { + return C.Get() < l +} + +func handler(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + jm, err := json.Marshal(r.PostForm) + if err != nil || !serve() { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintln(w, "why did you do that?") + C.Add() + return + } + fmt.Fprintf(w, "%v", string(jm)) + C.Add() +} + +func httpHealth() http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !serve() { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintf(w, `{"status":"FAIL","requests":"%v"}`, C.Get()) + return + } + fmt.Fprintf(w, `{"status":"ok","requests":"%v"}`, C.Get()) + } +} + +func main() { + l = getenv("MAX_REQUESTS", 500) + r := mux.NewRouter() + r.HandleFunc("/", handler). + Methods("POST") + r.HandleFunc("/healthz", httpHealth()). + Methods("GET") + logger := handlers.LoggingHandler(os.Stdout, r) + log.Fatal(http.ListenAndServe(":8080", logger)) +}