Skip to content

Commit

Permalink
feat: Add source code for "Deploy Applications with Kubernetes Locall…
Browse files Browse the repository at this point in the history
…y" chapter - part 2 (#44)
  • Loading branch information
igor-baiborodine authored Mar 17, 2023
1 parent 789f661 commit bd59b6e
Show file tree
Hide file tree
Showing 19 changed files with 923 additions and 39 deletions.
14 changes: 14 additions & 0 deletions DeployLocally/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
FROM golang:1.19-alpine AS build
WORKDIR /go/src/proglog
COPY . .
RUN CGO_ENABLED=0 go build -o /go/bin/proglog ./cmd/proglog
RUN GRPC_HEALTH_PROBE_VERSION=v0.3.2 && \
wget -qO/go/bin/grpc_health_probe \
https:#github.com/grpc-ecosystem/grpc-health-probe/releases/download/\
${GRPC_HEALTH_PROBE_VERSION}/grpc_health_probe-linux-amd64 && \
chmod +x /go/bin/grpc_health_probe

FROM scratch
COPY --from=build /go/bin/proglog /bin/proglog
COPY --from=build /go/bin/grpc_health_probe /bin/grpc_health_probe
ENTRYPOINT ["/bin/proglog"]
5 changes: 5 additions & 0 deletions DeployLocally/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,8 @@ gencert:
.PHONY: test
test:
go test -race ./...

TAG ?= 0.0.1

build-docker:
docker build -t github.com/igor-baiborodine/proglog:$(TAG) .
34 changes: 33 additions & 1 deletion DeployLocally/README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,41 @@
## Deploy Applications with Kubernetes Locally

### Tests
### Prerequisites

#### kubectl
```shell
$ curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
$ curl -LO "https://dl.k8s.io/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl.sha256"
$ echo "$(cat kubectl.sha256) kubectl" | sha256sum --check
$ chmod +x ./kubectl
$ sudo mv ./kubectl /usr/local/bin/kubectl
$ kubectl version --client
```

#### Kind
```shell
$ curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.17.0/kind-linux-amd64
$ chmod +x ./kind
$ sudo mv ./kind /usr/local/bin/kind
```

#### Helm
```shell
$ curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3
$ chmod 700 get_helm.sh
$ ./get_helm.sh
```

### Tests
```shell
$ make clean init compile
$ make gencerts
$ make test
```

### Run Docker Image in Kind Cluster
```shell
$ make build-docker
$ kind create cluster
$ kind load docker-image github.com/igor-baiborodine/proglog:0.0.1
```
31 changes: 31 additions & 0 deletions DeployLocally/cmd/getservers/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package main

import (
"context"
"flag"
"fmt"
"log"

"google.golang.org/grpc"

api "github.com/igor-baiborodine/proglog/api/v1"
)

func main() {
addr := flag.String("addr", ":8400", "service address")
flag.Parse()
conn, err := grpc.Dial(*addr, grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
client := api.NewLogClient(conn)
ctx := context.Background()
res, err := client.GetServers(ctx, &api.GetServersRequest{})
if err != nil {
log.Fatal(err)
}
fmt.Println("servers:")
for _, server := range res.Servers {
fmt.Printf("\t- %v\n", server)
}
}
153 changes: 153 additions & 0 deletions DeployLocally/cmd/proglog/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package main

import (
"log"
"os"
"os/signal"
"path"
"syscall"

"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/igor-baiborodine/proglog/internal/agent"
"github.com/igor-baiborodine/proglog/internal/config"
)

func main() {
cli := &cli{}

cmd := &cobra.Command{
Use: "proglog",
PreRunE: cli.setupConfig,
RunE: cli.run,
}

if err := setupFlags(cmd); err != nil {
log.Fatal(err)
}

if err := cmd.Execute(); err != nil {
log.Fatal(err)
}
}

type cli struct {
cfg cfg
}

type cfg struct {
agent.Config
ServerTLSConfig config.TLSConfig
PeerTLSConfig config.TLSConfig
}

func setupFlags(cmd *cobra.Command) error {
hostname, err := os.Hostname()
if err != nil {
log.Fatal(err)
}

cmd.Flags().String("config-file", "", "Path to config file.")

dataDir := path.Join(os.TempDir(), "proglog")
cmd.Flags().String("data-dir",
dataDir,
"Directory to store log and Raft data.")
cmd.Flags().String("node-name", hostname, "Unique server ID.")

cmd.Flags().String("bind-addr",
"127.0.0.1:8401",
"Address to bind Serf on.")
cmd.Flags().Int("rpc-port",
8400,
"Port for RPC clients (and Raft) connections.")
cmd.Flags().StringSlice("start-join-addrs",
nil,
"Serf addresses to join.")
cmd.Flags().Bool("bootstrap", false, "Bootstrap the cluster.")

cmd.Flags().String("acl-model-file", "", "Path to ACL model.")
cmd.Flags().String("acl-policy-file", "", "Path to ACL policy.")

cmd.Flags().String("server-tls-cert-file", "", "Path to server tls cert.")
cmd.Flags().String("server-tls-key-file", "", "Path to server tls key.")
cmd.Flags().String("server-tls-ca-file",
"",
"Path to server certificate authority.")

cmd.Flags().String("peer-tls-cert-file", "", "Path to peer tls cert.")
cmd.Flags().String("peer-tls-key-file", "", "Path to peer tls key.")
cmd.Flags().String("peer-tls-ca-file",
"",
"Path to peer certificate authority.")

return viper.BindPFlags(cmd.Flags())
}

func (c *cli) setupConfig(cmd *cobra.Command, args []string) error {
var err error

configFile, err := cmd.Flags().GetString("config-file")
if err != nil {
return err
}
viper.SetConfigFile(configFile)

if err = viper.ReadInConfig(); err != nil {
// it's ok if config file doesn't exist
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return err
}
}

c.cfg.DataDir = viper.GetString("data-dir")
c.cfg.NodeName = viper.GetString("node-name")
c.cfg.BindAddr = viper.GetString("bind-addr")
c.cfg.RPCPort = viper.GetInt("rpc-port")
c.cfg.StartJoinAddrs = viper.GetStringSlice("start-join-addrs")
c.cfg.Bootstrap = viper.GetBool("bootstrap")
c.cfg.ACLModelFile = viper.GetString("acl-mode-file")
c.cfg.ACLPolicyFile = viper.GetString("acl-policy-file")
c.cfg.ServerTLSConfig.CertFile = viper.GetString("server-tls-cert-file")
c.cfg.ServerTLSConfig.KeyFile = viper.GetString("server-tls-key-file")
c.cfg.ServerTLSConfig.CAFile = viper.GetString("server-tls-ca-file")
c.cfg.PeerTLSConfig.CertFile = viper.GetString("peer-tls-cert-file")
c.cfg.PeerTLSConfig.KeyFile = viper.GetString("peer-tls-key-file")
c.cfg.PeerTLSConfig.CAFile = viper.GetString("peer-tls-ca-file")

if c.cfg.ServerTLSConfig.CertFile != "" &&
c.cfg.ServerTLSConfig.KeyFile != "" {
c.cfg.ServerTLSConfig.Server = true
c.cfg.Config.ServerTLSConfig, err = config.SetupTLSConfig(
c.cfg.ServerTLSConfig,
)
if err != nil {
return err
}
}

if c.cfg.PeerTLSConfig.CertFile != "" &&
c.cfg.PeerTLSConfig.KeyFile != "" {
c.cfg.Config.PeerTLSConfig, err = config.SetupTLSConfig(
c.cfg.PeerTLSConfig,
)
if err != nil {
return err
}
}

return nil
}

func (c *cli) run(cmd *cobra.Command, args []string) error {
var err error
agent, err := agent.New(c.cfg.Config)
if err != nil {
return err
}
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
<-sigc
return agent.Shutdown()
}
22 changes: 22 additions & 0 deletions DeployLocally/deploy/proglog/.helmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# 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
*~
# Various IDEs
.project
.idea/
*.tmproj
.vscode/
21 changes: 21 additions & 0 deletions DeployLocally/deploy/proglog/Chart.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
apiVersion: v2
name: proglog
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.
version: 0.1.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.
appVersion: 1.16.0
63 changes: 63 additions & 0 deletions DeployLocally/deploy/proglog/templates/_helpers.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "proglog.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 "proglog.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 "proglog.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

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

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

{{/*
Create the name of the service account to use
*/}}
{{- define "proglog.serviceAccountName" -}}
{{- if .Values.serviceAccount.create -}}
{{ default (include "proglog.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
{{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}
22 changes: 22 additions & 0 deletions DeployLocally/deploy/proglog/templates/service.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
apiVersion: v1
kind: Service
metadata:
name: {{ include "proglog.fullname" . }}
namespace: {{ .Release.Namespace }}
labels: {{ include "proglog.labels" . | nindent 4 }}
spec:
clusterIP: None
publishNotReadyAddresses: true
ports:
- name: rpc
port: {{ .Values.rpcPort }}
targetPort: {{ .Values.rpcPort }}
- name: serf-tcp
protocol: "TCP"
port: {{ .Values.serfPort }}
targetPort: {{ .Values.serfPort }}
- name: serf-udp
protocol: "UDP"
port: {{ .Values.serfPort }}
targetPort: {{ .Values.serfPort }}
selector: {{ include "proglog.selectorLabels" . | nindent 4 }}
Loading

0 comments on commit bd59b6e

Please sign in to comment.