diff --git a/dbm-services/mongo/db-tools/dbactuator/pkg/atomjobs/atommongodb/add_user.go b/dbm-services/mongo/db-tools/dbactuator/pkg/atomjobs/atommongodb/add_user.go index 0d46ab7c95..e91209f29d 100644 --- a/dbm-services/mongo/db-tools/dbactuator/pkg/atomjobs/atommongodb/add_user.go +++ b/dbm-services/mongo/db-tools/dbactuator/pkg/atomjobs/atommongodb/add_user.go @@ -18,17 +18,18 @@ import ( // AddUserConfParams 参数 type AddUserConfParams struct { - IP string `json:"ip" validate:"required"` - Port int `json:"port" validate:"required"` - InstanceType string `json:"instanceType" validate:"required"` - Username string `json:"username" validate:"required"` - Password string `json:"password" validate:"required"` - AdminUsername string `json:"adminUsername"` - AdminPassword string `json:"adminPassword"` - AuthDb string `json:"authDb"` // 为方便管理用户,验证库默认为admin库 - Dbs []string `json:"dbs"` // 业务库 - Privileges []string `json:"privileges"` // 权限 - + IP string `json:"ip" validate:"required"` + Port int `json:"port" validate:"required"` + InstanceType string `json:"instanceType" validate:"required"` + Username string `json:"username" validate:"required"` + Password string `json:"password" validate:"required"` + AdminUsername string `json:"adminUsername"` + AdminPassword string `json:"adminPassword"` + AuthDb string `json:"authDb"` // 为方便管理用户,验证库默认为admin库 + DbsPrivileges []struct { + Db string `json:"db"` + Privileges []string `json:"privileges"` + } `json:"dbsPrivileges"` // 业务库 以及权限 [{"db":xxx,"privileges":[xxx,xxx]}] } // AddUser 添加分片到集群 @@ -151,16 +152,11 @@ func (u *AddUser) makeScriptContent() error { u.ConfParams.AuthDb = "admin" } - // 判断业务db是否存在 - if len(u.ConfParams.Dbs) == 0 { - u.ConfParams.Dbs = []string{"admin"} - } - - for _, db := range u.ConfParams.Dbs { - for _, privilege := range u.ConfParams.Privileges { + for _, dbPrivileges := range u.ConfParams.DbsPrivileges { + for _, privilege := range dbPrivileges.Privileges { role := common.NewMongoRole() role.Role = privilege - role.Db = db + role.Db = dbPrivileges.Db user.Roles = append(user.Roles, role) } } diff --git a/dbm-services/mongo/db-tools/mongo-toolkit-go/target/bs-cli_Darwin b/dbm-services/mongo/db-tools/mongo-toolkit-go/target/bs-cli_Darwin deleted file mode 100755 index f8c567707e..0000000000 Binary files a/dbm-services/mongo/db-tools/mongo-toolkit-go/target/bs-cli_Darwin and /dev/null differ diff --git a/dbm-ui/backend/flow/consts.py b/dbm-ui/backend/flow/consts.py index a5f01888a1..7979ed5da0 100644 --- a/dbm-ui/backend/flow/consts.py +++ b/dbm-ui/backend/flow/consts.py @@ -253,27 +253,6 @@ class MediumEnum(str, StructuredEnum): TBinlogDumper = EnumField("tbinlogdumper", _("tbinlogdumper实例")) Sqlserver = EnumField("sqlserver", _("sqlserver实例")) MongoDB = EnumField("mongodb", _("mongodb")) - MongoD = EnumField("mongod", _("mongod")) - MongoS = EnumField("mongos", _("mongos")) - MongoShardSvr = EnumField("shardsvr", _("shardsvr")) - MongoConfigSvr = EnumField("configsvr", _("configsvr")) - AuthDB = EnumField("admin", _("admin")) - DbaUser = EnumField("dba", _("dba")) - AppDbaUser = EnumField("appdba", _("appdba")) - MonitorUser = EnumField("monitor", _("monitor")) - AppMonitorUser = EnumField("appmonitor", _("appmonitor")) - RootRole = EnumField("root", _("root")) - BackupRole = EnumField("backup", _("backup")) - ClusterMonitorRole = EnumField("clusterMonitor", _("clusterMonitor")) - ReadAnyDatabaseRole = EnumField("readAnyDatabase", _("readAnyDatabase")) - HostManagerRole = EnumField("hostManager", _("hostManager")) - ReadWriteRole = EnumField("readWrite", _("readWrite")) - UserAdminAnyDatabaseRole = EnumField("userAdminAnyDatabase", _("userAdminAnyDatabase")) - DbAdminAnyDatabaseRole = EnumField("dbAdminAnyDatabase", _("dbAdminAnyDatabase")) - ReadWriteAnyDatabaseRole = EnumField("readWriteAnyDatabase", _("readWriteAnyDatabase")) - ClusterAdminRole = EnumField("clusterAdmin", _("clusterAdmin")) - MongoDBInitSet = EnumField("mongodb_init_set", _("mongodb_init_set")) - MongoDBExtraUserCreate = EnumField("mongodb_extra_user_create", _("mongodb_extra_user_create")) class CloudServiceName(str, StructuredEnum): @@ -1266,3 +1245,56 @@ class SqlserverLoginExecMode(str, StructuredEnum): ENABLE = EnumField("enable", _("启动")) DISABLE = EnumField("disable", _("关闭")) DROP = EnumField("drop", _("删除")) + + +class MongoDBManagerUser(str, StructuredEnum): + """mongodb 管理用户""" + + DbaUser = EnumField("dba", _("dba")) + AppDbaUser = EnumField("appdba", _("appdba")) + MonitorUser = EnumField("monitor", _("monitor")) + AppMonitorUser = EnumField("appmonitor", _("appmonitor")) + + +class MongoDBUserPrivileges(str, StructuredEnum): + """mongodb 用户权限""" + + RootRole = EnumField("root", _("root")) + BackupRole = EnumField("backup", _("backup")) + ClusterMonitorRole = EnumField("clusterMonitor", _("clusterMonitor")) + ReadAnyDatabaseRole = EnumField("readAnyDatabase", _("readAnyDatabase")) + HostManagerRole = EnumField("hostManager", _("hostManager")) + ReadWriteRole = EnumField("readWrite", _("readWrite")) + UserAdminAnyDatabaseRole = EnumField("userAdminAnyDatabase", _("userAdminAnyDatabase")) + DbAdminAnyDatabaseRole = EnumField("dbAdminAnyDatabase", _("dbAdminAnyDatabase")) + ReadWriteAnyDatabaseRole = EnumField("readWriteAnyDatabase", _("readWriteAnyDatabase")) + ClusterAdminRole = EnumField("clusterAdmin", _("clusterAdmin")) + MongoDBInitSet = EnumField("mongodb_init_set", _("mongodb_init_set")) + MongoDBExtraUserCreate = EnumField("mongodb_extra_user_create", _("mongodb_extra_user_create")) + + +class MongoDBTask(str, StructuredEnum): + """mongodb 任务""" + + MongoDBInitSet = EnumField("mongodb_init_set", _("mongodb_init_set")) + MongoDBExtraUserCreate = EnumField("mongodb_extra_user_create", _("mongodb_extra_user_create")) + + +class MongoDBInstanceType(str, StructuredEnum): + """mongodb 实例类型""" + + MongoD = EnumField("mongod", _("mongod")) + MongoS = EnumField("mongos", _("mongos")) + + +class MongoDBDfaultAuthDB(str, StructuredEnum): + """mongodb 默认验证db""" + + AuthDB = EnumField("admin", _("admin")) + + +class MongoDBShardType(str, StructuredEnum): + """mongodb shard类型""" + + MongoShardSvr = EnumField("shardsvr", _("shardsvr")) + MongoConfigSvr = EnumField("configsvr", _("configsvr")) diff --git a/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/mongodb_install.py b/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/mongodb_install.py index d17845f711..8378165226 100644 --- a/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/mongodb_install.py +++ b/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/mongodb_install.py @@ -47,7 +47,7 @@ def __init__(self, root_id: str, data: Optional[Dict]): self.data = payload_clusters self.get_kwargs = ActKwargs() self.get_kwargs.payload = payload_clusters - self.get_kwargs.get_inti_info() + self.get_kwargs.get_init_info() self.get_kwargs.get_file_path() def prepare_job(self, pipeline: Builder): diff --git a/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/mongodb_user.py b/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/mongodb_user.py index 16733e26ab..f49f52ae76 100644 --- a/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/mongodb_user.py +++ b/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/mongodb_user.py @@ -32,9 +32,8 @@ def __init__(self, root_id: str, data: Optional[Dict]): self.data = data self.get_kwargs = ActKwargs() self.get_kwargs.payload = data - self.get_kwargs.get_file_path() - def multi_cluster_create_user_flow(self, create: bool): + def multi_cluster_user_flow(self, create: bool): """ multi replicaset create/delete user流程 create True:创建 @@ -45,16 +44,19 @@ def multi_cluster_create_user_flow(self, create: bool): pipeline = Builder(root_id=self.root_id, data=self.data) # 创建/删除用户子流程并行 - sub_pipelines = [] - for cluster_id in self.data["cluster_ids"]: - sub_pipline = user( - root_id=self.root_id, - ticket_data=self.data, - sub_kwargs=self.get_kwargs, - cluster_id=cluster_id, - create=create, - ) - sub_pipelines.append(sub_pipline) - pipeline.add_parallel_sub_pipeline(sub_flow_list=sub_pipelines) + for info in self.data["infos"]: + sub_pipelines = [] + for cluster_id in info["cluster_ids"]: + sub_pipline = user( + root_id=self.root_id, + ticket_data=self.data, + sub_kwargs=self.get_kwargs, + cluster_id=cluster_id, + create=create, + info=info, + ) + sub_pipelines.append(sub_pipline) + pipeline.add_parallel_sub_pipeline(sub_flow_list=sub_pipelines) + # 运行流程 pipeline.run_pipeline() diff --git a/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/sub_task/replicaset_install.py b/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/sub_task/replicaset_install.py index a5e3e0e9d0..4806e72fcc 100644 --- a/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/sub_task/replicaset_install.py +++ b/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/sub_task/replicaset_install.py @@ -14,7 +14,7 @@ from django.utils.translation import ugettext as _ -from backend.flow.consts import MediumEnum +from backend.flow.consts import MongoDBManagerUser, MongoDBTask from backend.flow.engine.bamboo.scene.common.builder import SubBuilder from backend.flow.plugins.components.collections.mongodb.add_domain_to_dns import ExecAddDomainToDnsOperationComponent from backend.flow.plugins.components.collections.mongodb.add_password_to_db import ( @@ -79,14 +79,19 @@ def replicaset_install( ) # 创建appdba,monitor,monitor用户 - kwargs = sub_get_kwargs.get_init_exec_script_kwargs(script_type=MediumEnum.MongoDBExtraUserCreate) + kwargs = sub_get_kwargs.get_init_exec_script_kwargs(script_type=MongoDBTask.MongoDBExtraUserCreate) sub_pipeline.add_act( act_name=_("MongoDB--创建额外管理用户"), act_component_code=ExecuteDBActuatorJobComponent.code, kwargs=kwargs ) # dba, appdba,monitor,monitor用户密码写入密码服务 kwargs = sub_get_kwargs.get_add_password_to_db_kwargs( - usernames=[MediumEnum.DbaUser, MediumEnum.AppDbaUser, MediumEnum.MonitorUser, MediumEnum.AppMonitorUser], + usernames=[ + MongoDBManagerUser.DbaUser.value, + MongoDBManagerUser.AppDbaUser.value, + MongoDBManagerUser.MonitorUser.value, + MongoDBManagerUser.AppMonitorUser.value, + ], info=sub_get_kwargs.replicaset_info, ) sub_pipeline.add_act( @@ -98,7 +103,7 @@ def replicaset_install( # 进行初始配置 # 创建oplog重放权限的role,把role授权给dba,appdba 把admin库的gcs_heartbeat授予给monitor用户 # 3.x版本修改验证方式 - kwargs = sub_get_kwargs.get_init_exec_script_kwargs(script_type=MediumEnum.MongoDBInitSet) + kwargs = sub_get_kwargs.get_init_exec_script_kwargs(script_type=MongoDBTask.MongoDBInitSet) sub_pipeline.add_act( act_name=_("MongoDB-{}-db初始设置".format(sub_get_kwargs.replicaset_info["nodes"][0]["ip"])), act_component_code=ExecuteDBActuatorJobComponent.code, diff --git a/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/sub_task/user.py b/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/sub_task/user.py index 57757078a0..5407fc4048 100644 --- a/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/sub_task/user.py +++ b/dbm-ui/backend/flow/engine/bamboo/scene/mongodb/sub_task/user.py @@ -14,7 +14,7 @@ from django.utils.translation import ugettext as _ -from backend.flow.consts import MediumEnum +from backend.flow.consts import MongoDBManagerUser from backend.flow.engine.bamboo.scene.common.builder import SubBuilder from backend.flow.plugins.components.collections.mongodb.exec_actuator_job import ExecuteDBActuatorJobComponent from backend.flow.plugins.components.collections.mongodb.send_media import ExecSendMediaOperationComponent @@ -22,7 +22,7 @@ def user( - root_id: str, ticket_data: Optional[Dict], sub_kwargs: ActKwargs, cluster_id: int, create: bool + root_id: str, ticket_data: Optional[Dict], sub_kwargs: ActKwargs, cluster_id: int, create: bool, info: dict ) -> SubBuilder: """ 单个cluster 创建/删除用户流程 @@ -35,7 +35,7 @@ def user( sub_pipeline = SubBuilder(root_id=root_id, data=ticket_data) # 获取信息 - sub_get_kwargs.get_cluster_info_user(cluster_id=cluster_id, admin_user=MediumEnum.DbaUser) + sub_get_kwargs.get_cluster_info_user(cluster_id=cluster_id, admin_user=MongoDBManagerUser.DbaUser.value) # 介质下发 kwargs = sub_get_kwargs.get_send_media_kwargs() @@ -43,15 +43,16 @@ def user( act_name=_("MongoDB-介质下发"), act_component_code=ExecSendMediaOperationComponent.code, kwargs=kwargs ) - # 创建用户 - kwargs = sub_get_kwargs.get_user_kwargs(create=create, admin_user=MediumEnum.DbaUser) + # 创建或删除用户 + print("info:", info) + kwargs = sub_get_kwargs.get_user_kwargs(create=create, admin_user=MongoDBManagerUser.DbaUser.value, info=info) if create: - act_name = _("MongoDB-cluster_id:{}-创建用户".format(str(cluster_id))) + act_name = _("MongoDB-cluster_id:{}-创建用户:{}".format(str(cluster_id), info["username"])) sub_name = _( "MongoDB--创建用户--cluster_id:{}-{}".format(str(cluster_id), sub_get_kwargs.payload["hosts"][0]["ip"]) ) else: - act_name = _("MongoDB-cluster_id:{}-删除用户".format(str(cluster_id))) + act_name = _("MongoDB-cluster_id:{}-删除用户:{}".format(str(cluster_id), info["username"])) sub_name = _( "MongoDB--删除用户--cluster_id:{}-{}".format(str(cluster_id), sub_get_kwargs.payload["hosts"][0]["ip"]) ) diff --git a/dbm-ui/backend/flow/engine/controller/mongodb.py b/dbm-ui/backend/flow/engine/controller/mongodb.py index 585c42601b..41ee8e6a67 100644 --- a/dbm-ui/backend/flow/engine/controller/mongodb.py +++ b/dbm-ui/backend/flow/engine/controller/mongodb.py @@ -11,6 +11,7 @@ from backend.flow.engine.bamboo.scene.mongodb.mongodb_backup import MongoBackupFlow from backend.flow.engine.bamboo.scene.mongodb.mongodb_fake_install import MongoFakeInstallFlow from backend.flow.engine.bamboo.scene.mongodb.mongodb_install import MongoDBInstallFlow +from backend.flow.engine.bamboo.scene.mongodb.mongodb_user import MongoUserFlow from backend.flow.engine.controller.base import BaseController @@ -48,3 +49,19 @@ def fake_install(self): """ flow = MongoFakeInstallFlow(root_id=self.root_id, data=self.ticket_data) flow.start() + + def create_user(self): + """ + 创建用户 + """ + + flow = MongoUserFlow(root_id=self.root_id, data=self.ticket_data) + flow.multi_cluster_user_flow(True) + + def delete_user(self): + """ + 删除用户 + """ + + flow = MongoUserFlow(root_id=self.root_id, data=self.ticket_data) + flow.multi_cluster_user_flow(False) diff --git a/dbm-ui/backend/flow/urls.py b/dbm-ui/backend/flow/urls.py index d97f908bd2..0b0ccfb67e 100644 --- a/dbm-ui/backend/flow/urls.py +++ b/dbm-ui/backend/flow/urls.py @@ -66,6 +66,8 @@ from backend.flow.views.mongodb_scene import ( ClusterInstallApiView, MongoBackupApiView, + MongoDBCreateUserView, + MongoDBDeleteUserView, MongoFakeInstallApiView, MultiReplicasetInstallApiView, ) @@ -272,6 +274,8 @@ url(r"^scene/cluster_create$", ClusterInstallApiView.as_view()), url(r"^scene/mongo_backup$", MongoBackupApiView.as_view()), url(r"^scene/install_rs_fake$", MongoFakeInstallApiView.as_view()), + url(r"^scene/multi_cluster_create_user$", MongoDBCreateUserView.as_view()), + url(r"^scene/multi_cluster_delete_user$", MongoDBDeleteUserView.as_view()), # mongodb end url(r"^scene/install_mysql_apply$", InstallMySQLSingleSceneApiView.as_view()), url(r"^scene/install_mysql_ha_apply$", InstallMySQLHASceneApiView.as_view()), diff --git a/dbm-ui/backend/flow/utils/mongodb/calculate_cluster.py b/dbm-ui/backend/flow/utils/mongodb/calculate_cluster.py index 807069f113..f709d18017 100644 --- a/dbm-ui/backend/flow/utils/mongodb/calculate_cluster.py +++ b/dbm-ui/backend/flow/utils/mongodb/calculate_cluster.py @@ -60,12 +60,12 @@ def replicase_calc(payload: dict, payload_clusters: dict, app: str, domain_prefi / node_replica_count / 1024 ) - if payload["infos"][0]["mongo_machine_set"][0]["storage"].get("/data1"): + if payload["infos"][0]["mongo_machine_set"][0]["storage_device"].get("/data1"): data_disk = "/data1" - elif payload["infos"][0]["mongo_machine_set"][0]["storage"].get("/data"): + elif payload["infos"][0]["mongo_machine_set"][0]["storage_device"].get("/data"): data_disk = "/data" oplog_size_mb = int( - payload["infos"][0]["mongo_machine_set"][0]["storage"].get(data_disk)["size"] + payload["infos"][0]["mongo_machine_set"][0]["storage_device"].get(data_disk)["size"] * 1024 * oplog_percent / node_replica_count @@ -127,20 +127,24 @@ def cluster_calc(payload: dict, payload_clusters: dict, app: str) -> dict: payload["nodes"]["mongo_config"][0]["bk_mem"] * MongoDBTotalCache.Cache_Percent / node_replica_count / 1024 ) # shard oplogSizeMB - if payload["nodes"]["mongodb"][0][0]["storage"].get("/data1"): + data_disk = "/data1" + if payload["nodes"]["mongodb"][0][0]["storage_device"].get("/data1"): data_disk = "/data1" - elif payload["nodes"]["mongodb"][0][0]["storage"].get("/data"): + elif payload["nodes"]["mongodb"][0][0]["storage_device"].get("/data"): data_disk = "/data" shard_oplog_size_mb = int( - payload["nodes"]["mongodb"][0][0]["storage"].get(data_disk)["size"] * 1024 * oplog_percent / node_replica_count + payload["nodes"]["mongodb"][0][0]["storage_device"].get(data_disk)["size"] + * 1024 + * oplog_percent + / node_replica_count ) # config oplogSizeMB - if payload["nodes"]["mongo_config"][0]["storage"].get("/data1"): + if payload["nodes"]["mongo_config"][0]["storage_device"].get("/data1"): data_disk = "/data1" - elif payload["nodes"]["mongo_config"][0]["storage"].get("/data"): + elif payload["nodes"]["mongo_config"][0]["storage_device"].get("/data"): data_disk = "/data" config_oplog_size_mb = int( - payload["nodes"]["mongo_config"][0]["storage"].get(data_disk)["size"] * 1024 * oplog_percent + payload["nodes"]["mongo_config"][0]["storage_device"].get(data_disk)["size"] * 1024 * oplog_percent ) # 获取全部主机 diff --git a/dbm-ui/backend/flow/utils/mongodb/mongodb_dataclass.py b/dbm-ui/backend/flow/utils/mongodb/mongodb_dataclass.py index 650942800b..5dc34f7701 100644 --- a/dbm-ui/backend/flow/utils/mongodb/mongodb_dataclass.py +++ b/dbm-ui/backend/flow/utils/mongodb/mongodb_dataclass.py @@ -22,7 +22,16 @@ from backend.db_meta.models import Cluster from backend.db_meta.models.machine import Machine from backend.db_package.models import Package -from backend.flow.consts import ConfigTypeEnum, MediumEnum, MongoDBActuatorActionEnum +from backend.flow.consts import ( + ConfigTypeEnum, + MediumEnum, + MongoDBActuatorActionEnum, + MongoDBDfaultAuthDB, + MongoDBInstanceType, + MongoDBManagerUser, + MongoDBTask, + MongoDBUserPrivileges, +) from backend.flow.engine.bamboo.scene.common.get_file_list import GetFileList from backend.flow.utils.mongodb import mongodb_password, mongodb_script_template from backend.flow.utils.mongodb.mongodb_password import MongoDBPassword @@ -49,10 +58,10 @@ def __init__(self): self.file_path: str = None # 管理员用户 self.manager_users: list = [ - MediumEnum.DbaUser.value, - MediumEnum.AppDbaUser.value, - MediumEnum.MonitorUser.value, - MediumEnum.AppMonitorUser.value, + MongoDBManagerUser.DbaUser.value, + MongoDBManagerUser.AppDbaUser.value, + MongoDBManagerUser.MonitorUser.value, + MongoDBManagerUser.AppMonitorUser.value, ] def __get_define_config(self, namespace: str, conf_file: str, conf_type: str) -> Any: @@ -71,7 +80,7 @@ def __get_define_config(self, namespace: str, conf_file: str, conf_type: str) -> ) return data["content"] - def get_inti_info(self): + def get_init_info(self): """获取初始信息一些信息""" # 集群类型 @@ -89,7 +98,7 @@ def get_file_path(self): )["file_path"] def get_backup_dir(self): - """安装文件存放路径""" + """备份文件存放路径""" resp = self.__get_define_config( namespace=self.cluster_type, @@ -182,7 +191,7 @@ def get_install_mongod_kwargs(self, node: dict, cluster_role: str) -> dict: "ip": node["ip"], "port": self.replicaset_info["port"], "dbVersion": self.payload["db_version"], - "instanceType": MediumEnum.MongoD, + "instanceType": MongoDBInstanceType.MongoD, "app": self.payload["app"], "setId": self.replicaset_info["set_id"], "keyFile": self.payload["key_file"], @@ -225,7 +234,7 @@ def get_install_mongos_kwargs(self, node: dict) -> dict: "ip": node["ip"], "port": self.mongos_info["port"], "dbVersion": self.payload["db_version"], - "instanceType": MediumEnum.MongoS, + "instanceType": MongoDBInstanceType.MongoS, "app": self.payload["app"], "setId": self.mongos_info["set_id"], "keyFile": self.payload["key_file"], @@ -422,7 +431,7 @@ def get_add_shard_to_cluster_kwargs(self) -> dict: "payload": { "ip": self.payload["mongos"]["nodes"][0]["ip"], "port": self.payload["mongos"]["port"], - "adminUsername": MediumEnum.DbaUser, + "adminUsername": MongoDBManagerUser.DbaUser, "shards": self.payload["add_shards"], }, }, @@ -440,11 +449,11 @@ def get_init_exec_script_kwargs(self, script_type: str) -> dict: mongo_type = "cluster" set_name = "" - if script_type == MediumEnum.MongoDBExtraUserCreate: + if script_type == MongoDBTask.MongoDBExtraUserCreate: create_extra_manager_user_status = True db_init_set_status = False script = mongodb_script_template.mongo_extra_manager_user_create_js_script - elif script_type == MediumEnum.MongoDBInitSet: + elif script_type == MongoDBTask.MongoDBInitSet: create_extra_manager_user_status = False db_init_set_status = True script = mongodb_script_template.mongo_init_set_js_script @@ -466,7 +475,7 @@ def get_init_exec_script_kwargs(self, script_type: str) -> dict: "script": script, "type": mongo_type, "secondary": False, - "adminUsername": MediumEnum.DbaUser, + "adminUsername": MongoDBManagerUser.DbaUser, "adminPassword": "", "repoUrl": "", "repoUsername": "", @@ -498,14 +507,14 @@ def get_add_manager_user_kwargs(self) -> dict: "payload": { "ip": self.replicaset_info["nodes"][0]["ip"], "port": self.replicaset_info["port"], - "instanceType": MediumEnum.MongoD, - "username": MediumEnum.DbaUser, + "instanceType": MongoDBInstanceType.MongoD, + "username": MongoDBManagerUser.DbaUser, "password": "", "adminUsername": "", "adminPassword": "", - "authDb": MediumEnum.AuthDB, + "authDb": MongoDBDfaultAuthDB.AuthDB, "dbs": [], - "privileges": [MediumEnum.RootRole], + "privileges": [MongoDBUserPrivileges.RootRole], }, }, } @@ -538,32 +547,37 @@ def get_cluster_info_user(self, cluster_id: int, admin_user: str): # 获取集群信息 cluster_info = MongoRepository().fetch_one_cluster(id=cluster_id) bk_cloud_id = cluster_info.bk_cloud_id + self.cluster_type = cluster_info.cluster_type exec_ip: str = None port: int = None instance_type: str = None if cluster_info.cluster_type == ClusterType.MongoReplicaSet.value: exec_ip = cluster_info.get_shards()[0].members[0].ip port = int(cluster_info.get_shards()[0].members[0].port) - instance_type = MediumEnum.MongoD + instance_type = MongoDBInstanceType.MongoD elif cluster_info.cluster_type == ClusterType.MongoShardedCluster.value: exec_ip = cluster_info.get_mongos()[0].ip port = int(cluster_info.get_mongos()[0].port) - instance_type = MediumEnum.MongoS + instance_type = MongoDBInstanceType.MongoS # 获取用户密码 result = MongoDBPassword().get_password_from_db( ip=exec_ip, port=port, bk_cloud_id=bk_cloud_id, username=admin_user ) - if result["info"] != "": - raise ValueError("get password of dba fail, error:{}".format(result["info"])) + if result["info"] is not None: + raise ValueError("get password of {} fail, error:{}".format(admin_user, result["info"])) self.payload["db_version"] = cluster_info.major_version - self.payload["hosts"] = [{"ip": exec_ip}] + self.payload["hosts"] = [{"ip": exec_ip, "bk_cloud_id": bk_cloud_id}] self.payload["bk_cloud_id"] = bk_cloud_id self.payload["port"] = port self.payload["instance_type"] = instance_type self.payload["admin_password"] = result["password"] + # db大版本 + self.db_main_version = str(self.payload["db_version"].split(".")[0]) + # 获取file_path + self.get_file_path() - def get_user_kwargs(self, create: bool, admin_user: str) -> dict: + def get_user_kwargs(self, create: bool, admin_user: str, info: dict) -> dict: """用户""" if create: @@ -580,13 +594,12 @@ def get_user_kwargs(self, create: bool, admin_user: str) -> dict: "ip": self.payload["hosts"][0]["ip"], "port": self.payload["port"], "instanceType": self.payload["instance_type"], - "username": self.payload["username"], - "password": self.payload["password"], + "username": info["username"], + "password": info["password"], "adminUsername": admin_user, "adminPassword": self.payload["admin_password"], - "authDb": self.payload["authDb"], - "dbs": self.payload["dbs"], - "privileges": self.payload["privileges"], + "authDb": info["auth_db"], + "dbsPrivileges": info["rule_sets"], }, }, } @@ -604,10 +617,10 @@ def get_user_kwargs(self, create: bool, admin_user: str) -> dict: "ip": self.payload["hosts"][0]["ip"], "port": self.payload["port"], "instanceType": self.payload["instance_type"], - "username": self.payload["username"], + "username": info["username"], "adminUsername": admin_user, "adminPassword": self.payload["admin_password"], - "authDb": self.payload["authDb"], + "authDb": info["auth_db"], }, }, } @@ -774,12 +787,7 @@ def get_delete_pwd_kwargs(self): instances.append({"ip": node["ip"], "port": node["port"], "bk_cloud_id": node["bk_cloud_id"]}) return { "instances": self.payload["bk_cloud_id"], - "usernames": [ - MediumEnum.DbaUser, - MediumEnum.AppDbaUser, - MediumEnum.MonitorUser, - MediumEnum.AppMonitorUser, - ], + "usernames": self.manager_users, } def get_cluster_by_ip_replace(self): @@ -986,6 +994,7 @@ def fetch_many_cluster(cls, **kwargs): row.cluster_type = i.cluster_type row.major_version = i.major_version row.bk_biz_id = i.bk_biz_id + row.bk_cloud_id = i.bk_cloud_id row.immute_domain = i.immute_domain row.mongos = [] row.shards = [] diff --git a/dbm-ui/backend/flow/views/mongodb_scene.py b/dbm-ui/backend/flow/views/mongodb_scene.py index b1ecd6f435..d18f922564 100644 --- a/dbm-ui/backend/flow/views/mongodb_scene.py +++ b/dbm-ui/backend/flow/views/mongodb_scene.py @@ -73,3 +73,23 @@ def post(request): # request.data 输入Json MongoDBController(root_id=root_id, ticket_data=request.data).fake_install() return Response({"root_id": root_id}) + + +class MongoDBCreateUserView(FlowTestView): + """mongodb创建用户""" + + @staticmethod + def post(request): + root_id = uuid.uuid1().hex + MongoDBController(root_id=root_id, ticket_data=request.data).create_user() + return Response({"root_id": root_id}) + + +class MongoDBDeleteUserView(FlowTestView): + """mongodb删除用户""" + + @staticmethod + def post(request): + root_id = uuid.uuid1().hex + MongoDBController(root_id=root_id, ticket_data=request.data).delete_user() + return Response({"root_id": root_id})