Skip to content

Commit

Permalink
refactor(*)!: Refactor for better maintainability
Browse files Browse the repository at this point in the history
Signed-off-by: Anurag Rajawat <[email protected]>
  • Loading branch information
anurag-rajawat committed Sep 17, 2024
1 parent a1d331c commit 0fb291c
Show file tree
Hide file tree
Showing 36 changed files with 1,374 additions and 2,939 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,5 @@ go.work.sum
*.swp
*.swo
*~

venv/
107 changes: 74 additions & 33 deletions deployments/sentryflow.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,45 +2,65 @@ apiVersion: v1
kind: Namespace
metadata:
name: sentryflow
labels:
istio-injection: disabled # avoid Istio sidecar-injection
pod-security.kubernetes.io/audit: privileged
pod-security.kubernetes.io/enforce: privileged
pod-security.kubernetes.io/warn: privileged
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: sentryflow
namespace: sentryflow
name: sentryflow-sa
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: sentryflow-cr
name: sentryflow
rules:
- apiGroups: ["*"]
verbs: ["*"]
resources: ["*"]
- apiGroups:
- networking.istio.io
verbs:
- get
- create
- delete
resources:
- envoyfilters
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: sentryflow-rb
name: sentryflow
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: sentryflow-cr
name: sentryflow
subjects:
- kind: ServiceAccount
- kind: ServiceAccount
name: sentryflow
namespace: sentryflow
---
apiVersion: v1
kind: ConfigMap
metadata:
name: config
namespace: sentryflow
name: sentryflow-sa
data:
config.yaml: |2-
receivers:
serviceMeshes:
- name: istio-sidecar
enable: true
exporter:
grpc:
port: 8080
debug:
enable: false
pprof:
port: 6060
---
apiVersion: apps/v1
kind: Deployment
metadata:
namespace: sentryflow
name: sentryflow
namespace: sentryflow
spec:
replicas: 1
selector:
Expand All @@ -51,17 +71,38 @@ spec:
labels:
app: sentryflow
spec:
serviceAccountName: sentryflow-sa
serviceAccountName: sentryflow
containers:
- name: sentryflow
image: 5gsec/sentryflow:v0.1
ports:
- name: otel-grpc
protocol: TCP
containerPort: 4317
- name: sentryflow-grpc
protocol: TCP
containerPort: 8080
- name: sentryflow
image: ttl.sh/sentryflow:24h
imagePullPolicy: Always
args:
- --config
- /var/lib/sentryflow/config.yaml
volumeMounts:
- mountPath: /var/lib/sentryflow/
name: config
ports:
- containerPort: 8080
name: exporter
protocol: TCP
- containerPort: 8081
name: filter-server
protocol: TCP
securityContext:
capabilities:
drop:
- ALL
readOnlyRootFilesystem: true
runAsNonRoot: true
runAsUser: 1111
allowPrivilegeEscalation: false
terminationGracePeriodSeconds: 30
volumes:
- name: config
configMap:
name: config
defaultMode: 420
---
apiVersion: v1
kind: Service
Expand All @@ -72,11 +113,11 @@ spec:
selector:
app: sentryflow
ports:
- name: otel-grpc
protocol: TCP
port: 4317
targetPort: 4317
- name: sentryflow-grpc
protocol: TCP
port: 8080
targetPort: 8080
- name: exporter
port: 8080
targetPort: 8080
protocol: TCP
- name: filter-server
port: 8081
targetPort: 8081
protocol: TCP
1 change: 1 addition & 0 deletions sentryflow/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
bin/
40 changes: 14 additions & 26 deletions sentryflow/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,36 +1,24 @@
# SPDX-License-Identifier: Apache-2.0
FROM golang:1.23 AS builder

### Builder
RUN mkdir -p /protobuf/golang

FROM golang:1.21-alpine3.17 as builder

RUN apk --no-cache update
RUN apk add --no-cache git clang llvm make gcc protobuf musl-dev
RUN apk add --update alpine-sdk

RUN go install github.com/golang/protobuf/protoc-gen-go@latest
RUN go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

RUN mkdir /sentryflow
RUN mkdir /protobuf

WORKDIR /protobuf
COPY /protobuf .
COPY protobuf/golang /protobuf/golang

WORKDIR /sentryflow
COPY /sentryflow .

RUN export CGO_ENABLED=1; export CC=gcc;
RUN go build -o sentryflow
COPY sentryflow/go.mod .
COPY sentryflow/go.sum .
RUN go mod download

### Make executable image
COPY sentryflow/cmd cmd/
COPY sentryflow/pkg pkg/
COPY sentryflow/main.go main.go
COPY sentryflow/Makefile Makefile

FROM alpine:3.17 as sentryflow
RUN make build

# RUN echo "@community http://dl-cdn.alpinelinux.org/alpine/edge/community" | tee -a /etc/apk/repositories
# RUN apk --no-cache update
# RUN apk add bash
FROM gcr.io/distroless/static-debian12

COPY --from=builder /sentryflow/sentryflow /
COPY --from=builder /sentryflow/bin/sentryflow /

CMD ["/sentryflow"]
ENTRYPOINT ["/sentryflow"]
108 changes: 56 additions & 52 deletions sentryflow/Makefile
Original file line number Diff line number Diff line change
@@ -1,60 +1,64 @@
# SPDX-License-Identifier: Apache-2.0
BINARY_NAME ?= sentryflow
REGISTRY ?= docker.io/5gsec
VERSION ?= $(shell git rev-parse HEAD)
BUILD_TS ?= $(shell date)
DOCKER_IMAGE ?= $(REGISTRY)/$(BINARY_NAME)
DOCKER_TAG ?= ${VERSION}
CONTAINER_TOOL ?= docker

PROG_NAME = sentryflow
IMAGE_NAME = 5gsec/$(PROG_NAME)
TAG = v0.1
.PHONY: help
help: ## Display this help
@awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m<target>\033[0m\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST)

.PHONY: build
build: gofmt golint gosec
go mod tidy
go build -o $(PROG_NAME)

.PHONY: clean
clean:
rm -f $(PROG_NAME)

.PHONY: gofmt
gofmt:
cd $(CURDIR); gofmt -w -s -d $(shell find . -type f -name '*.go' -print)

.PHONY: golint
golint:
ifeq (, $(shell which golint))
@{ \
set -e ;\
GOLINT_TEMP_DIR=$$(mktemp -d) ;\
cd $$GOLINT_TEMP_DIR ;\
go mod init tmp ;\
go get golang.org/x/lint/golint ;\
go install golang.org/x/lint/golint ;\
rm -rf $$GOLINT_TEMP_DIR ;\
}
endif
cd $(CURDIR); golint ./...
.DEFAULT_GOAL := help

##@ Development
.PHONY: run
run: fmt vet ## Run SentryFlow on your host
@go mod tidy;go run main.go

.PHONY: fmt
fmt: ## Run go fmt against code
@go fmt ./...

.PHONY: gosec
gosec:
ifeq (, $(shell which gosec))
@{ \
.PHONY: vet
vet: ## Run go vet against code
@go vet ./...

GOLANGCI_LINT = $(shell pwd)/bin/golangci-lint
GOLANGCI_LINT_VERSION ?= v1.60.3
golangci-lint:
@[ -f $(GOLANGCI_LINT) ] || { \
set -e ;\
GOSEC_TEMP_DIR=$$(mktemp -d) ;\
cd $$GOSEC_TEMP_DIR ;\
go mod init tmp ;\
go get github.com/securego/gosec/v2/cmd/gosec ;\
go install github.com/securego/gosec/v2/cmd/gosec ;\
rm -rf $$GOSEC_TEMP_DIR ;\
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(shell dirname $(GOLANGCI_LINT)) $(GOLANGCI_LINT_VERSION) ;\
}
endif
cd $(CURDIR); gosec -exclude=G402 ./...

.PHONY: build-image
build-image:
docker build -t $(IMAGE_NAME):$(TAG) -f ./Dockerfile ../
.PHONY: lint
lint: golangci-lint ## Run golangci-lint linter
@$(GOLANGCI_LINT) run

##@ Build

.PHONY: build
build: fmt vet ## Build SentryFlow binary
@CGO_ENABLED=0 go build -ldflags="-s \
-X 'main.Version=${VERSION}' \
-X 'main.CommitHash=${VERSION}' \
-X 'main.BuildTimestamp=${BUILD_TS}'" \
-o bin/"${BINARY_NAME}" main.go

.PHONY: clean-image
clean-image:
docker rmi $(IMAGE_NAME):$(TAG)
.PHONY: image
image: ## Build and push SentryFlow's container image
$(CONTAINER_TOOL) build -t ${DOCKER_IMAGE}:${DOCKER_TAG} -f Dockerfile ../
$(CONTAINER_TOOL) push ${DOCKER_IMAGE}:${DOCKER_TAG}

.PHONY: run-image
run-image:
docker run -it --rm $(IMAGE_NAME):$(TAG)
PLATFORMS ?= linux/arm64,linux/amd64
.PHONY: imagex
imagex: ## Build and push SentryFlow's container image for cross-platform support
# copy existing Dockerfile and insert --platform=${BUILDPLATFORM} into Dockerfile.cross, and preserve the original Dockerfile
sed -e '1 s/\(^FROM\)/FROM --platform=\$$\{BUILDPLATFORM\}/; t' -e ' 1,// s//FROM --platform=\$$\{BUILDPLATFORM\}/' Dockerfile > Dockerfile.cross
- $(CONTAINER_TOOL) buildx create --name project-v3-builder
$(CONTAINER_TOOL) buildx use project-v3-builder
- $(CONTAINER_TOOL) buildx build --push --platform=$(PLATFORMS) --tag ${DOCKER_IMAGE}:${DOCKER_TAG} -f Dockerfile.cross ../ || { $(CONTAINER_TOOL) buildx rm project-v3-builder; rm Dockerfile.cross; exit 1; }
- $(CONTAINER_TOOL) buildx rm project-v3-builder
rm Dockerfile.cross
53 changes: 53 additions & 0 deletions sentryflow/cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package cmd

import (
"context"

"github.com/spf13/cobra"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
ctrl "sigs.k8s.io/controller-runtime"

"github.com/5GSEC/SentryFlow/pkg/core"
"github.com/5GSEC/SentryFlow/pkg/util"
)

var (
configFilePath string
kubeConfig string
development bool
logger *zap.SugaredLogger
)

func init() {
RootCmd.PersistentFlags().StringVar(&configFilePath, "config", "", "config file path")
RootCmd.PersistentFlags().StringVar(&kubeConfig, "kubeconfig", "", "kubeconfig file path")
RootCmd.PersistentFlags().BoolVar(&development, "development", false, "run in development mode")
}

var RootCmd = &cobra.Command{
Use: "sentryflow",
Run: func(cmd *cobra.Command, args []string) {
run()
},
}

func run() {
initLogger(development)
logBuildInfo()
ctx := context.WithValue(ctrl.SetupSignalHandler(), util.LoggerCtxKey, logger)
core.Run(ctx, configFilePath, kubeConfig)
}

func initLogger(development bool) {
cfg := zap.NewProductionConfig()
cfg.EncoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
if development {
cfg = zap.NewDevelopmentConfig()
cfg.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
}
cfg.EncoderConfig.TimeKey = "timestamp"
cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
coreLogger, _ := cfg.Build()
logger = coreLogger.Sugar()
}
Loading

0 comments on commit 0fb291c

Please sign in to comment.