Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(tenancy): respect databaseNameTemplate in finding database matrix from deployment schedule (#383)
spinningbot368e7ebb69ae
diff --git a/api/label.go b/api/label.goindex 89c853cd56..7d5d86d100 100644--- a/api/label.go+++ b/api/label.go@@ -12,6 +12,11 @@ const (// DatabaseLabelSizeMax is the maximium size of database labels.DatabaseLabelSizeMax = 4labelLengthMax = 63++ // LocationLabelKey is the label key for location+ LocationLabelKey = "bb.location"+ // TenantLabelKey is the label key for tenant+ TenantLabelKey = "bb.tenant")// LabelKey is the available key for labels.diff --git a/api/project.go b/api/project.goindex 287039a323..9e33e821e7 100644--- a/api/project.go+++ b/api/project.go@@ -138,16 +138,22 @@ type ProjectPatch struct {}var (- dbNameToken = "{{DB_NAME}}"+ // DBNameToken is the token for database name.+ DBNameToken = "{{DB_NAME}}"+ // LocationToken is the token for location.+ LocationToken = "{{LOCATION}}"+ // TenantToken is the token for tenant.+ TenantToken = "{{TENANT}}"+repositoryFilePathTemplateTokens = map[string]bool{"{{VERSION}}": true,- dbNameToken: true,+ DBNameToken: true,"{{TYPE}}": true,}allowedProjectDBNameTemplateTokens = map[string]bool{- dbNameToken: true,- "{{LOCATION}}": true,- "{{TENANT}}": true,+ DBNameToken: true,+ LocationToken: true,+ TenantToken: true,})@@ -196,7 +202,7 @@ func ValidateProjectDBNameTemplate(template string) error {// Must contain {{DB_NAME}}hasDBName := falsefor _, token := range tokens {- if token == dbNameToken {+ if token == DBNameToken {hasDBName = true}if _, ok := allowedProjectDBNameTemplateTokens[token]; !ok {@@ -204,11 +210,23 @@ func ValidateProjectDBNameTemplate(template string) error {}}if !hasDBName {- return fmt.Errorf("project database name template must include token %v", dbNameToken)+ return fmt.Errorf("project database name template must include token %v", DBNameToken)}return nil}+// FormatTemplate formats the template.+func FormatTemplate(template string, tokens map[string]string) (string, error) {+ keys := getTemplateTokens(template)+ for _, key := range keys {+ if _, ok := tokens[key]; !ok {+ return "", fmt.Errorf("token %q not found", key)+ }+ template = strings.ReplaceAll(template, key, tokens[key])+ }+ return template, nil+}+func getTemplateTokens(template string) []string {r := regexp.MustCompile(`{{[^{}]+}}`)return r.FindAllString(template, -1)diff --git a/api/project_test.go b/api/project_test.goindex ddad2013f5..ff1d075af7 100644--- a/api/project_test.go+++ b/api/project_test.go@@ -149,3 +149,48 @@ func TestValidateProjectDBNameTemplate(t *testing.T) {}}}++func TestFormatTemplate(t *testing.T) {+ tests := []struct {+ name string+ template string+ tokens map[string]string+ want string+ errPart string+ }{+ {+ "valid",+ "{{DB_NAME}}_hello_{{LOCATION}}",+ map[string]string{+ "{{DB_NAME}}": "db1",+ "{{LOCATION}}": "us-central1",+ },+ "db1_hello_us-central1",+ "",+ }, {+ "tokenNotFound",+ "{{DB_NAME}}_hello_{{LOCATION}}",+ map[string]string{+ "{{DB_NAME}}": "db1",+ },+ "",+ "not found",+ },+ }++ for _, test := range tests {+ got, err := FormatTemplate(test.template, test.tokens)+ if err != nil {+ if !strings.Contains(err.Error(), test.errPart) {+ t.Errorf("%q: FormatTemplate(%q, %+v) got error %q, want errPart %q.", test.name, test.template, test.tokens, err.Error(), test.errPart)+ }+ } else {+ if test.errPart != "" {+ t.Errorf("%q: FormatTemplate(%q, %+v) got no error, want errPart %q.", test.name, test.template, test.tokens, test.errPart)+ }+ }+ if got != test.want {+ t.Errorf("%q: FormatTemplate(%q, %+v) got %q, want %q.", test.name, test.template, test.tokens, got, test.want)+ }+ }+}diff --git a/server/database.go b/server/database.goindex 2dba150dff..6643ef2afc 100644--- a/server/database.go+++ b/server/database.go@@ -175,7 +175,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {if toProject.TenantMode == api.TenantModeTenant {// For database being transferred to a tenant mode project, its schema version and schema has to match a peer tenant database.// When a peer tenant database doesn't exist, we will return an error if there are databases in the project with the same name.- peerSchemaVersion, peerSchema, err := s.getSchemaFromPeerTenantDatabase(ctx, database.Instance, *databasePatch.ProjectID, database.Name)+ peerSchemaVersion, peerSchema, err := s.getSchemaFromPeerTenantDatabase(ctx, database.Instance, toProject, *databasePatch.ProjectID, database.Name)if err != nil {return err}diff --git a/server/deploy.go b/server/deploy.goindex aafe7643cc..febb658df8 100644--- a/server/deploy.go+++ b/server/deploy.go@@ -45,7 +45,7 @@ func isMatchExpressions(labels map[string]string, expressionList []*api.LabelSel// getDatabaseMatrixFromDeploymentSchedule gets a pipeline based on deployment schedule.// The returned matrix doesn't include deployment with no matched database.-func getDatabaseMatrixFromDeploymentSchedule(schedule *api.DeploymentSchedule, name string, databaseList []*api.Database) ([]*api.Deployment, [][]*api.Database, error) {+func getDatabaseMatrixFromDeploymentSchedule(schedule *api.DeploymentSchedule, databaseName, dbNameTemplate string, databaseList []*api.Database) ([]*api.Deployment, [][]*api.Database, error) {var pipeline [][]*api.Databasevar deployments []*api.Deployment@@ -75,7 +75,12 @@ func getDatabaseMatrixFromDeploymentSchedule(schedule *api.DeploymentSchedule, nvar matchedDatabaseList []int// Loop over databaseList instead of idToLabels to get determinant results.for _, database := range databaseList {+ labels := idToLabels[database.ID]// The tenant database should match the database name.+ name, err := formatDatabaseName(databaseName, dbNameTemplate, labels)+ if err != nil {+ continue+ }if database.Name != name {continue}@@ -84,7 +89,6 @@ func getDatabaseMatrixFromDeploymentSchedule(schedule *api.DeploymentSchedule, ncontinue}- labels := idToLabels[database.ID]if isMatchExpressions(labels, deployment.Spec.Selector.MatchExpressions) {matchedDatabaseList = append(matchedDatabaseList, database.ID)idsSeen[database.ID] = true@@ -104,3 +108,20 @@ func getDatabaseMatrixFromDeploymentSchedule(schedule *api.DeploymentSchedule, nreturn deployments, pipeline, nil}++func formatDatabaseName(databaseName, dbNameTemplate string, labels map[string]string) (string, error) {+ if dbNameTemplate == "" {+ return databaseName, nil+ }+ tokens := make(map[string]string)+ tokens[api.DBNameToken] = databaseName+ for k, v := range labels {+ switch k {+ case api.LocationLabelKey:+ tokens[api.LocationToken] = v+ case api.TenantLabelKey:+ tokens[api.TenantToken] = v+ }+ }+ return api.FormatTemplate(dbNameTemplate, tokens)+}diff --git a/server/deploy_test.go b/server/deploy_test.goindex 4774eab09d..3304adef22 100644--- a/server/deploy_test.go+++ b/server/deploy_test.go@@ -34,14 +34,25 @@ func TestGetDatabaseMatrixFromDeploymentSchedule(t *testing.T) {Name: "world",Labels: "[{\"key\":\"bb.location\",\"value\":\"earth\"},{\"key\":\"bb.environment\",\"value\":\"Dev\"}]",},+ {+ ID: 5,+ Name: "db1_us",+ Labels: "[{\"key\":\"bb.location\",\"value\":\"us\"},{\"key\":\"bb.environment\",\"value\":\"Dev\"}]",+ },+ {+ ID: 6,+ Name: "db1_eu",+ Labels: "[{\"key\":\"bb.location\",\"value\":\"eu\"},{\"key\":\"bb.environment\",\"value\":\"Dev\"}]",+ },}tests := []struct {- name string- schedule *api.DeploymentSchedule- databaseName string- databaseList []*api.Database- want [][]*api.Database+ name string+ schedule *api.DeploymentSchedule+ databaseName string+ databaseNameTemplate string+ databaseList []*api.Database+ want [][]*api.Database// Notice relevant position is preserved from databaseList to want.// e.g. in simpleDeployments the result is [db[0], db[1]] instead of [db[1], db[0]] in the first stage.}{@@ -78,6 +89,7 @@ func TestGetDatabaseMatrixFromDeploymentSchedule(t *testing.T) {},},"hello",+ "",[]*api.Database{dbs[0], dbs[1],},@@ -119,6 +131,7 @@ func TestGetDatabaseMatrixFromDeploymentSchedule(t *testing.T) {},},"hello",+ "",[]*api.Database{dbs[0], dbs[1], dbs[2],},@@ -161,6 +174,7 @@ func TestGetDatabaseMatrixFromDeploymentSchedule(t *testing.T) {},},"hello",+ "",[]*api.Database{dbs[0], dbs[2], dbs[3],},@@ -189,6 +203,7 @@ func TestGetDatabaseMatrixFromDeploymentSchedule(t *testing.T) {},},"world",+ "",[]*api.Database{dbs[3], dbs[4],},@@ -196,10 +211,39 @@ func TestGetDatabaseMatrixFromDeploymentSchedule(t *testing.T) {{dbs[4]},},},+ {+ "useDatabaseNameTemplate",+ &api.DeploymentSchedule{+ Deployments: []*api.Deployment{++ {+ Spec: &api.DeploymentSpec{+ Selector: &api.LabelSelector{+ MatchExpressions: []*api.LabelSelectorRequirement{+ {+ Key: "bb.location",+ Operator: "In",+ Values: []string{"us", "eu"},+ },+ },+ },+ },+ },+ },+ },+ "db1",+ "{{DB_NAME}}_{{LOCATION}}",+ []*api.Database{+ dbs[5], dbs[6],+ },+ [][]*api.Database{+ {dbs[5], dbs[6]},+ },+ },}for _, test := range tests {- _, create, _ := getDatabaseMatrixFromDeploymentSchedule(test.schedule, test.databaseName, test.databaseList)+ _, create, _ := getDatabaseMatrixFromDeploymentSchedule(test.schedule, test.databaseName, test.databaseNameTemplate, test.databaseList)diff := pretty.Diff(create, test.want)if len(diff) > 0 {diff --git a/server/issue.go b/server/issue.goindex d318a4896a..3e1c420114 100644--- a/server/issue.go+++ b/server/issue.go@@ -646,7 +646,7 @@ func (s *Server) createPipelineFromIssue(ctx context.Context, issueCreate *api.I}// We will use schema from existing tenant databases for creating a database in a tenant mode project if possible.if project.TenantMode == api.TenantModeTenant {- sv, s, err := s.getSchemaFromPeerTenantDatabase(ctx, instance, issueCreate.ProjectID, m.DatabaseName)+ sv, s, err := s.getSchemaFromPeerTenantDatabase(ctx, instance, project, issueCreate.ProjectID, m.DatabaseName)if err != nil {return nil, err}@@ -767,7 +767,7 @@ func (s *Server) createPipelineFromIssue(ctx context.Context, issueCreate *api.Iif err != nil {return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch databases in project ID: %v", issueCreate.ProjectID)).SetInternal(err)}- deployments, p, err := s.getTenantDatabaseMatrix(ctx, issueCreate.ProjectID, databaseList, d.DatabaseName)+ deployments, p, err := s.getTenantDatabaseMatrix(ctx, issueCreate.ProjectID, project.DBNameTemplate, databaseList, d.DatabaseName)if err != nil {return nil, err}@@ -1050,7 +1050,7 @@ func (s *Server) postInboxIssueActivity(ctx context.Context, issue *api.Issue, areturn nil}-func (s *Server) getTenantDatabaseMatrix(ctx context.Context, projectID int, databaseList []*api.Database, databaseName string) ([]*api.Deployment, [][]*api.Database, error) {+func (s *Server) getTenantDatabaseMatrix(ctx context.Context, projectID int, dbNameTemplate string, databaseList []*api.Database, databaseName string) ([]*api.Deployment, [][]*api.Database, error) {deployConfig, err := s.DeploymentConfigService.FindDeploymentConfig(ctx, &api.DeploymentConfigFind{ProjectID: &projectID,})@@ -1069,7 +1069,7 @@ func (s *Server) getTenantDatabaseMatrix(ctx context.Context, projectID int, datreturn nil, nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to compose database relationship for database ID %v", database.ID)).SetInternal(err)}}- d, p, err := getDatabaseMatrixFromDeploymentSchedule(deploySchedule, databaseName, databaseList)+ d, p, err := getDatabaseMatrixFromDeploymentSchedule(deploySchedule, databaseName, dbNameTemplate, databaseList)if err != nil {return nil, nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to create deployment pipeline").SetInternal(err)}@@ -1080,7 +1080,7 @@ func (s *Server) getTenantDatabaseMatrix(ctx context.Context, projectID int, dat// It's used for creating a database in a tenant mode project.// When a peer tenant database doesn't exist, we will return an error if there are databases in the project with the same name.// Otherwise, we will create a blank database without schema.-func (s *Server) getSchemaFromPeerTenantDatabase(ctx context.Context, instance *api.Instance, projectID int, databaseName string) (string, string, error) {+func (s *Server) getSchemaFromPeerTenantDatabase(ctx context.Context, instance *api.Instance, project *api.Project, projectID int, databaseName string) (string, string, error) {// Find all databases in the project.databaseList, err := s.DatabaseService.FindDatabaseList(ctx, &api.DatabaseFind{ProjectID: &projectID,@@ -1089,7 +1089,7 @@ func (s *Server) getSchemaFromPeerTenantDatabase(ctx context.Context, instance *return "", "", echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch databases in project ID: %v", projectID)).SetInternal(err)}- _, pipeline, err := s.getTenantDatabaseMatrix(ctx, projectID, databaseList, databaseName)+ _, pipeline, err := s.getTenantDatabaseMatrix(ctx, projectID, project.DBNameTemplate, databaseList, databaseName)if err != nil {return "", "", err}