diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index c635306..ae36398 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -11,6 +11,28 @@ permissions: packages: write jobs: + charts: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - run: git fetch --force --tags + - uses: azure/setup-helm@v3 + with: + version: latest + token: ${{ secrets.GITHUB_TOKEN }} + - run: | + ref="$GITHUB_REF_NAME" + chart_version="0.2.2" + echo "$GITHUB_TOKEN" | helm registry login ghcr.io --username=oauth-token --password-stdin + cp README.md charts/gitlab-goproxy/ + helm package charts/gitlab-goproxy --app-version "$ref" --version "$chart_version" + + echo "Creating chart release $ref / $chart_version" + helm push "gitlab-goproxy-$chart_version.tgz" "oci://ghcr.io/$GITHUB_REPOSITORY/helm-charts" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} goreleaser: runs-on: ubuntu-latest steps: diff --git a/README.md b/README.md index 537ec64..6ca592f 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,38 @@ # GitLab GoProxy This project contains an implementation of the [`GOPROXY` protocol](https://go.dev/ref/mod#goproxy-protocol) that stores data in the [GitLab Generic Package Repository](https://docs.gitlab.com/ee/user/packages/generic_packages/). + +## Getting started + +1. In GitLab, create a project that you intend on using to store packages. + > We recommend creating a new project otherwise it will make it hard to find any pre-existing packages. +2. Create a [project](https://docs.gitlab.com/ee/user/project/settings/project_access_tokens.html) or group access token with the `api` scope. +3. Create a Kubernetes secret using the token we just created: + ```shell + export GOPROXY_TOKEN= + kubectl create secret generic goproxy-token --from-literal=token=$GOPROXY_TOKEN + ``` +4. Create a `values.yaml` file with at least the following: + ```yaml + gitlab: + url: https://gitlab.example.com + projectId: 123 # numeric ID of the project we created + tokenSecretRef: + name: goproxy-token + key: token + ``` + There's plenty more that can be figured, but we will leave that as an exercise to the reader. +5. Deploy the application: + ```shell + helm install goproxy oci://ghcr.io/djcass44/gitlab-goproxy/helm-charts/gitlab-goproxy -f values.yaml + ``` + > We recommend using a GitOps tool (e.g., FluxCD, ArgoCD) rather than doing this manually. + +## Usage + +Once the application has been deployed, using it is as simple as setting the `GOPROXY` environment variable: + +```shell +export GOPROXY="https://goproxy.example.org" +go mod download +``` diff --git a/artifacthub-repo.yml b/artifacthub-repo.yml new file mode 100644 index 0000000..bc8360a --- /dev/null +++ b/artifacthub-repo.yml @@ -0,0 +1,4 @@ +repositoryID: "68bdb7e5-dc94-424f-9939-ab27d64f5cb2" +owners: + - name: djcass44 + email: django@dcas.dev \ No newline at end of file diff --git a/charts/gitlab-goproxy/.helmignore b/charts/gitlab-goproxy/.helmignore new file mode 100644 index 0000000..0e8a0eb --- /dev/null +++ b/charts/gitlab-goproxy/.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/gitlab-goproxy/Chart.yaml b/charts/gitlab-goproxy/Chart.yaml new file mode 100644 index 0000000..8b1209a --- /dev/null +++ b/charts/gitlab-goproxy/Chart.yaml @@ -0,0 +1,24 @@ +apiVersion: v2 +name: gitlab-goproxy +description: A Helm chart for Kubernetes + +# A chart can be either an 'application' or a 'library' chart. +# +# Application charts are a collection of templates that can be packaged into versioned archives +# to be deployed. +# +# Library charts provide useful utilities or functions for the chart developer. They're included as +# a dependency of application charts to inject those utilities and functions into the rendering +# pipeline. Library charts do not define any templates and therefore cannot be deployed. +type: application + +# This is the chart version. This version number should be incremented each time you make changes +# to the chart and its templates, including the app version. +# Versions are expected to follow Semantic Versioning (https://semver.org/) +version: 0.0.0 + +# This is the version number of the application being deployed. This version number should be +# incremented each time you make changes to the application. Versions are not expected to +# follow Semantic Versioning. They should reflect the version the application is using. +# It is recommended to use it with quotes. +appVersion: "0.0.0" diff --git a/charts/gitlab-goproxy/templates/NOTES.txt b/charts/gitlab-goproxy/templates/NOTES.txt new file mode 100644 index 0000000..3a8dd2f --- /dev/null +++ b/charts/gitlab-goproxy/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 "gitlab-goproxy.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 "gitlab-goproxy.fullname" . }}' + export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "gitlab-goproxy.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 "gitlab-goproxy.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/gitlab-goproxy/templates/_helpers.tpl b/charts/gitlab-goproxy/templates/_helpers.tpl new file mode 100644 index 0000000..a92e55f --- /dev/null +++ b/charts/gitlab-goproxy/templates/_helpers.tpl @@ -0,0 +1,62 @@ +{{/* +Expand the name of the chart. +*/}} +{{- define "gitlab-goproxy.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 "gitlab-goproxy.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 "gitlab-goproxy.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Common labels +*/}} +{{- define "gitlab-goproxy.labels" -}} +helm.sh/chart: {{ include "gitlab-goproxy.chart" . }} +{{ include "gitlab-goproxy.selectorLabels" . }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{/* +Selector labels +*/}} +{{- define "gitlab-goproxy.selectorLabels" -}} +app.kubernetes.io/name: {{ include "gitlab-goproxy.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} + +{{/* +Create the name of the service account to use +*/}} +{{- define "gitlab-goproxy.serviceAccountName" -}} +{{- if .Values.serviceAccount.create }} +{{- default (include "gitlab-goproxy.fullname" .) .Values.serviceAccount.name }} +{{- else }} +{{- default "default" .Values.serviceAccount.name }} +{{- end }} +{{- end }} diff --git a/charts/gitlab-goproxy/templates/deployment.yaml b/charts/gitlab-goproxy/templates/deployment.yaml new file mode 100644 index 0000000..a9b5773 --- /dev/null +++ b/charts/gitlab-goproxy/templates/deployment.yaml @@ -0,0 +1,82 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "gitlab-goproxy.fullname" . }} + labels: + {{- include "gitlab-goproxy.labels" . | nindent 4 }} +spec: + {{- if not .Values.autoscaling.enabled }} + replicas: {{ .Values.replicaCount }} + {{- end }} + selector: + matchLabels: + {{- include "gitlab-goproxy.selectorLabels" . | nindent 6 }} + template: + metadata: + {{- with .Values.podAnnotations }} + annotations: + {{- toYaml . | nindent 8 }} + {{- end }} + labels: + {{- include "gitlab-goproxy.selectorLabels" . | nindent 8 }} + spec: + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + serviceAccountName: {{ include "gitlab-goproxy.serviceAccountName" . }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + volumes: + - name: tmp + emptyDir: {} + containers: + - name: {{ .Chart.Name }} + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + image: "{{ .Values.image.registry }}/{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + env: + - name: APP_GITLAB_URL + value: {{ .Values.gitlab.url }} + - name: APP_GITLAB_PROJECT_ID + value: {{ .Values.gitlab.projectId | quote }} + - name: APP_GITLAB_TOKEN + valueFrom: + secretKeyRef: + name: {{ .Values.gitlab.tokenSecretRef.name }} + key: {{ .Values.gitlab.tokenSecretRef.key }} + - name: APP_GITLAB_HIDE_PACKAGES + value: {{ .Values.gitlab.hidePackages | quote }} + ports: + - name: http + containerPort: 8080 + protocol: TCP + - name: probes + containerPort: 8081 + protocol: TCP + volumeMounts: + - mountPath: /tmp + name: tmp + livenessProbe: + httpGet: + path: /livez + port: probes + readinessProbe: + httpGet: + path: /readyz + port: probes + 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/gitlab-goproxy/templates/hpa.yaml b/charts/gitlab-goproxy/templates/hpa.yaml new file mode 100644 index 0000000..67afdf3 --- /dev/null +++ b/charts/gitlab-goproxy/templates/hpa.yaml @@ -0,0 +1,28 @@ +{{- if .Values.autoscaling.enabled }} +apiVersion: autoscaling/v2beta1 +kind: HorizontalPodAutoscaler +metadata: + name: {{ include "gitlab-goproxy.fullname" . }} + labels: + {{- include "gitlab-goproxy.labels" . | nindent 4 }} +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: {{ include "gitlab-goproxy.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/gitlab-goproxy/templates/ingress.yaml b/charts/gitlab-goproxy/templates/ingress.yaml new file mode 100644 index 0000000..e61d262 --- /dev/null +++ b/charts/gitlab-goproxy/templates/ingress.yaml @@ -0,0 +1,61 @@ +{{- if .Values.ingress.enabled -}} +{{- $fullName := include "gitlab-goproxy.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 "gitlab-goproxy.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/gitlab-goproxy/templates/service.yaml b/charts/gitlab-goproxy/templates/service.yaml new file mode 100644 index 0000000..214db52 --- /dev/null +++ b/charts/gitlab-goproxy/templates/service.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "gitlab-goproxy.fullname" . }} + labels: + {{- include "gitlab-goproxy.labels" . | nindent 4 }} +spec: + type: {{ .Values.service.type }} + ports: + - port: {{ .Values.service.port }} + targetPort: http + protocol: TCP + name: http + selector: + {{- include "gitlab-goproxy.selectorLabels" . | nindent 4 }} diff --git a/charts/gitlab-goproxy/templates/serviceaccount.yaml b/charts/gitlab-goproxy/templates/serviceaccount.yaml new file mode 100644 index 0000000..e4ba52e --- /dev/null +++ b/charts/gitlab-goproxy/templates/serviceaccount.yaml @@ -0,0 +1,12 @@ +{{- if .Values.serviceAccount.create -}} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "gitlab-goproxy.serviceAccountName" . }} + labels: + {{- include "gitlab-goproxy.labels" . | nindent 4 }} + {{- with .Values.serviceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +{{- end }} diff --git a/charts/gitlab-goproxy/values.yaml b/charts/gitlab-goproxy/values.yaml new file mode 100644 index 0000000..0b9a892 --- /dev/null +++ b/charts/gitlab-goproxy/values.yaml @@ -0,0 +1,91 @@ +# Default values for gitlab-goproxy. +# This is a YAML-formatted file. +# Declare variables to be passed into your templates. + +gitlab: + url: "" + tokenSecretRef: + name: "" + key: "" + projectId: 0 + hidePackages: false + +replicaCount: 1 + +image: + registry: ghcr.io + repository: djcass44/gitlab-goproxy + 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 + +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/cmd/ggp/main.go b/cmd/ggp/main.go index f9b7be9..8834456 100644 --- a/cmd/ggp/main.go +++ b/cmd/ggp/main.go @@ -35,9 +35,10 @@ type environment struct { Port int `envconfig:"PORT" default:"8080"` LogLevel int `split_words:"true"` GitLab struct { - URL string `split_words:"true" required:"true"` - Token string `split_words:"true" required:"true"` - ProjectID int `split_words:"true" required:"true"` + URL string `split_words:"true" required:"true"` + Token string `split_words:"true" required:"true"` + ProjectID int `split_words:"true" required:"true"` + HidePackages bool `split_words:"true"` } } @@ -61,7 +62,7 @@ func main() { router.Use(logging.Middleware(log)) router.PathPrefix("/").Handler(&goproxy.Goproxy{ - Cacher: cache.NewGitLabCache(git, e.GitLab.ProjectID), + Cacher: cache.NewGitLabCache(git, e.GitLab.ProjectID, e.GitLab.HidePackages), ProxiedSUMDBs: nil, }) diff --git a/internal/cache/gitlab.go b/internal/cache/gitlab.go index 0b71a50..87d38c7 100644 --- a/internal/cache/gitlab.go +++ b/internal/cache/gitlab.go @@ -29,10 +29,11 @@ import ( "strings" ) -func NewGitLabCache(client *gitlab.Client, projectId int) *GitLabCache { +func NewGitLabCache(client *gitlab.Client, projectId int, hidePackages bool) *GitLabCache { return &GitLabCache{ - client: client, - projectId: projectId, + client: client, + projectId: projectId, + hidePackages: hidePackages, } } @@ -58,11 +59,12 @@ func (c *GitLabCache) Get(ctx context.Context, name string) (io.ReadCloser, erro } // return the data + log.Info("located cached module") return io.NopCloser(bytes.NewReader(data)), nil } func (c *GitLabCache) Put(ctx context.Context, name string, content io.ReadSeeker) error { - log := logr.FromContextOrDiscard(ctx).WithValues("name", name) + log := logr.FromContextOrDiscard(ctx).WithValues("name", name, "hidden", c.hidePackages) log.Info("uploading module to cache") pkg, err := parser.NewPackage(name) @@ -71,11 +73,18 @@ func (c *GitLabCache) Put(ctx context.Context, name string, content io.ReadSeeke } // upload the given data - _, _, err = c.client.GenericPackages.PublishPackageFile(c.projectId, safeName(pkg.Name), pkg.Version, safeName(pkg.String()), content, &gitlab.PublishPackageFileOptions{}) + status := gitlab.PackageDefault + if c.hidePackages { + status = gitlab.PackageHidden + } + _, _, err = c.client.GenericPackages.PublishPackageFile(c.projectId, safeName(pkg.Name), pkg.Version, safeName(pkg.String()), content, &gitlab.PublishPackageFileOptions{ + Status: gitlab.GenericPackageStatus(status), + }) if err != nil { log.Error(err, "failed to publish package") return err } + log.Info("successfully published package") return nil } diff --git a/internal/cache/types.go b/internal/cache/types.go index 27304d5..9d8d6f7 100644 --- a/internal/cache/types.go +++ b/internal/cache/types.go @@ -20,6 +20,7 @@ package cache import "github.com/xanzy/go-gitlab" type GitLabCache struct { - client *gitlab.Client - projectId int + client *gitlab.Client + projectId int + hidePackages bool }