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 1f347eb
Show file tree
Hide file tree
Showing 36 changed files with 1,417 additions and 2,907 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/
123 changes: 123 additions & 0 deletions deployments/sentryflow-updated.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# Todo: Revise
apiVersion: v1
kind: Namespace
metadata:
name: sentryflow
labels:
istio-injection: disabled # avoid Istio sidecar-injection
---
apiVersion: v1
kind: ServiceAccount
metadata:
namespace: sentryflow
name: sentryflow-sa
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: sentryflow-cr
rules:
- apiGroups: [ "*" ]
verbs: [ "*" ]
resources: [ "*" ]
- apiGroups: [ "networking.istio.io" ]
verbs: [ "*" ]
resources: [ "*" ]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: sentryflow-rb
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: sentryflow-cr
subjects:
- kind: ServiceAccount
namespace: sentryflow
name: sentryflow-sa
---
apiVersion: v1
kind: ConfigMap
metadata:
name: config
namespace: sentryflow
data:
config.yaml: |2-
receivers:
port: 8081
serviceMeshes:
- name: istio-sidecar
enable: true
others:
- name: "optional"
# Either gRPC or HTTP not both
grpc:
url: localhost
port: 1234
http:
url: localhost
port: 4321
exporter:
grpc:
port: 8080
debug:
enable: false
pprof:
port: 6060
---
apiVersion: apps/v1
kind: Deployment
metadata:
namespace: sentryflow
name: sentryflow
spec:
replicas: 1
selector:
matchLabels:
app: sentryflow
template:
metadata:
labels:
app: sentryflow
spec:
serviceAccountName: sentryflow-sa
containers:
- 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: grpc
protocol: TCP
volumes:
- name: config
configMap:
name: config
---
apiVersion: v1
kind: Service
metadata:
namespace: sentryflow
name: sentryflow
spec:
selector:
app: sentryflow
ports:
- name: filter
targetPort: 8081
port: 8081
protocol: TCP
- name: grpc
targetPort: 8080
port: 8080
protocol: TCP
1 change: 1 addition & 0 deletions sentryflow/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
bin/
36 changes: 9 additions & 27 deletions sentryflow/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,36 +1,18 @@
# SPDX-License-Identifier: Apache-2.0
# Todo: Revise

### Builder

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
FROM golang:1.23 AS builder

RUN mkdir /sentryflow
RUN mkdir /protobuf

WORKDIR /protobuf
COPY /protobuf .

WORKDIR /sentryflow
COPY /sentryflow .

RUN export CGO_ENABLED=1; export CC=gcc;
RUN go build -o sentryflow

### Make executable image
COPY protobuf /protobuf
COPY sentryflow /sentryflow

FROM alpine:3.17 as sentryflow
RUN make -C /sentryflow 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 /
FROM redhat/ubi9-minimal
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
@go mod tidy; 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", true, "run in development mode")
initLogger(development)
}

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()
}

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

func run() {
logBuildInfo()
ctx := context.WithValue(ctrl.SetupSignalHandler(), util.LoggerCtxKey, logger)
core.Run(ctx, configFilePath, kubeConfig)
}
20 changes: 20 additions & 0 deletions sentryflow/cmd/version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package cmd

import (
"runtime"
"runtime/debug"
)

func logBuildInfo() {
info, _ := debug.ReadBuildInfo()
vcsRev := ""
vcsTime := ""
for _, s := range info.Settings {
if s.Key == "vcs.revision" {
vcsRev = s.Value
} else if s.Key == "vcs.time" {
vcsTime = s.Value
}
}
logger.Infof("Git commit: %s, build time: %s, build version: %s, go os/arch: %s/%s\n", vcsRev, vcsTime, info.Main.Version, runtime.GOOS, runtime.GOARCH)
}
Loading

0 comments on commit 1f347eb

Please sign in to comment.