From a5caba14c33e85940899d00f8899788a03c6ee97 Mon Sep 17 00:00:00 2001 From: wcy00000000000000 <2269766985@qq.com> Date: Tue, 30 Jan 2024 14:41:46 +0800 Subject: [PATCH] feat: move migration logics to tool --- .../admin_server/service/migrate.go | 275 ------------ .../admin_server/service/service.go | 2 - .../{ => upgrader/imports}/imports.go | 2 +- .../{ => upgrader/imports}/imports_history.go | 2 +- src/tools/cmdb_ctl/cmd/migrate.go | 393 ++++++++++++++++++ src/tools/cmdb_ctl/readme.md | 87 ++++ 6 files changed, 482 insertions(+), 279 deletions(-) rename src/scene_server/admin_server/{ => upgrader/imports}/imports.go (99%) rename src/scene_server/admin_server/{ => upgrader/imports}/imports_history.go (99%) create mode 100644 src/tools/cmdb_ctl/cmd/migrate.go diff --git a/src/scene_server/admin_server/service/migrate.go b/src/scene_server/admin_server/service/migrate.go index e677100433c..7eb1639e042 100644 --- a/src/scene_server/admin_server/service/migrate.go +++ b/src/scene_server/admin_server/service/migrate.go @@ -17,275 +17,16 @@ import ( "fmt" "net/http" "path/filepath" - "time" "configcenter/src/common" "configcenter/src/common/blog" - "configcenter/src/common/mapstr" "configcenter/src/common/metadata" "configcenter/src/common/types" "configcenter/src/common/util" - "configcenter/src/common/version" - "configcenter/src/common/watch" - "configcenter/src/scene_server/admin_server/upgrader" - "configcenter/src/source_controller/cacheservice/event" - daltypes "configcenter/src/storage/dal/types" - streamtypes "configcenter/src/storage/stream/types" "github.com/emicklei/go-restful/v3" - "go.mongodb.org/mongo-driver/bson" ) -func (s *Service) migrate(req *restful.Request, resp *restful.Response) { - rHeader := req.Request.Header - rid := util.GetHTTPCCRequestID(rHeader) - defErr := s.CCErr.CreateDefaultCCErrorIf(util.GetLanguage(rHeader)) - ownerID := common.BKDefaultOwnerID - updateCfg := &upgrader.Config{ - OwnerID: ownerID, - User: common.CCSystemOperatorUserName, - } - - if err := s.createWatchDBChainCollections(rid); err != nil { - blog.Errorf("create watch db chain collections failed, err: %v, rid: %s", err, rid) - result := &metadata.RespError{ - Msg: defErr.Errorf(common.CCErrCommMigrateFailed, err.Error()), - } - resp.WriteError(http.StatusInternalServerError, result) - return - } - - preVersion, finishedVersions, err := upgrader.Upgrade(s.ctx, s.db, s.cache, s.iam, updateCfg) - if err != nil { - blog.Errorf("db upgrade failed, err: %+v, rid: %s", err, rid) - result := &metadata.RespError{ - Msg: defErr.Errorf(common.CCErrCommMigrateFailed, err.Error()), - } - resp.WriteError(http.StatusInternalServerError, result) - return - } - - currentVersion := preVersion - if len(finishedVersions) > 0 { - currentVersion = finishedVersions[len(finishedVersions)-1] - } - - result := MigrationResponse{ - BaseResp: metadata.BaseResp{ - Result: true, - Code: 0, - ErrMsg: "", - Permissions: nil, - }, - Data: "migrate success", - PreVersion: preVersion, - CurrentVersion: currentVersion, - FinishedVersions: finishedVersions, - } - resp.WriteEntity(result) -} - -// dbChainTTLTime the ttl time seconds of the db event chain, used to set the ttl index of mongodb -const dbChainTTLTime = 5 * 24 * 60 * 60 - -func (s *Service) createWatchDBChainCollections(rid string) error { - // create watch token table to store the last watch token info for every collections - exists, err := s.watchDB.HasTable(s.ctx, common.BKTableNameWatchToken) - if err != nil { - blog.Errorf("check if table %s exists failed, err: %v, rid: %s", common.BKTableNameWatchToken, err, rid) - return err - } - - if !exists { - err = s.watchDB.CreateTable(s.ctx, common.BKTableNameWatchToken) - if err != nil && !s.watchDB.IsDuplicatedError(err) { - blog.Errorf("create table %s failed, err: %v, rid: %s", common.BKTableNameWatchToken, err, rid) - return err - } - } - - // create watch chain node table and init the last token info as empty for all collections - cursorTypes := watch.ListCursorTypes() - for _, cursorType := range cursorTypes { - key, err := event.GetResourceKeyWithCursorType(cursorType) - if err != nil { - blog.Errorf("get resource key with cursor type %s failed, err: %v, rid: %s", cursorType, err, rid) - return err - } - - exists, err := s.watchDB.HasTable(s.ctx, key.ChainCollection()) - if err != nil { - blog.Errorf("check if table %s exists failed, err: %v, rid: %s", key.ChainCollection(), err, rid) - return err - } - - if !exists { - err = s.watchDB.CreateTable(s.ctx, key.ChainCollection()) - if err != nil && !s.watchDB.IsDuplicatedError(err) { - blog.Errorf("create table %s failed, err: %v, rid: %s", key.ChainCollection(), err, rid) - return err - } - } - - if err = s.createWatchIndexes(cursorType, key, rid); err != nil { - return err - } - - if err = s.createWatchToken(key); err != nil { - return err - } - } - return nil -} - -func (s *Service) createWatchIndexes(cursorType watch.CursorType, key event.Key, rid string) error { - indexes := []daltypes.Index{ - {Name: "index_id", Keys: bson.D{{common.BKFieldID, -1}}, Background: true, Unique: true}, - {Name: "index_cursor", Keys: bson.D{{common.BKCursorField, -1}}, Background: true, Unique: true}, - {Name: "index_cluster_time", Keys: bson.D{{common.BKClusterTimeField, -1}}, Background: true, - ExpireAfterSeconds: dbChainTTLTime}, - } - - if cursorType == watch.ObjectBase || cursorType == watch.MainlineInstance || cursorType == watch.InstAsst { - subResourceIndex := daltypes.Index{ - Name: "index_sub_resource", Keys: bson.D{{common.BKSubResourceField, 1}}, Background: true, - } - indexes = append(indexes, subResourceIndex) - } - - existIndexArr, err := s.watchDB.Table(key.ChainCollection()).Indexes(s.ctx) - if err != nil { - blog.Errorf("get exist indexes for table %s failed, err: %v, rid: %s", key.ChainCollection(), err, rid) - return err - } - - existIdxMap := make(map[string]bool) - for _, index := range existIndexArr { - existIdxMap[index.Name] = true - } - - for _, index := range indexes { - if _, exist := existIdxMap[index.Name]; exist { - continue - } - - err = s.watchDB.Table(key.ChainCollection()).CreateIndex(s.ctx, index) - if err != nil && !s.watchDB.IsDuplicatedError(err) { - blog.Errorf("create indexes for table %s failed, err: %v, rid: %s", key.ChainCollection(), err, rid) - return err - } - } - return nil -} - -func (s *Service) createWatchToken(key event.Key) error { - filter := map[string]interface{}{ - "_id": key.Collection(), - } - - count, err := s.watchDB.Table(common.BKTableNameWatchToken).Find(filter).Count(s.ctx) - if err != nil { - blog.Errorf("check if last watch token exists failed, err: %v, filter: %+v", err, filter) - return err - } - - if count > 0 { - return nil - } - - if key.Collection() == event.HostIdentityKey.Collection() { - // host identity's watch token is different with other identity. - // only set coll is ok, the other fields is useless - data := mapstr.MapStr{ - "_id": key.Collection(), - common.BKTableNameBaseHost: watch.LastChainNodeData{Coll: common.BKTableNameBaseHost}, - common.BKTableNameModuleHostConfig: watch.LastChainNodeData{Coll: common.BKTableNameModuleHostConfig}, - common.BKTableNameBaseProcess: watch.LastChainNodeData{Coll: common.BKTableNameBaseProcess}, - } - if err = s.watchDB.Table(common.BKTableNameWatchToken).Insert(s.ctx, data); err != nil { - blog.Errorf("init last watch token failed, err: %v, data: %+v", err, data) - return err - } - return nil - } - - if key.Collection() == event.BizSetRelationKey.Collection() { - // biz set relation's watch token is generated in the same way with the host identity's watch token - data := mapstr.MapStr{ - "_id": key.Collection(), - common.BKTableNameBaseApp: watch.LastChainNodeData{Coll: common.BKTableNameBaseApp}, - common.BKTableNameBaseBizSet: watch.LastChainNodeData{Coll: common.BKTableNameBaseBizSet}, - common.BKFieldID: 0, - common.BKTokenField: "", - } - if err = s.watchDB.Table(common.BKTableNameWatchToken).Insert(s.ctx, data); err != nil { - blog.Errorf("init last biz set relation watch token failed, err: %v, data: %+v", err, data) - return err - } - return nil - } - - data := watch.LastChainNodeData{ - Coll: key.Collection(), - Token: "", - StartAtTime: streamtypes.TimeStamp{ - Sec: uint32(time.Now().Unix()), - Nano: 0, - }, - } - if err = s.watchDB.Table(common.BKTableNameWatchToken).Insert(s.ctx, data); err != nil { - blog.Errorf("init last watch token failed, err: %v, data: %+v", err, data) - return err - } - return nil -} - -func (s *Service) migrateSpecifyVersion(req *restful.Request, resp *restful.Response) { - rHeader := req.Request.Header - rid := util.GetHTTPCCRequestID(rHeader) - defErr := s.CCErr.CreateDefaultCCErrorIf(util.GetLanguage(rHeader)) - ownerID := common.BKDefaultOwnerID - updateCfg := &upgrader.Config{ - OwnerID: ownerID, - User: common.CCSystemOperatorUserName, - } - - input := new(MigrateSpecifyVersionRequest) - if err := json.NewDecoder(req.Request.Body).Decode(input); err != nil { - blog.Errorf("migrateSpecifyVersion failed, decode body err: %v, body:%+v,rid:%s", err, req.Request.Body, rid) - _ = resp.WriteError(http.StatusOK, &metadata.RespError{Msg: defErr.Error(common.CCErrCommJSONUnmarshalFailed)}) - return - } - - if input.CommitID != version.CCGitHash { - _ = resp.WriteError(http.StatusOK, - &metadata.RespError{Msg: defErr.Errorf(common.CCErrCommParamsInvalid, "commit_id")}) - return - } - - err := upgrader.UpgradeSpecifyVersion(s.ctx, s.db, s.cache, s.iam, updateCfg, input.Version) - if err != nil { - blog.Errorf("db upgrade specify failed, err: %+v, rid: %s", err, rid) - result := &metadata.RespError{ - Msg: defErr.Errorf(common.CCErrCommMigrateFailed, err.Error()), - } - resp.WriteError(http.StatusInternalServerError, result) - return - } - - result := MigrationResponse{ - BaseResp: metadata.BaseResp{ - Result: true, - Code: 0, - ErrMsg: "", - Permissions: nil, - }, - Data: "migrate success. version: " + input.Version, - } - resp.WriteEntity(result) - -} - var allConfigNames = map[string]bool{ "redis": true, "mongodb": true, @@ -350,19 +91,3 @@ func (s *Service) refreshConfig(req *restful.Request, resp *restful.Response) { blog.Infof("refresh config success, input:%#v", input) resp.WriteEntity(metadata.NewSuccessResp("refresh config success")) } - -// MigrationResponse TODO -type MigrationResponse struct { - metadata.BaseResp `json:",inline"` - Data interface{} `json:"data"` - PreVersion string `json:"pre_version"` - CurrentVersion string `json:"current_version"` - FinishedVersions []string `json:"finished_migrations"` -} - -// MigrateSpecifyVersionRequest TODO -type MigrateSpecifyVersionRequest struct { - CommitID string `json:"commit_id"` - TimeStamp int64 `json:"time_stamp"` - Version string `json:"version"` -} diff --git a/src/scene_server/admin_server/service/service.go b/src/scene_server/admin_server/service/service.go index f39ccd74ce6..8fb335369b6 100644 --- a/src/scene_server/admin_server/service/service.go +++ b/src/scene_server/admin_server/service/service.go @@ -96,7 +96,6 @@ func (s *Service) WebService() *restful.Container { api.Route(api.POST("/authcenter/init").To(s.InitAuthCenter)) api.Route(api.POST("/authcenter/register").To(s.RegisterAuthAccount)) - api.Route(api.POST("/migrate/{distribution}/{ownerID}").To(s.migrate)) api.Route(api.POST("/migrate/system/hostcrossbiz/{ownerID}").To(s.SetSystemConfiguration)) api.Route(api.POST("/migrate/system/user_config/{key}/{can}").To(s.UserConfigSwitch)) api.Route(api.GET("/find/system/config_admin").To(s.SearchConfigAdmin)) @@ -105,7 +104,6 @@ func (s *Service) WebService() *restful.Container { api.Route(api.PUT("/update/system_config/platform_setting").To(s.UpdatePlatformSettingConfig)) api.Route(api.GET("/find/system_config/platform_setting/{type}").To(s.SearchPlatformSettingConfig)) - api.Route(api.POST("/migrate/specify/version/{distribution}/{ownerID}").To(s.migrateSpecifyVersion)) api.Route(api.POST("/migrate/config/refresh").To(s.refreshConfig)) api.Route(api.POST("/migrate/dataid").To(s.migrateDataID)) api.Route(api.POST("/migrate/old/dataid").To(s.migrateOldDataID)) diff --git a/src/scene_server/admin_server/imports.go b/src/scene_server/admin_server/upgrader/imports/imports.go similarity index 99% rename from src/scene_server/admin_server/imports.go rename to src/scene_server/admin_server/upgrader/imports/imports.go index 09ac6507f5e..29b48f59929 100644 --- a/src/scene_server/admin_server/imports.go +++ b/src/scene_server/admin_server/upgrader/imports/imports.go @@ -10,7 +10,7 @@ * limitations under the License. */ -package main +package imports import ( diff --git a/src/scene_server/admin_server/imports_history.go b/src/scene_server/admin_server/upgrader/imports/imports_history.go similarity index 99% rename from src/scene_server/admin_server/imports_history.go rename to src/scene_server/admin_server/upgrader/imports/imports_history.go index 76d87864474..3bfa1d1aad0 100644 --- a/src/scene_server/admin_server/imports_history.go +++ b/src/scene_server/admin_server/upgrader/imports/imports_history.go @@ -10,7 +10,7 @@ * limitations under the License. */ -package main +package imports import ( _ "configcenter/src/scene_server/admin_server/upgrader/history/v3.0.8" diff --git a/src/tools/cmdb_ctl/cmd/migrate.go b/src/tools/cmdb_ctl/cmd/migrate.go new file mode 100644 index 00000000000..a657733baa5 --- /dev/null +++ b/src/tools/cmdb_ctl/cmd/migrate.go @@ -0,0 +1,393 @@ +/* + * Tencent is pleased to support the open source community by making + * 蓝鲸智云 - 配置平台 (BlueKing - Configuration System) available. + * Copyright (C) 2017 THL A29 Limited, + * a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * We undertake not to change the open source license (MIT license) applicable + * to the current version of the project delivered to anyone in the future. + */ + +package cmd + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + "configcenter/src/ac/iam" + "configcenter/src/common" + "configcenter/src/common/auth" + cc "configcenter/src/common/backbone/configcenter" + "configcenter/src/common/mapstr" + "configcenter/src/common/metrics" + "configcenter/src/common/version" + "configcenter/src/common/watch" + "configcenter/src/scene_server/admin_server/upgrader" + // import upgrader + _ "configcenter/src/scene_server/admin_server/upgrader/imports" + "configcenter/src/source_controller/cacheservice/event" + "configcenter/src/storage/dal" + "configcenter/src/storage/dal/mongo/local" + "configcenter/src/storage/dal/redis" + daltypes "configcenter/src/storage/dal/types" + streamtypes "configcenter/src/storage/stream/types" + + "github.com/spf13/cobra" + "go.mongodb.org/mongo-driver/bson" +) + +func init() { + rootCmd.AddCommand(NewMigrateCommand()) +} + +// NewMigrateCommand new tool command for migration +func NewMigrateCommand() *cobra.Command { + var configPath string + + cmd := &cobra.Command{ + Use: "migrate", + Short: "migrate cmdb data", + RunE: func(cmd *cobra.Command, args []string) error { + return cmd.Help() + }, + } + cmd.PersistentFlags().StringVar(&configPath, "config-path", "", "migrate tool config file path") + cmd.PersistentFlags().Var(auth.EnableAuthFlag, "enable-auth", + "The auth center enable status, true for enabled, false for disabled") + + cmd.AddCommand(&cobra.Command{ + Use: "db", + Short: "migrate cmdb data in database", + RunE: func(cmd *cobra.Command, args []string) error { + srv, err := newMigrateService(configPath) + if err != nil { + return err + } + return srv.migrateDB() + }, + }) + + specifyVersionReq := new(MigrateSpecifyVersionRequest) + specifyVersionCmd := &cobra.Command{ + Use: "specify-version", + Short: "migrate cmdb data of specify version", + RunE: func(cmd *cobra.Command, args []string) error { + srv, err := newMigrateService(configPath) + if err != nil { + return err + } + return srv.migrateSpecifyVersion(specifyVersionReq) + }, + } + specifyVersionReq.addFlags(specifyVersionCmd) + + cmd.AddCommand(specifyVersionCmd) + + return cmd +} + +type migrateService struct { + db dal.DB + watchDB dal.DB + cache redis.Client + iam *iam.IAM +} + +func newMigrateService(configPath string) (*migrateService, error) { + if !strings.HasSuffix(configPath, ".yaml") { + return nil, fmt.Errorf("config path %s is invalid, should be a yaml file", configPath) + } + configPath = strings.TrimSuffix(configPath, ".yaml") + + if err := cc.SetMigrateFromFile(configPath); err != nil { + return nil, fmt.Errorf("parse migration config from file[%s] failed, err: %v", configPath, err) + } + + if err := cc.SetMongodbFromFile(configPath); err != nil { + return nil, fmt.Errorf("parse mongodb config from file[%s] failed, err: %v", configPath, err) + } + + if err := cc.SetRedisFromFile(configPath); err != nil { + return nil, fmt.Errorf("parse redis config from file[%s] failed, err: %v", configPath, err) + } + + svc := new(migrateService) + + // new mongodb client + dbConf, err := cc.Mongo("mongodb") + if err != nil { + return nil, fmt.Errorf("get mongodb config failed, err: %v", err) + } + + svc.db, err = local.NewMgo(dbConf.GetMongoConf(), time.Minute) + if err != nil { + return nil, fmt.Errorf("new mongodb client failed, err: %v", err) + } + + // new watch mongodb client + watchDBConf, err := cc.Mongo("watch") + if err != nil { + return nil, fmt.Errorf("get watch mongodb config failed, err: %v", err) + } + + svc.watchDB, err = local.NewMgo(watchDBConf.GetMongoConf(), time.Minute) + if err != nil { + return nil, fmt.Errorf("new watch mongodb client failed, err: %v", err) + } + + // new redis client + redisConf, err := cc.Redis("redis") + if err != nil { + return nil, fmt.Errorf("get redis config failed, err: %v", err) + } + + svc.cache, err = redis.NewFromConfig(redisConf) + if err != nil { + return nil, fmt.Errorf("new redis client failed, err: %v", err) + } + + // new iam client + if auth.EnableAuthorize() { + iamConf, err := iam.ParseConfigFromKV("iam", nil) + if err != nil && auth.EnableAuthorize() { + return nil, fmt.Errorf("parse iam config failed, err: %v", err) + } + + metricService := metrics.NewService(metrics.Config{ProcessName: "migrate_tool"}) + svc.iam, err = iam.NewIAM(iamConf, metricService.Registry()) + if err != nil { + return nil, fmt.Errorf("new iam client failed, err: %v", err) + } + } + + return svc, nil +} + +func (s *migrateService) migrateDB() error { + ctx := context.Background() + if err := s.createWatchDBChainCollections(ctx); err != nil { + return err + } + + updateCfg := &upgrader.Config{ + OwnerID: common.BKDefaultOwnerID, + User: common.CCSystemOperatorUserName, + } + + preVersion, finishedVersions, err := upgrader.Upgrade(ctx, s.db, s.cache, s.iam, updateCfg) + if err != nil { + return fmt.Errorf("db upgrade failed, err: %v", err) + } + + currentVersion := preVersion + if len(finishedVersions) > 0 { + currentVersion = finishedVersions[len(finishedVersions)-1] + } + + result := MigrationResult{ + Data: "migrate success", + PreVersion: preVersion, + CurrentVersion: currentVersion, + FinishedVersions: finishedVersions, + } + + res, err := json.Marshal(result) + if err != nil { + return err + } + + fmt.Printf("%s\n", string(res)) + return nil +} + +// MigrationResult is the migration result +type MigrationResult struct { + Data interface{} `json:"data"` + PreVersion string `json:"pre_version"` + CurrentVersion string `json:"current_version"` + FinishedVersions []string `json:"finished_migrations"` +} + +// dbChainTTLTime the ttl time seconds of the db event chain, used to set the ttl index of mongodb +const dbChainTTLTime = 5 * 24 * 60 * 60 + +func (s *migrateService) createWatchDBChainCollections(ctx context.Context) error { + // create watch token table to store the last watch token info for every collection + exists, err := s.watchDB.HasTable(ctx, common.BKTableNameWatchToken) + if err != nil { + return fmt.Errorf("check if table %s exists failed, err: %v", common.BKTableNameWatchToken, err) + } + + if !exists { + err = s.watchDB.CreateTable(ctx, common.BKTableNameWatchToken) + if err != nil && !s.watchDB.IsDuplicatedError(err) { + return fmt.Errorf("create table %s failed, err: %v", common.BKTableNameWatchToken, err) + } + } + + // create watch chain node table and init the last token info as empty for all collections + cursorTypes := watch.ListCursorTypes() + for _, cursorType := range cursorTypes { + key, err := event.GetResourceKeyWithCursorType(cursorType) + if err != nil { + return fmt.Errorf("get resource key with cursor type %s failed, err: %v", cursorType, err) + } + + exists, err := s.watchDB.HasTable(ctx, key.ChainCollection()) + if err != nil { + return fmt.Errorf("check if table %s exists failed, err: %v", key.ChainCollection(), err) + } + + if !exists { + err = s.watchDB.CreateTable(ctx, key.ChainCollection()) + if err != nil && !s.watchDB.IsDuplicatedError(err) { + return fmt.Errorf("create table %s failed, err: %v", key.ChainCollection(), err) + } + } + + if err = s.createWatchIndexes(ctx, cursorType, key); err != nil { + return err + } + + if err = s.createWatchToken(ctx, key); err != nil { + return err + } + } + return nil +} + +func (s *migrateService) createWatchIndexes(ctx context.Context, cursorType watch.CursorType, key event.Key) error { + indexes := []daltypes.Index{ + {Name: "index_id", Keys: bson.D{{common.BKFieldID, -1}}, Background: true, Unique: true}, + {Name: "index_cursor", Keys: bson.D{{common.BKCursorField, -1}}, Background: true, Unique: true}, + {Name: "index_cluster_time", Keys: bson.D{{common.BKClusterTimeField, -1}}, Background: true, + ExpireAfterSeconds: dbChainTTLTime}, + } + + if cursorType == watch.ObjectBase || cursorType == watch.MainlineInstance || cursorType == watch.InstAsst { + subResourceIndex := daltypes.Index{ + Name: "index_sub_resource", Keys: bson.D{{common.BKSubResourceField, 1}}, Background: true, + } + indexes = append(indexes, subResourceIndex) + } + + existIndexArr, err := s.watchDB.Table(key.ChainCollection()).Indexes(ctx) + if err != nil { + return fmt.Errorf("get exist indexes for table %s failed, err: %v", key.ChainCollection(), err) + } + + existIdxMap := make(map[string]bool) + for _, index := range existIndexArr { + existIdxMap[index.Name] = true + } + + for _, index := range indexes { + if _, exist := existIdxMap[index.Name]; exist { + continue + } + + err = s.watchDB.Table(key.ChainCollection()).CreateIndex(ctx, index) + if err != nil && !s.watchDB.IsDuplicatedError(err) { + return fmt.Errorf("create indexes for table %s failed, err: %v", key.ChainCollection(), err) + } + } + return nil +} + +func (s *migrateService) createWatchToken(ctx context.Context, key event.Key) error { + filter := map[string]interface{}{ + "_id": key.Collection(), + } + + count, err := s.watchDB.Table(common.BKTableNameWatchToken).Find(filter).Count(ctx) + if err != nil { + return fmt.Errorf("check if last watch token exists failed, err: %v, filter: %+v", err, filter) + } + + if count > 0 { + return nil + } + + if key.Collection() == event.HostIdentityKey.Collection() { + // host identity's watch token is different with other identity. + // only set coll is ok, the other fields is useless + data := mapstr.MapStr{ + "_id": key.Collection(), + common.BKTableNameBaseHost: watch.LastChainNodeData{Coll: common.BKTableNameBaseHost}, + common.BKTableNameModuleHostConfig: watch.LastChainNodeData{Coll: common.BKTableNameModuleHostConfig}, + common.BKTableNameBaseProcess: watch.LastChainNodeData{Coll: common.BKTableNameBaseProcess}, + } + if err = s.watchDB.Table(common.BKTableNameWatchToken).Insert(ctx, data); err != nil { + return fmt.Errorf("init last watch token failed, err: %v, data: %+v", err, data) + } + return nil + } + + if key.Collection() == event.BizSetRelationKey.Collection() { + // biz set relation's watch token is generated in the same way with the host identity's watch token + data := mapstr.MapStr{ + "_id": key.Collection(), + common.BKTableNameBaseApp: watch.LastChainNodeData{Coll: common.BKTableNameBaseApp}, + common.BKTableNameBaseBizSet: watch.LastChainNodeData{Coll: common.BKTableNameBaseBizSet}, + common.BKFieldID: 0, + common.BKTokenField: "", + } + if err = s.watchDB.Table(common.BKTableNameWatchToken).Insert(ctx, data); err != nil { + return fmt.Errorf("init last biz set relation watch token failed, err: %v, data: %+v", err, data) + } + return nil + } + + data := watch.LastChainNodeData{ + Coll: key.Collection(), + Token: "", + StartAtTime: streamtypes.TimeStamp{ + Sec: uint32(time.Now().Unix()), + Nano: 0, + }, + } + if err = s.watchDB.Table(common.BKTableNameWatchToken).Insert(ctx, data); err != nil { + return fmt.Errorf("init last watch token failed, err: %v, data: %+v", err, data) + } + return nil +} + +func (s *migrateService) migrateSpecifyVersion(input *MigrateSpecifyVersionRequest) error { + updateCfg := &upgrader.Config{ + OwnerID: common.BKDefaultOwnerID, + User: common.CCSystemOperatorUserName, + } + + if input.CommitID != version.CCGitHash { + return fmt.Errorf("commit id %s is not the same with current version %s", input.CommitID, version.CCGitHash) + } + + err := upgrader.UpgradeSpecifyVersion(context.Background(), s.db, s.cache, s.iam, updateCfg, input.Version) + if err != nil { + return fmt.Errorf("db upgrade specify failed, err: %v", err) + } + + fmt.Printf("migrate success, version: %s\n", input.Version) + return nil +} + +// MigrateSpecifyVersionRequest migrate specify version request +type MigrateSpecifyVersionRequest struct { + CommitID string `json:"commit_id"` + Version string `json:"version"` +} + +func (m *MigrateSpecifyVersionRequest) addFlags(cmd *cobra.Command) { + cmd.Flags().StringVar(&m.CommitID, "commit-id", "", "the commit id of this tool") + cmd.Flags().StringVar(&m.Version, "version", "", "version to migrate") +} diff --git a/src/tools/cmdb_ctl/readme.md b/src/tools/cmdb_ctl/readme.md index dcf54207f89..04cc19b4327 100644 --- a/src/tools/cmdb_ctl/readme.md +++ b/src/tools/cmdb_ctl/readme.md @@ -416,3 +416,90 @@ denyall配置为false的情况下,limit和ttl配置才能生效 } ] ``` + +### CMDB数据迁移 + +- 使用方式 + ``` + ./tool_ctl migrate [flag] [command] + ``` +- 子命令 + ``` + db migrate cmdb data in database + specify-version migrate cmdb data of specify version + ``` +- 命令行参数 + ``` + --config-path string migrate tool config file path + --enable-auth The auth center enable status, true for enabled, false for disabled (default true) + --commit-id string the commit id of this tool(仅用于specify-version命令) + --version string version to migrate(仅用于specify-version命令) + ``` +- 配置文件示例 + ``` + # mongodb配置 + mongodb: + host: 127.0.0.1 + port: 27017 + usr: + pwd: + database: cmdb + maxOpenConns: 50 + maxIdleConns: 50 + mechanism: SCRAM-SHA-1 + rsName: rs0 + socketTimeoutSeconds: 10 + # mongodb事件监听存储事件链的mongodb配置 + watch: + host: 127.0.0.1 + port: 27017 + usr: + pwd: + database: cmdb_events + maxOpenConns: 10 + maxIdleConns: 5 + mechanism: SCRAM-SHA-1 + rsName: rs0 + socketTimeoutSeconds: 10 + # redis配置 + redis: + host: 127.0.0.1:6379 + pwd: + sentinelPwd: + database: "0" + maxOpenConns: 10 + maxIDleConns: 10 + # iam配置 + iam: + # 蓝鲸权限中心地址,可配置多个,用,(逗号)分割 + address: 127.0.0.1 + # cmdb项目在蓝鲸权限中心的应用编码 + appCode: bk_cmdb + #cmdb项目在蓝鲸权限中心的应用密钥 + appSecret: + authCenter: + # 权限中心tls配置 + tls: + # 客户端是否验证服务端证书,包含证书链和主机名,bool值, true为不校验, false为校验 + insecureSkipVerify: + # 服务使用的证书的路径,如:/data/cmdb/cert/server.crt + certFile: + # 服务使用的证书对应的密钥的路径,如:/data/cmdb/cert/server.key + keyFile: + # CA证书路径,用于验证对方证书,如:/data/cmdb/cert/ca.crt + caFile: + # 用于解密根据RFC1423加密的证书密钥的PEM块 + password: + ``` +- 示例 + ``` + 迁移DB数据操作示例: + ./tool_ctl migrate db --config-path=migrate.yaml --enable-auth=false + 回显样式: + {"data":"migrate success","pre_version":"y3.12.202311061800","current_version":"y3.12.202311061800","finished_migrations":[]} + + 迁移指定版本的DB数据操作示例: + ./tool_ctl migrate specify-version --config-path=migrate.yaml --enable-auth=false --commit-id=759fa78e118faa92fc488fc90e5fffaa6617bd6d --version=y3.12.202311061800 + 回显样式: + migrate success, version: y3.12.202311061800 + ```