Skip to content

Commit

Permalink
set webhook to receive update values
Browse files Browse the repository at this point in the history
  • Loading branch information
Mostela committed Dec 28, 2023
1 parent 439846c commit 27bd7a7
Show file tree
Hide file tree
Showing 13 changed files with 225 additions and 51 deletions.
98 changes: 98 additions & 0 deletions .github/workflows/docker.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
name: Docker

# This workflows uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.

on:
schedule:
- cron: '24 7 * * *'
push:
branches: [ "main" ]
# Publish semver tags as releases.
tags: [ 'v*.*.*' ]
pull_request:
branches: [ "main" ]

env:
# Use docker.io for Docker Hub if empty
REGISTRY: ghcr.io
# github.repository as <account>/<repo>
IMAGE_NAME: ${{ github.repository }}


jobs:
build:

runs-on: ubuntu-latest
permissions:
contents: read
packages: write
# This is used to complete the identity challenge
# with sigstore/fulcio when running outside of PRs.
id-token: write

steps:
- name: Checkout repository
uses: actions/checkout@v3

# Install the cosign tool except on PR
# https://github.com/sigstore/cosign-installer
- name: Install cosign
if: github.event_name != 'pull_request'
uses: sigstore/cosign-installer@6e04d228eb30da1757ee4e1dd75a0ec73a653e06 #v3.1.1
with:
cosign-release: 'v2.1.1'

# Set up BuildKit Docker container builder to be able to build
# multi-platform images and export cache
# https://github.com/docker/setup-buildx-action
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0

# Login against a Docker registry except on PR
# https://github.com/docker/login-action
- name: Log into registry ${{ env.REGISTRY }}
if: github.event_name != 'pull_request'
uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

# Extract metadata (tags, labels) for Docker
# https://github.com/docker/metadata-action
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

# Build and push Docker image with Buildx (don't push on PR)
# https://github.com/docker/build-push-action
- name: Build and push Docker image
id: build-and-push
uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max

# Sign the resulting Docker image digest except on PRs.
# This will only write to the public Rekor transparency log when the Docker
# repository is public to avoid leaking data. If you would like to publish
# transparency data even for private images, pass --force to cosign below.
# https://github.com/sigstore/cosign
- name: Sign the published Docker image
if: ${{ github.event_name != 'pull_request' }}
env:
# https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#using-an-intermediate-environment-variable
TAGS: ${{ steps.meta.outputs.tags }}
DIGEST: ${{ steps.build-and-push.outputs.digest }}
# This step uses the identity token to provision an ephemeral certificate
# against the sigstore community Fulcio instance.
run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}
File renamed without changes.
8 changes: 8 additions & 0 deletions example/consumer/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
FROM python
WORKDIR app/
LABEL authors="joao"
EXPOSE 8000
COPY requirements.txt app/
RUN pip install -r requirements.txt
COPY . app/
ENTRYPOINT uvicorn main:app --host 0.0.0.0 --port 8000
2 changes: 1 addition & 1 deletion example/consumer.yml → example/consumer/deployment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ spec:
protocol: TCP
env:
- name: REMOTE_CONFIG_URL
value: http://control.producer-control.svc.cluster.local:8080
value: http://producer-control-service.producer-control.svc.cluster.local:8080/keyrotation
---
apiVersion: v1
kind: Service
Expand Down
35 changes: 35 additions & 0 deletions example/consumer/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import os

import requests
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


def startup_remote_config():
return requests.get(os.getenv('REMOTE_CONFIG_URL')).json()


remote_config = startup_remote_config()


class DataRemote(BaseModel):
key: str
value: str


@app.get("/")
async def root():
return {"person_name": remote_config['person']}


@app.get("/healthcheck")
async def healthcheck():
return {"status": "ok"}


@app.post("/remoteconfig")
async def remoteconfig(data_remote: DataRemote):
remote_config.__setitem__(data_remote.key, data_remote.value)
return {"status": "ok"}
4 changes: 4 additions & 0 deletions example/consumer/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
requests~=2.31.0
fastapi~=0.104.1
pydantic~=2.4.2
uvicorn
18 changes: 9 additions & 9 deletions kubernetes/deployment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,30 +22,31 @@ metadata:
name: producer-control
namespace: producer-control
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: producer-control
name: producer-control-cr
namespace: producer-control
labels:
app: producer-control
rules:
- apiGroups: [""]
resources: ["pods", "configmaps"]
verbs: ["get", "list", "update"]
- apiGroups: [ "" ]
resources: [ "pods", "configmaps" ]
verbs: ["get", "list", "update" ]
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: producer-control
namespace: producer-control
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: producer-control
kind: ClusterRole
name: producer-control-cr
subjects:
- kind: ServiceAccount
name: producer-control
namespace: producer-control
---
kind: Deployment
apiVersion: apps/v1
Expand Down Expand Up @@ -118,7 +119,6 @@ metadata:
spec:
type: NodePort
externalTrafficPolicy: Cluster
externalName: control
selector:
app: producer-control
ports:
Expand Down
19 changes: 13 additions & 6 deletions src/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,23 @@ package src
import "os"

type GlobalConfigKeyRotation struct {
Namespace string
ConfigMapName string
Debug bool
Namespace string
ConfigMapName string
Debug bool
EndpointSetValues string
}

func ConfigGlobal() GlobalConfigKeyRotation {
endpointConfig := os.Getenv("ENDPOINT_SET_VALUES")
if endpointConfig == "" {
endpointConfig = "remoteconfig"
}

config := GlobalConfigKeyRotation{
Namespace: os.Getenv("K8S_NAMESPACE"),
ConfigMapName: os.Getenv("K8S_CONFIGMAP_NAME"),
Debug: os.Getenv("DEBUG") == "true",
Namespace: os.Getenv("K8S_NAMESPACE"),
ConfigMapName: os.Getenv("K8S_CONFIGMAP_NAME"),
Debug: os.Getenv("DEBUG") == "true",
EndpointSetValues: os.Getenv("ENDPOINT_SET_VALUES"),
}
return config
}
28 changes: 17 additions & 11 deletions src/controllers/keys_rotation.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,18 @@ import (
"net/http"
)

type ServiceBody struct {
App string `json:"app"`
Namespace string `json:"namespace"`
}

type NewKeyRotationBody struct {
Key string `json:"key"`
Value string `json:"value"`
Service string `json:"service"`
Key string `json:"key"`
Value string `json:"value"`
Service ServiceBody `json:"service"`
}

func ReturnConfigs() k8s.ConfigMapConfig {
func SetConfigs() k8s.ConfigMapConfig {
configCM := k8s.ConfigMapConfig{
Name: config.ConfigGlobal().ConfigMapName,
Namespace: config.ConfigGlobal().Namespace,
Expand All @@ -23,7 +28,7 @@ func ReturnConfigs() k8s.ConfigMapConfig {

func SetNewKeyRotation(w *gin.Context) {
var dataBody NewKeyRotationBody
configCM := ReturnConfigs()
configCM := SetConfigs()
if err := w.Bind(&dataBody); err != nil {
w.JSON(http.StatusBadRequest, gin.H{"status": "fail", "message": err.Error()})
return
Expand All @@ -39,8 +44,9 @@ func SetNewKeyRotation(w *gin.Context) {
}

_, errorSendRequest := k8s.SendRequestContainerHandler(&k8s.DeploymentConfig{
Namespace: configCM.Namespace,
Name: dataBody.Service,
Namespace: dataBody.Service.Namespace,
Name: dataBody.Service.App,
EndpointSetValues: config.ConfigGlobal().EndpointSetValues,
}, configMapData)

if errorSendRequest != nil {
Expand All @@ -53,10 +59,10 @@ func SetNewKeyRotation(w *gin.Context) {
}

func ReturnKeysRotation(w *gin.Context) {
configCM := ReturnConfigs()
listConfigs, errorListConfig := k8s.ReturnConfigMapHandler(configCM)
if errorListConfig != nil {
w.JSON(http.StatusBadRequest, gin.H{"status": "fail", "message": errorListConfig.Error()})
configCM := SetConfigs()
listConfigs, err := k8s.ReturnConfigMapHandler(configCM)
if err != nil {
w.JSON(http.StatusBadRequest, gin.H{"status": "fail", "message": err.Error()})
return
}
w.JSON(http.StatusOK, &listConfigs.Data)
Expand Down
12 changes: 7 additions & 5 deletions src/services/pods.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import (
)

type DeploymentConfig struct {
Namespace string
Name string
Namespace string
Name string
EndpointSetValues string
}

type PodInfo struct {
Expand Down Expand Up @@ -52,10 +53,11 @@ func SendRequestContainerHandler(config *DeploymentConfig, dataConfigMap ConfigM
for _, pod := range containerList {
status, err := UpdateKeysRequest(KeyUpdate{
ConfigMapData: BodyKeyUpdate{
DataValue: dataConfigMap.Value,
Key: dataConfigMap.Key,
Value: dataConfigMap.Value,
Key: dataConfigMap.Key,
},
PodInfo: pod,
PodInfo: pod,
EndpointSetValues: config.EndpointSetValues,
})
if err != nil {
fmt.Printf("%s", err.Error())
Expand Down
11 changes: 6 additions & 5 deletions src/services/update_keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ import (
)

type BodyKeyUpdate struct {
DataValue string `json:"dataValue"`
Key string `json:"key"`
Value string `json:"value"`
Key string `json:"key"`
}

type KeyUpdate struct {
ConfigMapData BodyKeyUpdate
PodInfo PodInfo
ConfigMapData BodyKeyUpdate
PodInfo PodInfo
EndpointSetValues string
}

func UpdateKeysRequest(keyValue KeyUpdate) (bool, error) {
Expand All @@ -23,7 +24,7 @@ func UpdateKeysRequest(keyValue KeyUpdate) (bool, error) {
return false, errorBodyUpdate
}
response, errorResponse := http.Post(
fmt.Sprintf("http://%s:%d/remoteconfig", keyValue.PodInfo.IP, keyValue.PodInfo.Port),
fmt.Sprintf("http://%s:%d/%s", keyValue.PodInfo.IP, keyValue.PodInfo.Port, keyValue.EndpointSetValues),
"application/json; charset=utf-8",
bytes.NewBuffer(bodyUpdate),
)
Expand Down
20 changes: 20 additions & 0 deletions test/load/low.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
vus: 5,
duration: '5m',
};

const listNameValid = ['Obama', 'LeBron', 'Jackson']

export default () => {
const res = http.get('http://127.0.0.1/');
check(res, {
'is status 200': (r) => r.status === 200,
});
check(res, {
'return name': (r) => listNameValid.includes(JSON.parse(r.body)['person_name']),
});
sleep(1);
};
Loading

0 comments on commit 27bd7a7

Please sign in to comment.