Skip to content

Commit

Permalink
feat(mongodb): mongodb安装,卸载,添加用户,删除用户,执行脚本flow #2321
Browse files Browse the repository at this point in the history
  • Loading branch information
yyhenryyy authored and iSecloud committed Jan 10, 2024
1 parent 5b2b6cf commit 32d66de
Show file tree
Hide file tree
Showing 39 changed files with 3,999 additions and 0 deletions.
93 changes: 93 additions & 0 deletions dbm-ui/backend/flow/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ class NameSpaceEnum(str, StructuredEnum):
Influxdb = EnumField("influxdb", _("Influxdb"))
TenDBCluster = EnumField("tendbcluster", _("tendbcluster"))
Riak = EnumField("riak", _("Riak"))
MongoDB = EnumField("mongodb", _("mongodb"))


class ConfigTypeEnum(str, StructuredEnum):
Expand All @@ -184,6 +185,8 @@ class ConfigTypeEnum(str, StructuredEnum):
HdfsSite = EnumField("hdfs-site", _("HDFS实例hdfs-site配置"))
CoreSite = EnumField("core-site", _("HDFS实例core-site配置"))
HdfsInstall = EnumField("install", _("HDFS实例安装配置"))
MongoD = EnumField("mongod", _("mongod配置"))
MongoS = EnumField("mongos", _("mongos配置"))


class ConfigFileEnum(str, StructuredEnum):
Expand All @@ -198,6 +201,8 @@ class ConfigFileEnum(str, StructuredEnum):
Base = EnumField("base", _("基本配置"))
HotKey = EnumField("hotkey", _("热key配置"))
BigKey = EnumField("bigkey", _("大key配置"))
DefaultConf = EnumField("defaultconf", _("默认配置"))
OsConf = EnumField("osconf", _("os配置"))


class DbBackupRoleEnum(str, StructuredEnum):
Expand Down Expand Up @@ -240,6 +245,28 @@ class MediumEnum(str, StructuredEnum):
RiakMonitor = EnumField("riak-monitor", _("riak-monitor"))
RedisDts = EnumField("redis-dts", _("redis-dts"))
TBinlogDumper = EnumField("tbinlogdumper", _("tbinlogdumper实例"))
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):
Expand Down Expand Up @@ -401,6 +428,20 @@ class RedisActuatorActionEnum(str, StructuredEnum):
REUPLOAD_OLD_BACKUP_RECORDS = EnumField("reupload_old_backup_records", _("reupload_old_backup_records"))


class MongoDBActuatorActionEnum(str, StructuredEnum):
OsInit = EnumField("os_mongo_init", _("os_mongo_init"))
mongoDInstall = EnumField("mongod_install", _("mongod_install"))
mongoSInstall = EnumField("mongos_install", _("mongos_install"))
InitReplicaset = EnumField("init_replicaset", _("init_replicaset"))
AddUser = EnumField("add_user", _("add_user"))
DeleteUser = EnumField("delete_user", _("delete_user"))
MongoExecuteScript = EnumField("mongo_execute_script", _("mongo_execute_script"))
Backup = EnumField("mongodb_backup", _("mongodb_backup"))
RemoveNs = EnumField("mongodb_remove_ns", _("mongodb_remove_ns"))
Restore = EnumField("mongodb_restore", _("mongodb_restore"))
PitRestore = EnumField("mongodb_pit_restore", _("mongodb_pit_restore"))


class EsActuatorActionEnum(str, StructuredEnum):
Init = EnumField("init", _("init"))
DecompressPkg = EnumField("decompress_pkg", _("decompress_pkg"))
Expand Down Expand Up @@ -946,6 +987,58 @@ class MySQLPrivComponent(str, StructuredEnum):
PULSAR_FAKE_USER = EnumField("pulsar_user", _("pulsar_user"))


class RequestResultCode(int, StructuredEnum):
"""
请求结果code状态
"""

Success = EnumField(0, _("success"))


class MongoDBPasswordRule(str, StructuredEnum):
"""
mongodb密码规则
"""

RULE = EnumField("password", _("密码规则"))


class MongoDBClusterRole(str, StructuredEnum):
"""
mongodb cluster role
"""

ConfigSvr = EnumField("configsvr", _("configsvr"))
ShardSvr = EnumField("shardsvr", _("shardsvr"))


class MongoDBTotalCache(float, StructuredEnum):
"""
cache占机器内存的百分比
"""

Cache_Percent = EnumField(0.65, _("cache_percent"))


class MongoDBDomainPrefix(str, StructuredEnum):
"""
mongodb domain Prefix
"""

MONGOS = EnumField("mongos", _("mongos"))
M1 = EnumField("m1", _("m1"))
M2 = EnumField("m2", _("m2"))
M3 = EnumField("m3", _("m3"))
M4 = EnumField("m4", _("m4"))
M5 = EnumField("m5", _("m5"))
M6 = EnumField("m6", _("m6"))
M7 = EnumField("m7", _("m7"))
M8 = EnumField("m8", _("m8"))
M9 = EnumField("m9", _("m9"))
M10 = EnumField("m10", _("m10"))
BACKUP = EnumField("backup", _("backup"))


class TBinlogDumperProtocolType(str, StructuredEnum):
"""
定义tbinlogdumper的对端协议
Expand Down
17 changes: 17 additions & 0 deletions dbm-ui/backend/flow/engine/bamboo/scene/common/get_file_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,3 +527,20 @@ def get_tbinlogdumper_package(self):
f"{env.BKREPO_PROJECT}/{env.BKREPO_BUCKET}/{tbinlogdumper_pkg.path}",
f"{env.BKREPO_PROJECT}/{env.BKREPO_BUCKET}/{self.actuator_pkg.path}",
]

def mongodb_pkg(self, db_version: str) -> list:
"""
部署mongodb,需要的pkg包
"""

mongodb_pkg = Package.get_latest_package(
version=db_version, pkg_type=MediumEnum.MongoDB, db_type=DBType.MongoDB
)
# bkdbmon_pkg = Package.get_latest_package(
# version=MediumEnum.Latest, pkg_type=MediumEnum.DbMon, db_type=DBType.MongoDB
# )
return [
f"{env.BKREPO_PROJECT}/{env.BKREPO_BUCKET}{self.actuator_pkg.path}",
f"{env.BKREPO_PROJECT}/{env.BKREPO_BUCKET}{mongodb_pkg.path}",
# f"{env.BKREPO_PROJECT}/{env.BKREPO_BUCKET}/{bkdbmon_pkg.path}",
]
Empty file.
48 changes: 48 additions & 0 deletions dbm-ui/backend/flow/engine/bamboo/scene/mongodb/base_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-DB管理系统(BlueKing-BK-DBM) available.
Copyright (C) 2017-2023 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 https://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.
"""

from typing import Dict, Optional

from backend.flow.utils.mongodb.mongodb_dataclass import MongoDBCluster


def start():
pass
"""
fix me
"""


class MongoBaseFlow(object):
"""MongoRemoveNsFlowflow
分析 payload,检查输入,生成Flow"""

def __init__(self, root_id: str, data: Optional[Dict]):
"""
传入参数
@param root_id : 任务流程定义的root_id
@param data : 单据传递过来的参数列表,是dict格式
"""

self.root_id = root_id
self.payload = data

# 检查 cluster 和 输入中的bk_biz_id字段是否相同.
@classmethod
def check_cluster(cls, cluster: MongoDBCluster, payload):
if cluster is None:
raise Exception("row.cluster_domain is not exists.")
if str(cluster.bk_biz_id) != payload["bk_biz_id"]:
raise Exception(
"bad bk_biz_id {} vs {} {} {}".format(
cluster.bk_biz_id, payload["bk_biz_id"], type(cluster.bk_biz_id), type(payload["bk_biz_id"])
)
)
98 changes: 98 additions & 0 deletions dbm-ui/backend/flow/engine/bamboo/scene/mongodb/mongodb_backup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-DB管理系统(BlueKing-BK-DBM) available.
Copyright (C) 2017-2023 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 https://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.
"""
import logging.config
from typing import Dict, Optional

from django.utils.translation import ugettext as _

from backend.configuration.constants import DBType
from backend.flow.engine.bamboo.scene.common.builder import Builder
from backend.flow.engine.bamboo.scene.common.get_file_list import GetFileList
from backend.flow.engine.bamboo.scene.mongodb.base_flow import MongoBaseFlow
from backend.flow.engine.bamboo.scene.mongodb.mongodb_fake_install import FlowActKwargs
from backend.flow.engine.bamboo.scene.mongodb.sub_task.backup import BackupSubTask
from backend.flow.plugins.components.collections.mongodb.send_media import ExecSendMediaOperationComponent
from backend.flow.utils.mongodb.mongodb_dataclass import MongoRepository

logger = logging.getLogger("flow")


class MongoBackupFlow(MongoBaseFlow):
"""MongoDB备份flow
分析 payload,检查输入,生成Flow"""

def __init__(self, root_id: str, data: Optional[Dict]):
"""
传入参数
@param root_id : 任务流程定义的root_id
@param data : 单据传递过来的参数列表,是dict格式
"""

self.root_id = root_id
self.payload = data

def start(self):
"""
mongo_backup install流程
"""

# backup_dir 提前创建好的,在部署的时候就创建好了.
backup_dir = FlowActKwargs(self.payload).get_backup_dir()
file_list = GetFileList(db_type=DBType.MongoDB).get_db_actuator_package()

# 创建流程实例
pipeline = Builder(root_id=self.root_id, data=self.payload)

# 解析输入
# 1. 解析每个集群Id的节点列表
# 2. 备份一般在某个Secondary且非Backup节点上执行. 但由于无法连接mongod,这里怎么搞?
# 3. 获得密码列表
# 4. 生成并发子任务.
# 介质下发——job的api可以多个IP并行执行

sub_pipelines = []
# bk_host {ip:"x.x.x.x", bk_cloud_id: "0"}
bk_host_list = []

# 域名忽略大小写.
cluster_domain_list = [row["cluster_domain"].lower() for row in self.payload["data_for_backup"]]
clusters = MongoRepository.fetch_many_cluster_dict(immute_domain__in=cluster_domain_list)

for row in self.payload["data_for_backup"]:
domain_lower = row["cluster_domain"].lower()
cluster = clusters[domain_lower]
self.check_cluster(cluster, self.payload)
sub_pl, sub_bk_host_list = BackupSubTask.process_cluster(
root_id=self.root_id,
ticket_data=self.payload,
sub_ticket_data=row,
cluster=cluster,
backup_dir=backup_dir,
)
bk_host_list.extend(sub_bk_host_list)
sub_pipelines.append(sub_pl.build_sub_process(_("MongoDB-备份-{}".format(cluster.name))))

send_media_kwargs = {
"file_list": file_list,
"ip_list": bk_host_list,
"exec_ips": [item["ip"] for item in bk_host_list],
"file_target_path": backup_dir + "/install",
}
pipeline.add_act(
act_name=_("MongoDB-介质下发"),
act_component_code=ExecSendMediaOperationComponent.code,
kwargs=send_media_kwargs,
)

pipeline.add_parallel_sub_pipeline(sub_flow_list=sub_pipelines)

# 运行流程
pipeline.run_pipeline()
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-DB管理系统(BlueKing-BK-DBM) available.
Copyright (C) 2017-2023 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 https://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.
"""
import logging.config
from typing import Dict, Optional

from django.utils.translation import ugettext as _

from backend.flow.engine.bamboo.scene.common.builder import Builder
from backend.flow.engine.bamboo.scene.mongodb.sub_task import deinstall
from backend.flow.plugins.components.collections.mongodb.send_media import ExecSendMediaOperationComponent
from backend.flow.utils.mongodb.mongodb_dataclass import ActKwargs

logger = logging.getLogger("flow")


class MongoDBDeInstallFlow(object):
"""MongoDB卸载flow"""

def __init__(self, root_id: str, data: Optional[Dict]):
"""
传入参数
@param root_id : 任务流程定义的root_id
@param data : 单据传递过来的参数列表,是dict格式
"""

self.root_id = root_id
self.data = data
self.get_kwargs = ActKwargs()
self.get_kwargs.payload = data
self.get_kwargs.get_file_path()

def prepare_job(self, pipeline: Builder):
"""
准备工作
"""

# 介质下发——job的api可以多个IP并行执行
kwargs = self.get_kwargs.get_send_media_kwargs()
pipeline.add_act(
act_name=_("MongoDB-介质下发"), act_component_code=ExecSendMediaOperationComponent.code, kwargs=kwargs
)

def multi_cluster_deinstall_flow(self):
"""
multi cluster deinstall流程
"""

# 创建流程实例
pipeline = Builder(root_id=self.root_id, data=self.data)

# 获取所有的cluster主机信息
self.get_kwargs.get_hosts_deinstall()

# 下发介质
self.prepare_job(pipeline=pipeline)

# 卸载——子流程并行
sub_pipelines = []
for cluster_id in self.data["cluster_ids"]:
sub_pipline = deinstall(
root_id=self.root_id, ticket_data=self.data, sub_kwargs=self.get_kwargs, cluster_id=cluster_id
)
sub_pipelines.append(sub_pipline)
pipeline.add_parallel_sub_pipeline(sub_flow_list=sub_pipelines)

# 运行流程
pipeline.run_pipeline()
Loading

0 comments on commit 32d66de

Please sign in to comment.