Skip to content

Commit

Permalink
blah
Browse files Browse the repository at this point in the history
  • Loading branch information
benc-uk committed Apr 7, 2020
1 parent b1f3b4c commit 9fea402
Show file tree
Hide file tree
Showing 22 changed files with 324 additions and 108 deletions.
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**/node_modules/**
46 changes: 46 additions & 0 deletions build/service.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# ===================================================================================
# === Stage 1: bleep bloop =========================
# ===================================================================================
FROM golang:1.14-alpine as go-build

ARG serviceName="SET_ON_COMMAND_LINE"
ARG version="0.0.1"
ARG buildInfo="Local manual builds"

WORKDIR /build

# Install system dependencies
RUN apk update && apk add git gcc musl-dev

# Fetch and cache Go modules
COPY services/go.mod .
COPY services/go.sum .
RUN go mod download

# Copy in Go source files
COPY services/$serviceName/ ./service
COPY services/common/ ./common

# Now run the build
# Disabling cgo results in a fully static binary that can run without C libs
# Also inject version and build details
RUN GO111MODULE=on CGO_ENABLED=0 GOOS=linux go build \
-ldflags "-X main.version=$version -X 'main.buildInfo=$buildInfo'" \
-o server ./service

# ================================================================================================
# === Stage 2: Fooo ===================================
# ================================================================================================
FROM alpine
WORKDIR /app

ARG servicePort=9000

# Copy the Go server binary
COPY --from=go-build /build/server .

EXPOSE $servicePort
ENV PORT=$servicePort

# That's it! Just run the server
CMD [ "./server"]
50 changes: 50 additions & 0 deletions deploy/app/api-gateway.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: api-gateway
labels:
app: api-gateway
spec:
replicas: 1
selector:
matchLabels:
app: api-gateway
template:
metadata:
labels:
app: api-gateway
annotations:
dapr.io/enabled: "true"
dapr.io/id: "api-gateway"
dapr.io/port: "9000"
spec:
containers:
- name: service
image: bcdemo.azurecr.io/dapr-store/api-gateway
imagePullPolicy: Always
ports:
- containerPort: 9000
env:
- name: DAPR_HTTP_PORT
value: "3500"
resources:
limits:
cpu: 200m
memory: 200M

---

kind: Service
apiVersion: v1
metadata:
name: api-gateway
labels:
app: api-gateway
spec:
selector:
app: api-gateway
ports:
- protocol: TCP
port: 80
targetPort: 9000
type: LoadBalancer
31 changes: 31 additions & 0 deletions deploy/app/orders.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders
labels:
app: orders
spec:
replicas: 1
selector:
matchLabels:
app: orders
template:
metadata:
labels:
app: orders
annotations:
dapr.io/enabled: "true"
dapr.io/id: "orders"
dapr.io/port: "9001"
spec:
containers:
- name: service
image: bcdemo.azurecr.io/dapr-store/orders
imagePullPolicy: Always
env:
- name: DAPR_HTTP_PORT
value: "3500"
resources:
limits:
cpu: 200m
memory: 200M
13 changes: 13 additions & 0 deletions deploy/dapr/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: default
spec:
httpPipeline:
handlers:
- name: uppercase
type: middleware.http.uppercase
mtls:
enabled: true
workloadCertTTL: "24h"
allowedClockSkew: "15m"
14 changes: 14 additions & 0 deletions deploy/dapr/state-redis.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: statestore
spec:
type: state.redis
metadata:
- name: redisHost
value: redis:6379
- name: redisPassword
value: ""

# helm install redis bitnami/redis --set "cluster.enabled=false,master.persistence.enabled=false"
# kubectl get secret --namespace default redis -o jsonpath="{.data.redis-password}" | base64 --decode
5 changes: 5 additions & 0 deletions deploy/state/ingress-values.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
controller:
podAnnotations:
dapr.io/enabled: "true"
dapr.io/id: "nginx-ingress"
dapr.io/port: "80"
41 changes: 41 additions & 0 deletions deploy/state/redis.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis
spec:
selector:
matchLabels:
app: redis
replicas: 1
template:
metadata:
labels:
app: redis
spec:
containers:
- name: master
image: redis
imagePullPolicy: IfNotPresent
resources:
limits:
cpu: 100m
memory: 100M
ports:
- containerPort: 6379

---

kind: Service
apiVersion: v1
metadata:
name: redis
labels:
app: redis
spec:
selector:
app: redis
ports:
- protocol: TCP
port: 6379
targetPort: 6379
type: ClusterIP
17 changes: 17 additions & 0 deletions etc/build-images.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/bin/bash
set -e

ACR_NAME="bcdemo"

docker build . -f build/service.Dockerfile \
--build-arg serviceName=api-gateway \
--build-arg servicePort=9000 \
-t $ACR_NAME.azurecr.io/dapr-store/api-gateway

docker build . -f build/service.Dockerfile \
--build-arg serviceName=orders \
--build-arg servicePort=9001 \
-t $ACR_NAME.azurecr.io/dapr-store/orders

docker push $ACR_NAME.azurecr.io/dapr-store/api-gateway
docker push $ACR_NAME.azurecr.io/dapr-store/orders
4 changes: 4 additions & 0 deletions etc/restart-dapr.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
kubectl rollout restart -n dapr-system deploy/dapr-operator
kubectl rollout restart -n dapr-system deploy/dapr-placement
kubectl rollout restart -n dapr-system deploy/dapr-sentry
kubectl rollout restart -n dapr-system deploy/dapr-sidecar-injector
17 changes: 17 additions & 0 deletions etc/tests.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
GET http://localhost:9000/healthz
###

GET http://localhost:9000/status
###

GET http://localhost:9000/api/orders/6
###
GET http://localhost:45949/v1.0/invoke/orders/method/foo
###
GET http://localhost:9000/api/forUser/1


###
GET http://localhost:9001/6
###
GET http://localhost:9001/forUser/1
3 changes: 2 additions & 1 deletion services/api-gateway/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ func main() {
router.HandleFunc("/status", api.Status)
router.HandleFunc("/api/status", api.Status)

router.PathPrefix("/api/orders").HandlerFunc(api.ordersAPI)
// Catch API calls in stanard REST format
router.PathPrefix("/api/{service}/{restOfURL:.*}").HandlerFunc(api.daprProxy)

// Start server
log.Printf("### Server listening on %v\n", serverPort)
Expand Down
55 changes: 41 additions & 14 deletions services/api-gateway/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,53 @@ import (
"fmt"
"io/ioutil"
"net/http"

"github.com/benc-uk/dapr-store/common"

"github.com/gorilla/mux"
)

//
// Call Orders service
// Make a generic service to service call with Dapr
//
func (h API) ordersAPI(resp http.ResponseWriter, req *http.Request) {
resp.Header().Add("Content-Type", "application/json")
func (h API) daprProxy(resp http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)

// Proxy call via Dapr sidecar
// In format invoke/{service}/method/{methodPath}
invokeURL := fmt.Sprintf(
"http://localhost:%d/v1.0/invoke/%s/method/%s",
daprPort,
vars["service"],
vars["restOfURL"],
)
fmt.Println("### Making proxy invoke call to:", invokeURL)
proxyResp, err := http.Get(invokeURL)

// Check major / network errors
if err != nil {
common.SendProblem(resp, "", "Dapr network error", 502, err.Error())
return
}

// HTTP errors could be downstream is dead/404 or a error returned
if proxyResp.StatusCode < 200 || proxyResp.StatusCode > 299 {
common.SendProblem(resp, "", "Downstream service HTTP code not OK", proxyResp.StatusCode, "")
return
}

// Read the body, we assume it's JSON
defer proxyResp.Body.Close()
proxyBody, err := ioutil.ReadAll(proxyResp.Body)

url := fmt.Sprintf("http://localhost:%v/v1.0/invoke/orders/method/sss", daprPort)
fmt.Println(url)
r, err := http.Get(url)
// Yet more chance for a error
if err != nil {
fmt.Println("ERROR")
resp.Write([]byte("{error: \"BAD\"}"))
resp.WriteHeader(r.StatusCode)
common.SendProblem(resp, "", "Body IO error", 502, err.Error())
return
}
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
fmt.Println(string(body))
resp.WriteHeader(r.StatusCode)
resp.Write(body)

// Done, mimic the content type, status and body
resp.Header().Set("Content-Type", proxyResp.Header.Get("Content-Type"))
resp.WriteHeader(proxyResp.StatusCode)
resp.Write(proxyBody)
}
7 changes: 0 additions & 7 deletions services/api-gateway/tests.http

This file was deleted.

25 changes: 25 additions & 0 deletions services/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,38 @@ import (
"runtime"
)

// API holds a standard set of values for all services & APIs
type API struct {
ServiceName string
Healthy bool
Version string
BuildInfo string
}

// Problem in RFC-7807 format
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status,omitempty"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
}

//
// NewProblem creates a problem object
//
func SendProblem(resp http.ResponseWriter, probtype string, title string, sc int, detail string) {
p := Problem{
Type: "https://dapr.io/" + probtype,
Title: title,
Status: sc,
Detail: detail,
}
resp.WriteHeader(sc)
resp.Header().Add("Content-Type", "application/json")
json.NewEncoder(resp).Encode(p)
}

//
// HealthCheck - Simple health check endpoint, returns 204 when healthy
//
Expand Down
11 changes: 0 additions & 11 deletions services/components/pubsub.yaml

This file was deleted.

Loading

0 comments on commit 9fea402

Please sign in to comment.