示例#1
0
    def stop_service(self, service, username, tenant_id=None):
        try:
            event = ServiceEvent(event_id=make_uuid(),
                                 service_id=service.service_id,
                                 tenant_id=tenant_id,
                                 type="stop",
                                 deploy_version=service.deploy_version,
                                 user_name=username,
                                 start_time=datetime.datetime.now())
            event.save()

            body = {}
            body["operator"] = str(username)
            body["event_id"] = event.event_id
            tenant = Tenants.objects.get(tenant_id=service.tenant_id)
            body["enterprise_id"] = tenant.enterprise_id
            region_api.stop_service(service.service_region, tenant.tenant_name,
                                    service.service_alias, body)

            monitorhook.serviceMonitor(username, service, 'app_stop', True)
            return 200, True, "success"
        except Exception as e:
            logger.exception("openapi.services", e)
            monitorhook.serviceMonitor(username, service, 'app_stop', False)
            return 409, False, "停止服务失败"
示例#2
0
    def post(self, request, *args, **kwargs):
        try:
            perm = PermRelTenant.objects.filter(
                tenant_id=self.tenant.ID).first()
            enterprise = TenantEnterprise.objects.get(pk=perm.enterprise_id)
        except (TenantEnterprise.DoesNotExist, PermRelTenant.DoesNotExist):
            return JsonResponse(data={
                'ok': False,
                'msg': '企业信息或关系不存在'
            },
                                status=200)

        if ServiceEvent.objects.filter(service_id=enterprise.ID,
                                       type='market_sync',
                                       final_status='').count() > 0:
            return JsonResponse(data={
                'ok': False,
                'msg': '应用正在同步, 请稍后重试'
            },
                                status=200)

        download_event = ServiceEvent(event_id=make_uuid(),
                                      service_id=enterprise.ID,
                                      tenant_id=self.tenant.tenant_id,
                                      type='market_sync',
                                      status='success',
                                      user_name=self.user.nick_name,
                                      start_time=datetime.datetime.now())
        download_event.save()

        t = threading.Thread(target=self.__download,
                             args=(download_event, enterprise, self.tenant))
        t.start()
        return JsonResponse(data={'ok': True}, status=200)
 def create_service_event(self, service, tenant, action):
     event = ServiceEvent(event_id=make_uuid(), service_id=service.service_id,
                          tenant_id=tenant.tenant_id, type="{0}".format(action),
                          deploy_version=service.deploy_version,
                          old_deploy_version=service.deploy_version,
                          user_name=self.user.nick_name, start_time=datetime.datetime.now())
     event.save()
     return event
示例#4
0
    def post(self, request, format=None):
        """

        停止服务
        ---
        parameters:
            - name: service_id
              description: 操作ID
              required: true
              type: string
              paramType: form
            - name: region
              description: 数据中心
              required: true
              type: string
              paramType: form
            - name: action
              description: 操作
              required: false
              type: string
              paramType: form
        """
        data = {}
        try:
            service_id = request.data.get("service_id")
            service_region = request.data.get("region")
            action = request.data.get("action", "own_money")
            service = TenantServiceInfo.objects.get(service_region=service_region,service_id=service_id)
            tenant = Tenants.objects.get(tenant_id=service.tenant_id)
            body = region_api.check_service_status(service_region, tenant.tenant_name, service.service_alias,tenant.enterprise_id)
            bean = body["bean"]

            status = bean["cur_status"]
            if status not in ('closed', 'undeploy', 'deploying'):
                event_id = make_uuid()
                service = TenantServiceInfo.objects.get(service_id=service_id)
                event = ServiceEvent(event_id=event_id, service_id=service_id,
                                     tenant_id=service.tenant_id, type=action,
                                     deploy_version=service.deploy_version, old_deploy_version=service.deploy_version,
                                     user_name="system", start_time=datetime.datetime.now())
                event.save()
                body = {}
                body["operator"] = str("system")
                body["event_id"] = event_id
                body["enterprise_id"] = tenant.enterprise_id

                region_api.stop_service(service.service_region,
                                        tenant.tenant_name,
                                        service.service_alias,
                                        body)
            data["status"] = "success"
        except TenantServiceInfo.DoesNotExist as ex:
            logger.exception(ex)
            logger.error("service is not exist")
        except Exception as e:
            logger.exception(e)
            data["status"] = "failure"
        return Response(data, status=200)
示例#5
0
 def create_publish_event(self, record_event, user_name, event_type):
     import datetime
     event = ServiceEvent(event_id=make_uuid(),
                          service_id=record_event.service_id,
                          tenant_id=record_event.team_id,
                          type=event_type,
                          user_name=user_name,
                          start_time=datetime.datetime.now())
     event.save()
     return event
示例#6
0
    def post(self, request, *args, **kwargs):
        result = {}
        event_id = make_uuid()
        try:
            old_deploy_version = ""
            # 检查上次事件是否完成
            events = ServiceEvent.objects.filter(
                service_id=self.service.service_id).order_by("-start_time")
            if events:
                last_event = events[0]
                if last_event.final_status == "":
                    if not baseService.checkEventTimeOut(last_event):
                        result["status"] = "often"
                        return JsonResponse(result, status=200)
                old_deploy_version = last_event.deploy_version
            action = request.POST["action"]
            if not action:
                result["status"] = "failure"
                result["msg"] = "action cannot be empty"
                return JsonResponse(result, status=200)
            event = ServiceEvent(event_id=event_id,
                                 service_id=self.service.service_id,
                                 tenant_id=self.tenant.tenant_id,
                                 type=action,
                                 deploy_version=self.service.deploy_version,
                                 old_deploy_version=old_deploy_version,
                                 user_name=self.user.nick_name,
                                 start_time=datetime.datetime.now())
            old_code_version = ""
            if action == "deploy":
                last_all_deploy_event = ServiceEvent.objects.filter(
                    service_id=self.service.service_id,
                    type="deploy").order_by("-start_time")
                if last_all_deploy_event:
                    last_deploy_event = last_all_deploy_event[0]
                    old_code_version = last_deploy_event.code_version
                    event.old_code_version = old_code_version

            event.save()
            result["status"] = "success"
            result["event"] = {}
            result["event"]["event_id"] = event.event_id
            result["event"]["user_name"] = event.user_name
            result["event"]["event_type"] = event.type
            result["event"]["event_start_time"] = event.start_time
            result["event"]["old_deploy_version"] = old_deploy_version
            result["event"]["old_code_version"] = old_code_version
            return JsonResponse(result, status=200)
        except Exception as e:
            logger.exception(e)
            result["status"] = "failure"
            result["message"] = e.message
            ServiceEvent.objects.filter(event_id=event_id).delete()
            return JsonResponse(result, status=500)
示例#7
0
    def update_service_memory(self,
                              tenant,
                              service,
                              username,
                              memory,
                              limit=True):
        cpu = baseService.calculate_service_cpu(service.service_region, memory)
        old_cpu = service.min_cpu
        old_memory = service.min_memory
        if int(memory) != old_memory or cpu != old_cpu:
            left = memory % 128
            if memory > 0 and memory <= 65536 and left == 0:
                # calculate resource
                diff_memory = memory - int(old_memory)
                if limit:
                    rt_type, flag = self.predict_next_memory(
                        tenant, service, diff_memory, True)
                    if not flag:
                        if rt_type == "memory":
                            return 410, False, "内存不足"
                        else:
                            return 411, False, "余额不足"

                event = ServiceEvent(event_id=make_uuid(),
                                     service_id=service.service_id,
                                     tenant_id=tenant.tenant_id,
                                     type="update",
                                     deploy_version=service.deploy_version,
                                     user_name=username,
                                     start_time=datetime.datetime.now())
                event.save()

                body = {
                    "container_memory": memory,
                    "deploy_version": service.deploy_version,
                    "container_cpu": cpu,
                    "operator": username,
                    "event_id": event.event_id,
                    "enterprise_id": tenant.enterprise_id
                }
                region_api.vertical_upgrade(service.service_region,
                                            tenant.tenant_name,
                                            service.service_alias, body)
                # 更新console记录
                service.min_cpu = cpu
                service.min_memory = memory
                service.save()
                # 添加记录
                monitorhook.serviceMonitor(username, service, 'app_vertical',
                                           True)
        return 200, True, "success"
示例#8
0
 def create_gitChange_events(self,service):
     try:
         import datetime
         event = ServiceEvent(event_id=make_uuid(), service_id=service.service_id,
                              tenant_id=self.tenant.tenant_id, type="git-change",
                              deploy_version=service.deploy_version,
                              old_deploy_version=service.deploy_version,
                              user_name=self.user.nick_name, start_time=datetime.datetime.now())
         event.save()
         self.event = event
         return event.event_id
     except Exception as e:
         self.event = None
         logger.error(e)
示例#9
0
    def create_service_event(self, tenant, service):

        try:
            import datetime
            event = ServiceEvent(event_id=make_uuid(), service_id=service.service_id,
                                 tenant_id=tenant.tenant_id, type="upgrade",
                                 deploy_version=service.deploy_version,
                                 old_deploy_version=service.deploy_version,
                                 user_name="system", start_time=datetime.datetime.now())
            event.save()
            self.event = event
            return event.event_id
        except Exception as e:
            self.event = None
            raise e
示例#10
0
def create_label_event(tenant, user, service, action):
    try:
        import datetime
        event = ServiceEvent(event_id=make_uuid(),
                             service_id=service.service_id,
                             tenant_id=tenant.tenant_id,
                             type="{0}".format(action),
                             deploy_version=service.deploy_version,
                             old_deploy_version=service.deploy_version,
                             user_name=user.nick_name,
                             start_time=datetime.datetime.now())
        event.save()
        return event.event_id
    except Exception as e:
        raise e
示例#11
0
    def get(self, request, *args, **kwargs):
        try:
            perm = PermRelTenant.objects.filter(
                tenant_id=self.tenant.ID).first()
            enterprise = TenantEnterprise.objects.get(pk=perm.enterprise_id)
        except (TenantEnterprise.DoesNotExist, PermRelTenant.DoesNotExist):
            return JsonResponse(data={
                'ok': False,
                'msg': '企业信息或关系不存在'
            },
                                status=200)

        event_list = ServiceEvent.objects.filter(service_id=enterprise.ID,
                                                 type='market_sync',
                                                 final_status='')

        event = event_list[0] if event_list.count() > 0 else ServiceEvent()
        return JsonResponse(data={
            'ok': True,
            'msg': 'ok',
            'event_id': event.event_id,
            'final_status': event.final_status,
            'message': event.message
        },
                            status=200)
示例#12
0
 def _create_publish_event(self, service, info):
     try:
         import datetime
         event = ServiceEvent(event_id=make_uuid(),
                              service_id=service.service_id,
                              tenant_id=self.tenant.tenant_id,
                              type="share-{0}".format(info),
                              deploy_version=service.deploy_version,
                              old_deploy_version=service.deploy_version,
                              user_name=self.user.nick_name,
                              start_time=datetime.datetime.now())
         event.save()
         self.event = event
         return event.event_id
     except Exception as e:
         self.event = None
         raise e
示例#13
0
 def update_service_node(self,
                         tenant,
                         service,
                         username,
                         node_num,
                         limit=True):
     new_node_num = int(node_num)
     old_min_node = service.min_node
     if new_node_num >= 0 and new_node_num != old_min_node:
         # calculate resource
         diff_memory = (new_node_num - old_min_node) * service.min_memory
         if limit:
             rt_type, flag = self.predict_next_memory(
                 tenant, service, diff_memory, True)
             if not flag:
                 if rt_type == "memory":
                     return 410, False, "内存不足"
                 else:
                     return 411, False, "余额不足"
         event = ServiceEvent(event_id=make_uuid(),
                              service_id=service.service_id,
                              tenant_id=tenant.tenant_id,
                              type="update",
                              deploy_version=service.deploy_version,
                              user_name=username,
                              start_time=datetime.datetime.now())
         event.save()
         body = {
             "node_num": new_node_num,
             "deploy_version": service.deploy_version,
             "operator": username,
             "event_id": event.event_id,
             "enterprise_id": tenant.enterprise_id
         }
         region_api.horizontal_upgrade(service.service_region,
                                       tenant.tenant_name,
                                       service.service_alias, body)
         service.min_node = new_node_num
         service.save()
         monitorhook.serviceMonitor(username, service, 'app_horizontal',
                                    True)
     return 200, True, "success"
示例#14
0
    def start_service(self, tenant, service, username, limit=True):
        try:
            # calculate resource
            diff_memory = service.min_node * service.min_memory
            if limit:
                rt_type, flag = self.predict_next_memory(
                    tenant, service, diff_memory, False)
                if not flag:
                    if rt_type == "memory":
                        return 410, False, "内存不足"
                    else:
                        return 411, False, "余额不足"

            event = ServiceEvent(event_id=make_uuid(),
                                 service_id=service.service_id,
                                 tenant_id=tenant.tenant_id,
                                 type="restart",
                                 deploy_version=service.deploy_version,
                                 user_name=username,
                                 start_time=datetime.datetime.now())
            event.save()

            body = {}
            body["deploy_version"] = service.deploy_version
            body["operator"] = str(username)
            body["event_id"] = event.event_id
            body["enterprise_id"] = tenant.enterprise_id
            region_api.start_service(service.service_region,
                                     tenant.tenant_name, service.service_alias,
                                     body)
            monitorhook.serviceMonitor(username, service, 'app_start', True)
            return 200, True, "success"
        except Exception as e:
            logger.exception("openapi.services", e)
            monitorhook.serviceMonitor(username, service, 'app_start', False)
            return 412, False, "启动失败"
示例#15
0
    def create_region_service(self,
                              newTenantService,
                              domain,
                              region,
                              nick_name,
                              do_deploy=True,
                              dep_sids=None):
        """创建region服务"""
        data = {}
        data["tenant_id"] = newTenantService.tenant_id
        data["service_id"] = newTenantService.service_id
        data["service_key"] = newTenantService.service_key
        data["comment"] = newTenantService.desc
        data["image_name"] = newTenantService.image
        data["container_cpu"] = newTenantService.min_cpu
        data["container_memory"] = newTenantService.min_memory
        data["volume_path"] = "vol" + newTenantService.service_id[0:10]
        data["volume_mount_path"] = newTenantService.volume_mount_path
        data["host_path"] = newTenantService.host_path
        data["extend_method"] = newTenantService.extend_method
        data["status"] = 0
        data["replicas"] = newTenantService.min_node
        data["service_alias"] = newTenantService.service_alias
        data["service_version"] = newTenantService.version
        data["container_env"] = newTenantService.env
        data["container_cmd"] = newTenantService.cmd
        data["node_label"] = ""
        data[
            "deploy_version"] = newTenantService.deploy_version if do_deploy else None
        data["domain"] = domain
        data["category"] = newTenantService.category
        data["operator"] = nick_name
        data["service_type"] = newTenantService.service_type
        data["extend_info"] = {"ports": [], "envs": []}
        data["namespace"] = newTenantService.namespace
        data["code_from"] = newTenantService.code_from
        data["dep_sids"] = dep_sids
        data["port_type"] = newTenantService.port_type
        data["ports_info"] = []
        data["envs_info"] = []
        data["volumes_info"] = []

        if hasattr(newTenantService, "service_origin"):
            data["service_origin"] = newTenantService.service_origin

        ports_info = TenantServicesPort.objects.filter(
            service_id=newTenantService.service_id).values(
                'container_port', 'mapping_port', 'protocol', 'port_alias',
                'is_inner_service', 'is_outer_service')
        if ports_info:
            data["ports_info"] = list(ports_info)

        envs_info = TenantServiceEnvVar.objects.filter(
            service_id=newTenantService.service_id).values(
                'container_port', 'name', 'attr_name', 'attr_value',
                'is_change', 'scope')
        if envs_info:
            data["envs_info"] = list(envs_info)

        volume_info = TenantServiceVolume.objects.filter(
            service_id=newTenantService.service_id).values(
                'service_id', 'category', 'host_path', 'volume_path')
        if volume_info:
            data["volumes_info"] = list(volume_info)

        # 创建操作
        event = ServiceEvent(event_id=make_uuid(),
                             service_id=newTenantService.service_id,
                             tenant_id=newTenantService.tenant_id,
                             type="create",
                             deploy_version=newTenantService.deploy_version
                             if do_deploy else None,
                             user_name=nick_name,
                             start_time=datetime.datetime.now())
        event.save()

        data["event_id"] = event.event_id
        logger.debug(newTenantService.tenant_id + " start create_service:" +
                     datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        tenant = Tenants.objects.get(tenant_id=newTenantService.tenant_id)
        data["enterprise_id"] = tenant.enterprise_id
        region_api.create_service(region, tenant.tenant_name, data)
        logger.debug(newTenantService.tenant_id + " end create_service:" +
                     datetime.datetime.now().strftime('%Y%m%d%H%M%S'))