Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: sql service deployment (#2099)
ecmadao05911087885e
diff --git a/.github/workflows/build-push-release-image.yml b/.github/workflows/build-push-release-image.ymlindex e8c4e59148..136e7909b5 100644--- a/.github/workflows/build-push-release-image.yml+++ b/.github/workflows/build-push-release-image.yml@@ -54,3 +54,17 @@ jobs:BUILD_USER=${{ env.BUILD_USER }}- name: Image digestrun: echo "Successfully pushed bytebase/bb:${{ env.RELEASE_VERSION }} ${{ steps.bb_build.outputs.digest }}"+ - name: Build and push SQL service+ id: sql_build+ uses: docker/build-push-action@v2+ with:+ file: Dockerfile.sql-service+ push: true+ tags: bytebase/sql:${{ env.RELEASE_VERSION }}+ build-args: |+ VERSION=${{ env.RELEASE_VERSION }}+ GIT_COMMIT=${{ env.GIT_COMMIT }}+ BUILD_TIME=${{ env.BUILD_TIME }}+ BUILD_USER=${{ env.BUILD_USER }}+ - name: Image digest+ run: echo "Successfully pushed bytebase/sql:${{ env.RELEASE_VERSION }} ${{ steps.sql_build.outputs.digest }}"diff --git a/Dockerfile.sql-service b/Dockerfile.sql-servicenew file mode 100644index 0000000000..12e08fa9d6--- /dev/null+++ b/Dockerfile.sql-service@@ -0,0 +1,62 @@+# DO NOT run docker build against this file directly. Instead using ./build_docker.sh as that+# one sets the various ARG used in the Dockerfile++# After build++# $ docker run --init --rm --name sql-service --publish 8081:8081 bytebase/sql++FROM golang:1.18.4 as sql++ARG VERSION="development"+ARG GO_VERSION="1.18.4"+ARG GIT_COMMIT="unknown"+ARG BUILD_TIME="unknown"+ARG BUILD_USER="unknown"++ARG RELEASE="release"++# Need gcc for CGO_ENABLED=1+RUN apt-get install -y gcc++WORKDIR /sql-service-build++COPY . .++COPY ./scripts/VERSION .++# -ldflags="-w -s" means omit DWARF symbol table and the symbol table and debug information+# go-sqlite3 requires CGO_ENABLED+RUN VERSION=`cat ./VERSION` && CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build \+ --tags "${RELEASE}" \+ -ldflags="-w -s -X 'github.com/bytebase/bytebase/bin/sql-service/cmd.version=${VERSION}' -X 'github.com/bytebase/bytebase/bin/sql-service/cmd.goversion=${GO_VERSION}' -X 'github.com/bytebase/bytebase/bin/sql-service/cmd.gitcommit=${GIT_COMMIT}' -X 'github.com/bytebase/bytebase/bin/sql-service/cmd.buildtime=${BUILD_TIME}' -X 'github.com/bytebase/bytebase/bin/sql-service/cmd.builduser=${BUILD_USER}'" \+ -o sql-service \+ ./bin/sql-service/main.go++# Use debian because mysql requires glibc.+FROM debian:bullseye-slim as monolithic++ARG VERSION="development"+ARG GIT_COMMIT="unknown"+ARG BUILD_TIME="unknown"+ARG BUILD_USER="unknown"++# See https://github.com/opencontainers/image-spec/blob/master/annotations.md+LABEL org.opencontainers.image.version=${VERSION}+LABEL org.opencontainers.image.revision=${GIT_COMMIT}+LABEL org.opencontainers.image.created=${BUILD_TIME}+LABEL org.opencontainers.image.authors=${BUILD_USER}++# Our HEALTHCHECK instruction in dockerfile needs curl.+RUN apt-get update && apt-get install -y curl++COPY --from=sql /sql-service-build/sql-service /usr/local/bin/+COPY --from=sql /etc/ssl/certs /etc/ssl/certs++# Copy utility scripts+COPY ./scripts /usr/local/bin/++CMD ["--host", "http://localhost", "--port", "80"]++HEALTHCHECK --interval=5m --timeout=60s CMD curl -f http://localhost:80/healthz || exit 1++ENTRYPOINT ["sql-service"]diff --git a/bin/sql-service/cmd/profile_dev.go b/bin/sql-service/cmd/profile_dev.goindex ce1d94c123..817fbcf382 100644--- a/bin/sql-service/cmd/profile_dev.go+++ b/bin/sql-service/cmd/profile_dev.go@@ -17,5 +17,6 @@ func activeProfile() server.Profile {Version: version,GitCommit: gitcommit,MetricConnectionKey: "",+ WorkspaceID: flags.workspaceID,}}diff --git a/bin/sql-service/cmd/profile_release.go b/bin/sql-service/cmd/profile_release.goindex 183c6d3dae..dc38c30b31 100644--- a/bin/sql-service/cmd/profile_release.go+++ b/bin/sql-service/cmd/profile_release.go@@ -16,6 +16,7 @@ func activeProfile() server.Profile {Debug: flags.debug,Version: version,GitCommit: gitcommit,- MetricConnectionKey: "",+ MetricConnectionKey: "46nEgegY1APWBz4NcQp0rCRJomDnLJyE",+ WorkspaceID: flags.workspaceID,}}diff --git a/bin/sql-service/cmd/root.go b/bin/sql-service/cmd/root.goindex e4ee070ac1..a181fc73ad 100644--- a/bin/sql-service/cmd/root.go+++ b/bin/sql-service/cmd/root.go@@ -61,9 +61,10 @@ ________________________________________________________________________________var (flags struct {// Used for Bytebase command line config- host string- port int- debug bool+ host string+ port int+ debug bool+ workspaceID string}rootCmd = &cobra.Command{Use: "sql",@@ -85,6 +86,7 @@ func init() {rootCmd.PersistentFlags().StringVar(&flags.host, "host", "http://localhost", "host where Bytebase SQL service backend is accessed from, must start with http:// or https://.")rootCmd.PersistentFlags().IntVar(&flags.port, "port", 80, "port where Bytebase SQL service backend is accessed from.")rootCmd.PersistentFlags().BoolVar(&flags.debug, "debug", false, "whether to enable debug level logging")+ rootCmd.PersistentFlags().StringVar(&flags.workspaceID, "workspace-id", "", "the identifier for SQL service")}// -----------------------------------Command Line Config END--------------------------------------diff --git a/scripts/build_docker_sql_service.sh b/scripts/build_docker_sql_service.shnew file mode 100644index 0000000000..f51b99e37f--- /dev/null+++ b/scripts/build_docker_sql_service.sh@@ -0,0 +1,32 @@+#!/bin/sh+# ===========================================================================+# File: build_sql_service.sh+# Description: usage: ./build_sql_service.sh+# ===========================================================================++# exit when any command fails+set -e++cd "$(dirname "$0")/../"+. ./scripts/init.sh++echo "Start building SQL Service docker image ${VERSION}..."++docker build -f ./Dockerfile.sql-service\+ --build-arg VERSION=${VERSION} \+ --build-arg GO_VERSION="$(go version)" \+ --build-arg GIT_COMMIT="$(git rev-parse HEAD)"\+ --build-arg BUILD_TIME="$(date -u +"%Y-%m-%dT%H:%M:%SZ")" \+ --build-arg BUILD_USER="$(id -u -n)" \+ -t bytebase/sql .++echo "${GREEN}Completed building Bytebase SQL Service docker image ${VERSION}.${NC}"+echo ""+echo "Command to tag and push the image"+echo ""+echo "$ docker tag bytebase/sql bytebase/sql:${VERSION}; docker push bytebase/sql:${VERSION}"+echo ""+echo "Command to start Bytebase SQL Service on http://localhost:8081"+echo ""+echo "$ docker run --init --name sql-service --restart always --publish 8081:8081 --volume ~/.sql-service/data:/var/opt/sql-service bytebase/sql:${VERSION} --host http://localhost --port 8081"+echo ""diff --git a/scripts/sql_service.sh b/scripts/sql_service.shnew file mode 100644index 0000000000..71b24bf884--- /dev/null+++ b/scripts/sql_service.sh@@ -0,0 +1,39 @@+#!/bin/bash++# For now, we use this script to start our SQL service on render+# by changing the ENTRYPOINT and CMD at the dockerfile to this.++# example usages:+# ./sql_service.sh+# ./sql_service.sh --host https://example.com+# ./sql_service.sh --host https://example.com --port 8080 --workspace-id bytebase-sql-service++ONLINE_HOST='http://localhost'+ONLINE_PORT='80'+WORKSPACE_ID=''++# Get parameters+for i in "$@"+do+case $i in+ --host)+ ONLINE_HOST="$2"+ shift+ ;;+ --port)+ ONLINE_PORT="$2"+ shift+ ;;+ --workspace-id)+ WORKSPACE_ID="$2"+ shift # past argument+ ;;+ *) # unknown option+ ;;+esac+done++echo "Starting Bytebase SQL Service at ${ONLINE_HOST}:${ONLINE_PORT} with workspace ${WORKSPACE_ID}..."++# Start the SQL service with workspace id+sql-service --host ${ONLINE_HOST} --port ${ONLINE_PORT} --workspace-id ${WORKSPACE_ID}diff --git a/sql-server/advise.go b/sql-server/advise.goindex 89e52ae579..7f71c2109d 100644--- a/sql-server/advise.go+++ b/sql-server/advise.go@@ -7,9 +7,12 @@ import ("io""net/http"+ metricAPI "github.com/bytebase/bytebase/metric"+"github.com/bytebase/bytebase/plugin/advisor""github.com/bytebase/bytebase/plugin/advisor/catalog"advisorDB "github.com/bytebase/bytebase/plugin/advisor/db"+ "github.com/bytebase/bytebase/plugin/metric""github.com/labstack/echo/v4""gopkg.in/yaml.v3")@@ -52,7 +55,7 @@ func (s *Server) registerAdvisorRoutes(g *echo.Group) {// @Failure 400 {object} echo.HTTPError// @Failure 500 {object} echo.HTTPError// @Router /sql/advise [get].-func (*Server) sqlCheckController(c echo.Context) error {+func (s *Server) sqlCheckController(c echo.Context) error {request := &sqlCheckRequestBody{}body, err := io.ReadAll(c.Request().Body)if err != nil {@@ -104,6 +107,17 @@ func (*Server) sqlCheckController(c echo.Context) error {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to run sql check").SetInternal(err)}+ s.metricReporter.Report(&metric.Metric{+ Name: metricAPI.SQLAdviseAPIMetricName,+ Value: 1,+ Labels: map[string]string{+ "database_type": string(advisorDBType),+ "platform": c.Request().Header.Get("X-Platform"),+ "repository": c.Request().Header.Get("X-Repository"),+ "actor": c.Request().Header.Get("X-Actor"),+ },+ })+return c.JSON(http.StatusOK, adviceList)}diff --git a/sql-server/metric.go b/sql-server/metric.gonew file mode 100644index 0000000000..b53d30ff64--- /dev/null+++ b/sql-server/metric.go@@ -0,0 +1,60 @@+package sqlserver++import (+ "strconv"+ "time"++ "github.com/bytebase/bytebase/common/log"+ metricAPI "github.com/bytebase/bytebase/metric"+ "github.com/bytebase/bytebase/plugin/metric"+ "github.com/labstack/echo/v4"+ "go.uber.org/zap"+)++type metricReporter struct {+ workspaceID string+ reporter metric.Reporter+}++func (m *metricReporter) Report(metric *metric.Metric) {+ if m.workspaceID == "" {+ return+ }++ if err := m.reporter.Report(metric); err != nil {+ log.Error(+ "Failed to report metric",+ zap.String("metric", string(metricAPI.OpenAPIMetricName)),+ zap.Error(err),+ )+ }+}++func metricMiddleware(s *Server, next echo.HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) (err error) {+ start := time.Now()++ defer func() {+ duration := time.Since(start)+ requestMethod := c.Request().Method+ requestPath := c.Path()+ responseCode := c.Response().Status++ s.metricReporter.Report(&metric.Metric{+ Name: metricAPI.OpenAPIMetricName,+ Value: 1,+ Labels: map[string]string{+ "latency_ns": strconv.FormatInt(duration.Nanoseconds(), 10),+ "request_method": requestMethod,+ "request_path": requestPath,+ "response_code": strconv.Itoa(responseCode),+ },+ })+ }()++ if err := next(c); err != nil {+ c.Error(err)+ }+ return nil+ }+}diff --git a/sql-server/profile.go b/sql-server/profile.goindex bc072ca346..4e9c8f9e30 100644--- a/sql-server/profile.go+++ b/sql-server/profile.go@@ -18,4 +18,6 @@ type Profile struct {GitCommit string// MetricConnectionKey is the connection key for metric.MetricConnectionKey string+ // WorkspaceID is the identifier for SQL Service, used by metric.+ WorkspaceID string}diff --git a/sql-server/server.go b/sql-server/server.goindex e81258461e..d53ec479e8 100644--- a/sql-server/server.go+++ b/sql-server/server.go@@ -7,6 +7,7 @@ import ("time"_ "github.com/bytebase/bytebase/docs/sqlservice" // initial the swagger doc+ "github.com/bytebase/bytebase/plugin/metric/segment"echoSwagger "github.com/swaggo/echo-swagger""github.com/bytebase/bytebase/common"@@ -19,9 +20,10 @@ import (// Server is the Bytebase server.type Server struct {- profile Profile- e *echo.Echo- startedTs int64+ profile Profile+ e *echo.Echo+ startedTs int64+ metricReporter *metricReporter}// Use following cmd to generate swagger doc@@ -48,6 +50,10 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {s := &Server{profile: prof,startedTs: time.Now().Unix(),+ metricReporter: &metricReporter{+ workspaceID: prof.WorkspaceID,+ reporter: segment.NewReporter(prof.MetricConnectionKey, prof.WorkspaceID),+ },}// Display config@@ -55,6 +61,7 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {fmt.Printf("mode=%s\n", prof.Mode)fmt.Printf("server=%s:%d\n", prof.BackendHost, prof.BackendPort)fmt.Printf("debug=%t\n", prof.Debug)+ fmt.Printf("workspaceID=%s\n", prof.WorkspaceID)fmt.Println("-----Config END-------")serverStarted := false@@ -87,6 +94,9 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {e.GET("/swagger/*", echoSwagger.WrapHandler)apiGroup := e.Group("/v1")+ apiGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {+ return metricMiddleware(s, next)+ })s.registerAdvisorRoutes(apiGroup)// Register healthz endpoint.