-
Notifications
You must be signed in to change notification settings - Fork 55
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: 优化订阅任务按顺序执行而非抛错 (closed #2447)
- Loading branch information
Showing
9 changed files
with
480 additions
and
115 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
115 changes: 115 additions & 0 deletions
115
apps/backend/periodic_tasks/schedule_running_subscription_task.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
# -*- coding: utf-8 -*- | ||
""" | ||
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available. | ||
Copyright (C) 2017-2022 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 json | ||
from typing import Any, Dict, List | ||
|
||
from celery.schedules import crontab | ||
from celery.task import periodic_task | ||
from django.db.models import QuerySet | ||
from django.utils import timezone | ||
|
||
from apps.backend import constants | ||
from apps.backend.subscription.handler import SubscriptionHandler | ||
from apps.backend.utils.redis import REDIS_INST | ||
from apps.node_man import models | ||
from common.log import logger | ||
|
||
|
||
def get_need_clean_subscription_app_code(): | ||
""" | ||
获取配置需要清理的appcode | ||
""" | ||
app_codes: List[str] = models.GlobalSettings.get_config( | ||
key=models.GlobalSettings.KeyEnum.NEED_CLEAN_SUBSCRIPTION_APP_CODE.value, default=[] | ||
) | ||
return app_codes | ||
|
||
|
||
@periodic_task(run_every=constants.UPDATE_SUBSCRIPTION_TASK_INTERVAL, queue="backend", options={"queue": "backend"}) | ||
def schedule_update_subscription(): | ||
name: str = constants.UPDATE_SUBSCRIPTION_REDIS_KEY_TPL | ||
# 先计算出要从redis取数据的长度 | ||
length: int = min(REDIS_INST.llen(name), constants.MAX_SUBSCRIPTION_TASK_COUNT) | ||
# 从redis中取出对应长度的数据 | ||
update_params: List[bytes] = REDIS_INST.lrange(name, -length, -1) | ||
# 使用ltrim保留剩下的,可以保证redis中新push的值不会丢失 | ||
REDIS_INST.ltrim(name, 0, -length - 1) | ||
# 翻转数据,先进的数据先处理 | ||
update_params.reverse() | ||
results = [] | ||
if not update_params: | ||
return | ||
for update_param in update_params: | ||
# redis取出为bytes类型,需进行解码后转字典 | ||
params = json.loads(update_param.decode()) | ||
subscription_id = params["subscription_id"] | ||
try: | ||
result: Dict[str, int] = SubscriptionHandler.update_subscription(params=params) | ||
except Exception as e: | ||
logger.exception(f"{subscription_id} update scription failed with error: {e}") | ||
result = {"subscription_id": subscription_id, "update_result": False} | ||
results.append(result) | ||
logger.info(f" update scription with results: {results}, length -> {len(results)} ") | ||
|
||
|
||
@periodic_task(run_every=constants.UPDATE_SUBSCRIPTION_TASK_INTERVAL, queue="backend", options={"queue": "backend"}) | ||
def schedule_run_scription(): | ||
name: str = constants.RUN_SUBSCRIPTION_REDIS_KEY_TPL | ||
length: int = min(REDIS_INST.llen(name), constants.MAX_SUBSCRIPTION_TASK_COUNT) | ||
run_params: List[bytes] = REDIS_INST.lrange(name, -length, -1) | ||
REDIS_INST.ltrim(name, 0, -length - 1) | ||
run_params.reverse() | ||
results = [] | ||
if not run_params: | ||
return | ||
for run_param in run_params: | ||
# redis取出为bytes类型,需进行解码后转字典 | ||
params = json.loads(run_param.decode()) | ||
subscription_id = params["subscription_id"] | ||
scope = params["scope"] | ||
actions = params["actions"] | ||
try: | ||
result: Dict[str, int] = SubscriptionHandler(subscription_id).run(scope=scope, actions=actions) | ||
except Exception as e: | ||
logger.exception(f"{subscription_id} run scription failed with error: {e}") | ||
result = {"subscription_id": subscription_id, "run_result": False} | ||
results.append(result) | ||
logger.info(f"run subscription with results: {results}, length -> {len(results)}") | ||
|
||
|
||
@periodic_task( | ||
run_every=crontab(hour="3", minute="0", day_of_week="*", day_of_month="*", month_of_year="*"), | ||
queue="default", | ||
options={"queue": "default"}, | ||
) | ||
def clean_deleted_subscription(): | ||
query_kwargs: Dict[str, Any] = { | ||
"is_deleted": True, | ||
"from_system": "bkmonitorv3", | ||
"deleted_time__range": ( | ||
timezone.now() - timezone.timedelta(days=constants.SUBSCRIPTION_DELETE_DAYS), | ||
timezone.now(), | ||
), | ||
} | ||
|
||
app_codes = get_need_clean_subscription_app_code() | ||
if app_codes: | ||
query_kwargs.pop("from_system") | ||
query_kwargs["from_system__in"] = app_codes | ||
|
||
subscription_qs: QuerySet = models.Subscription.objects.filter(**query_kwargs) | ||
if not subscription_qs.exists(): | ||
# 没有需要更新的订阅 | ||
return | ||
|
||
subscription_ids = list(subscription_qs.values_list("id", flat=True)) | ||
subscription_qs.update(nodes=[], is_deleted=False, enable=True) | ||
logger.info(f"set {subscription_ids} nodes be null and enable auto trigger, length -> {len(subscription_ids)}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.