def post(self, request): server_id = request.POST.get('server_id', '') try: server = BkServer.objects.get(id=server_id) except Exception: logger.exception("服务器信息[id:%s]不存在", server_id) return FailJsonResponse("服务器信息不存在,请重新添加") if server.is_active: return OKJsonResponse("服务器已激活") # V1 版本 判断 测试环境/正式环境 分别只能激活一台服务器 active_server = BkServer.objects.category_has_active_server( server.category, server_id) if active_server: message = "已经有一台{} [IP:{}, 端口:{}] 被激活<br><br>不能再激活其他{}".format( active_server.get_category_display(), active_server.ip_address, active_server.ip_port, active_server.get_category_display()) return FailJsonResponse(message) ok, message = activate_agent(server_id) if not ok: return FailJsonResponse("服务器激活失败: {}".format(message)) return OKJsonResponse("服务器已激活")
def post(self, request): """添加/编辑第三方服务信息 """ form = ExternalServerForm(request.POST) if not form.is_valid(): message = first_error_message(form) raise BadRequestException(message) server_id = form.cleaned_data["server_id"] server_ip = form.cleaned_data["server_ip"] server_port = form.cleaned_data["server_port"] server_cate = form.cleaned_data["server_cate"] username = form.cleaned_data["username"] password = form.cleaned_data["password"] if ThirdServer.objects.is_server_exists(server_id, server_ip, server_port): message = "IP为[{ip}], 端口为 [{port}] 的服务器已经存在".format( ip=server_ip, port=server_port) return FailJsonResponse(message) try: data = ThirdServer.objects.update_or_create_server( server_id, server_ip, server_port, username, password, server_cate) return OKJsonResponse("保存成功", data=data) except Exception as e: logger.exception("保存服务信息异常:%s", e) return FailJsonResponse("保存出错", data={})
def post(self, request): """添加/编辑AppServer信息 """ form = ServerForm(request.POST) if not form.is_valid(): message = first_error_message(form) raise BadRequestException(message) server_id = form.cleaned_data["server_id"] server_ip = form.cleaned_data["server_ip"] server_port = form.cleaned_data["server_port"] app_port = form.cleaned_data["app_port"] server_cate = form.cleaned_data["server_cate"] # 验证 ip & port 是否重复 if BkServer.objects.is_server_exists(server_id, server_ip, server_port): message = "IP为[{ip}], 端口为 [{port}] 的服务器已经存在".format( ip=server_ip, port=server_port) return FailJsonResponse(message) # 编辑信息 try: data = BkServer.objects.update_or_create_server( server_id, server_ip, server_port, app_port, server_cate) return OKJsonResponse("保存成功", data=data) except Exception as e: logger.exception("保存应用服务器信息异常:%s", e) return FailJsonResponse("保存出错", data={})
def delete(self, request, app_code, var_id): try: AppEnvVar.objects.filter(id=var_id).delete() except Exception: logger.exception("删除app环境变量失败") return FailJsonResponse("删除app环境变量失败") return OKJsonResponse("删除成功")
def post(self, request, *args, **kwargs): app_code = self.kwargs["app_code"] username = request.user.username ok, message = delete_saas_app(app_code, username) if ok: return OKJsonResponse(message) return FailJsonResponse(message)
def post(self, request, *args, **kwargs): app_code = self.kwargs["app_code"] logger.info("[app:%s] 开始进行[删除]...", app_code) username = request.user.username app = App.objects.get(code=app_code) can_be_deleted, message = app.can_be_deleted(username) if not can_be_deleted: logger.info("[app:%s] %s", app_code, message) return FailJsonResponse(message) try: SecureInfo.objects.filter(app_code=app_code).delete() App.objects.filter(code=app_code).delete() # 将APP的发布记录保存为上一次,避免下次创建时显示冲突 Record.objects.filter(app_code=app_code).update(version='last') except Exception: message = "删除失败!" logger.exception("[app:%s] %s", app_code, message) return FailJsonResponse(message) # 操作流水日志 extra_data = {"username": username} _r(app_code, username, UserOperateTypeEnum.APP_DELETE.value, extra_data) message = "删除成功!" logger.info("[app:%s] %s", app_code, message) return OKJsonResponse(message)
def post(self, request): server_id = request.POST.get('server_id', '') try: server = ThirdServer.objects.get(id=server_id) except Exception: logger.exception("服务信息[id:%s]不存在", server_id) return FailJsonResponse("服务信息不存在,请重新添加") if server.is_active: return FailJsonResponse("服务已激活") # V1 版本 判断只能激活一台服务器 active_server = ThirdServer.objects.category_has_active_server( server.category, server_id) if active_server: message = "已经有一台 {} 服务被激活<br><br>不能再激活其他 {} 服务".format( active_server.get_category_display(), active_server.get_category_display()) return FailJsonResponse(message) ok, message = activate_service(server.category, server_id) if not ok: return FailJsonResponse("服务激活失败: {}".format(message)) return OKJsonResponse("服务已激活")
def delete(self, request, server_id): """删除第三方服务 """ if not server_id: raise BadRequestException('请选择要删除的服务') try: ThirdServer.objects.filter(id=server_id).delete() except Exception: logger.exception("删除服务[id:%s]失败", server_id) return FailJsonResponse("删除服务失败") return OKJsonResponse("删除成功")
def delete(self, request, server_id): """删除AppServer信息 """ if not server_id: raise BadRequestException("请选择要删除的服务器") try: BkServer.objects.filter(id=server_id).delete() except Exception: logger.exception("删除服务器[id:%s]失败", server_id) return FailJsonResponse("删除服务器失败") return OKJsonResponse("删除成功")
def post(self, request): bk_token = request.COOKIES.get(settings.BK_COOKIE_NAME, None) data = { 'chname': request.POST.get('chname').strip(), 'phone': request.POST.get('phone').strip(), 'email': request.POST.get('email').strip() } ok, message = modify_user_info(bk_token, data) if not ok: return FailJsonResponse(message or "个人信息修改失败") return OKJsonResponse("success")
def post(self, request): server_id = request.POST.get('server_id', '') try: server = ThirdServer.objects.get(id=server_id) except Exception: logger.exception("服务器信息[id:%s]不存在", server_id) return FailJsonResponse("服务器信息不存在,请重新添加") ok, message = activate_service(server.category, server_id) if not ok: return FailJsonResponse("服务刷新失败: {}".format(message)) return OKJsonResponse("服务刷新成功")
def get(self, request, *args, **kwargs): app_code = self.kwargs["app_code"] app = App.objects.get(code=app_code) records = Record.objects.get_last_ongoing_records(app_code, size=10) for record in records: event_id = record.event_id event_ids = [event_id] if record.operate_id == OperateIDEnum.IN_OFFLINE.value: try: event_ids = json.loads(record.extra_data).get( "event_ids", []) except Exception: event_ids = [event_id] ok, data = get_event_log(app_code=app_code, auth_token=app.auth_token, event_ids=event_ids) if not ok: continue status = data.get("status") # 判定操作时间, 超过了, 就判定是超时, 直接失败 expire_seconds = (datetime.datetime.now() - record.operate_time).total_seconds() if (expire_seconds > settings.HISTORY_EVENT_STATE_EXPIRE_SECONDS and status != EventStatusEnum.SUCCESS.value): message = "check_unfinished_task, 事件超时({}s), 设置为失败".format( settings.HISTORY_EVENT_STATE_EXPIRE_SECONDS) # noqa logger.info("[app:%s] %s, event_id:%s", app_code, message, event_id) record.message = message status = EventStatusEnum.FAILURE.value if status in (EventStatusEnum.SUCCESS.value, EventStatusEnum.FAILURE.value): record.is_success = (status == EventStatusEnum.SUCCESS.value) to_operate_id = { OperateIDEnum.IN_TEST.value: OperateIDEnum.TO_TEST.value, OperateIDEnum.IN_ONLINE.value: OperateIDEnum.TO_ONLINE.value, OperateIDEnum.IN_OFFLINE.value: OperateIDEnum.TO_OFFLINE.value }.get(record.operate_id, record.operate_id) record.operate_id = to_operate_id record.save() return OKJsonResponse("success")
def put(self, request, user_id): request_param = QueryDict(request.body) form = SetPasswordForm(request_param) if not form.is_valid(): message = first_error_message(form) return FailJsonResponse(message) # 修改密码 result, message = BkUser.objects.modify_password_by_userid( user_id, form.cleaned_data['new_password1']) if not result: return FailJsonResponse(message) return OKJsonResponse(_("修改密码成功"))
def post(self, request): form = PasswordChangeForm(request.POST) if not form.is_valid(): message = first_error_message(form) raise BadRequestException(message) new_password1 = form.cleaned_data.get("new_password1") bk_token = request.COOKIES.get(settings.BK_COOKIE_NAME, None) data = {'new_password': new_password1} ok, message = change_password(bk_token, data) if not ok: return FailJsonResponse(message or "密码重置失败") return OKJsonResponse("success")
def _add_or_update(self, request, app_code, var_id=None): if not var_id: form = AppEnvForm(request.POST) else: put = QueryDict(request.body) form = AppEnvForm(put) if not form.is_valid(): message = first_error_message(form) # print form.errors raise BadRequestException(message) # app_code = form.cleaned_data["app_code"] name = form.cleaned_data["name"] value = form.cleaned_data["value"] intro = form.cleaned_data["intro"] mode = form.cleaned_data["mode"] name = 'BKAPP_%s' % name # do add if not var_id: if AppEnvVar.objects.exists(app_code, mode, name): message = "变量名已经存在, 请勿重复添加!" return FailJsonResponse(message) try: env_var = AppEnvVar.objects.create(app_code=app_code, mode=mode, name=name, value=value, intro=intro) var_id = env_var.id except Exception: # 保存app环境变量异常 message = "保存app环境变量失败" logger.exception(message) return FailJsonResponse(message) # do update else: if AppEnvVar.objects.update_target_exists(app_code, mode, name, var_id): message = "同名变量已经存在! 无法对当前变量进行更新" return FailJsonResponse(message) AppEnvVar.objects.update(var_id, name, value, intro, mode) return OKJsonResponse("保存变量成功", id=var_id)
def post(self, request, *args, **kwargs): app_code = self.kwargs["app_code"] username = request.user.username logger.info("[app:%s] 开始进行[正式部署]...", app_code) app = App.objects.get(code=app_code) try: form_data = json.loads(request.POST.get("form_data", '{}')) except Exception as e: message = "参数错误!" logger.exception("[app:%s] %s error=%s", app_code, message, e) return BadRequestException(message) is_prod_app_deployable = BkServer.objects.check_prod_app_deployable() if not is_prod_app_deployable: message = "当前没有可用的[正式服务器], 无法进行提测操作. 请到<a href='/engine/server/'> [蓝鲸智云-开发者中心-服务器信息] </a> 注册并激活服务器" logger.info("[app:%s] %s", app_code, message) return FailJsonResponse(message) # 前端变量不要一直向后, 限制 is_tips = form_data.get("is_tips", 0) features = form_data.get("features", "") bugs = form_data.get("bugs", "") can_be_online, message = app.can_be_online() if not can_be_online: logger.info("[app:%s] %s", app_code, message) return FailJsonResponse(message) # 上线操作 ok, event_id, message = app_to_online_task(app_code, app, username, is_tips, features, bugs) # 操作流水日志 extra_data = {"username": username, "form_data": form_data} _r(app_code, username, UserOperateTypeEnum.RELEASE_ONLINE.value, extra_data) if not ok: logger.info("[app:%s] %s event_id: %s", app_code, message, event_id) return FailJsonResponse(message, event_id=event_id) message = "正式部署事件提交成功!" logger.info("[app:%s] %s event_id: %s", app_code, message, event_id) return OKJsonResponse(message, event_id=event_id)
def _add_or_update(self, request, user_id=None): request_param = request.POST if user_id is None else QueryDict( request.body) form = UserInfoForm(request_param) if not form.is_valid(): message = first_error_message(form) return FailJsonResponse(message) # 创建用户 result, user_id, message = BkUser.objects.modify_or_create_user_by_userid( user_id, form.cleaned_data["username"], form.cleaned_data["chname"], form.cleaned_data["phone"], form.cleaned_data["email"], form.cleaned_data["role"]) if not result: return FailJsonResponse(message) return OKJsonResponse(_("保存用户信息成功"), data={"user_id": user_id})
def post(self, request, *args, **kwargs): app_code = self.kwargs["app_code"] username = request.user.username logger.info("[app:%s] 开始进行[下架]...", app_code) try: form_data = json.loads(request.POST.get("form_data", '{}')) except Exception: message = "参数错误!" logger.exception("[app:%s] %s", app_code, message) return BadRequestException(message) # NOTE: 下架不加检查服务器, 因为此时已经提测/上线的, 所以默认可以下架成功 # 获取应用基本信息 app = App.objects.get(code=app_code) # 状态判定 mode = form_data.get("mode", "all") can_be_offline, message = app.can_be_offline(mode) if not can_be_offline: logger.info("[app:%s] %s", app_code, message) return FailJsonResponse(message) # 执行下架 app_old_state = app.state auth_token = app.auth_token ok, event_id = app_to_offline_task(app_code, auth_token, username, mode, app_old_state) # 操作流水日志 extra_data = {"username": username, "form_data": form_data} _r(app_code, username, UserOperateTypeEnum.RELEASE_OFFLINE.value, extra_data) if ok: message = "下架事件提交成功!" logger.info("[app:%s] %s event_id: %s", app_code, message, event_id) return OKJsonResponse(message, event_id=event_id) message = "下架事件提交失败!" logger.info("[app:%s] %s event_id: %s", app_code, message, event_id) return FailJsonResponse(message, event_id=event_id)
def get(self, request): # NOTE: better name is: target_app_codes app_codes = request.GET.get('target_app_code') query = App.objects.all() # 过滤查询的app_codes if app_codes: app_code_list = app_codes.split(';') query = query.filter(code__in=app_code_list) # 按照创建时间逆排序 query = query.values('code', 'name').order_by('-created_date') app_list = [{ 'app_code': i['code'], 'app_name': i['name'] } for i in query] return OKJsonResponse("SUCCESS", data=app_list, code="00")
def post(self, request, *args, **kwargs): app_code = self.kwargs["app_code"] operate = request.POST.get('operate', '') if not operate: raise BadRequestException("参数异常") # 保存基本信息 try: if operate == 'base': self._update_base_info(request, app_code) elif operate == 'introduction': self._update_introduction(request, app_code) elif operate == 'vcs': self._update_vsc_info(request, app_code) elif operate == 'db': self._update_db_info(request, app_code) except BadRequestException as e: raise e except Exception as e: logger.exception("保存用户基本信息异常:%s", e) return FailJsonResponse("编辑失败") return OKJsonResponse("编辑成功")
def delete(self, request, user_id): result, message = BkUser.objects.delete_user(user_id) if not result: return FailJsonResponse(message) return OKJsonResponse(_("用户删除成功"))
def post(self, request, *args, **kwargs): app_code = self.kwargs["app_code"] username = request.user.username logger.info("[app:%s] 开始进行[测试部署]...", app_code) app = App.objects.get(code=app_code) # 检测测试服务器是否激活 is_test_app_deployable = BkServer.objects.check_test_app_deployable() if not is_test_app_deployable: message = "当前没有可用的[测试服务器], 无法进行提测操作. 请到<a href='/engine/server/'> [蓝鲸智云-开发者中心-服务器信息] </a> 注册并激活服务器" logger.info("[app:%s] %s", app_code, message) return FailJsonResponse(message) # 只有[下架/开发/测试/上线]状态可操作 can_be_test, message = app.can_be_test() if not can_be_test: logger.info("[app:%s] %s", app_code, message) return FailJsonResponse(message) # 启用服务 form_data = request.POST.get("form_data", None) if form_data: try: form_data = json.loads(request.POST.get("form_data")) except Exception as e: message = "参数错误!" logger.exception("[app:%s] %s error=%s", app_code, message, str(e)) return BadRequestException(message) is_use_celery = (form_data.get("is_use_celery") == "checked") is_use_celery_beat = ( form_data.get("is_use_celery_beat") == "checked") try: app.trigger_celery(is_use_celery, is_use_celery_beat) logger.info( "update app info [is_use_celery=%s, is_use_celery_beat=%s]", app.is_use_celery, app.is_use_celery_beat) except Exception: logger.exception( "Update is_use_celery/is_use_celery_beat fail!") # 提测 ok, event_id, message = app_to_test_task(app_code, app, username) # 记录操作流水日志 extra_data = { "username": username, "is_success": ok, "event_id": event_id } _r(app_code, username, UserOperateTypeEnum.RELEASE_TEST.value, extra_data) if ok: message = "测试部署事件提交成功!" logger.info("[app:%s] %s event_id: %s", app_code, message, event_id) return OKJsonResponse(message, event_id=event_id) logger.info("[app:%s] %s event_id: %s", app_code, message, event_id) return FailJsonResponse(message, event_id=event_id)
def post(self, request): username = request.user.username apps = request.POST.get('apps') if apps: UserSettings.objects.filter(username=username).update(apps=apps) return OKJsonResponse("排序成功")