Beispiel #1
0
    def post(self, request, format=None):
        reason = "ok"
        raw_data = json.loads(request.data)
        need_params = ('host', 'port')
        try:
            source_ip = get_ip(request)
            for param in need_params:
                if raw_data.get(param, None) is None:
                    raise Exception("%s: 参数没有" % (param))

            myins = MysqlInstance.objects.get(host=raw_data.get('host'), port=raw_data.get('port'))
            # 删除记录
            MyqlHistoryRecord.objects.filter(mysql=myins).update(**{'remark': myins.host + ':' + myins.port})
            MyqlHistoryRecord.objects.create(create_user=request.user, type=3, remark=myins.host + ':' + myins.port,
                                             source_ip=source_ip)

            myins.delete()
            reason = 'delete ok'
            resp = 1

        except MysqlInstance.DoesNotExist:
            reason = '没有找到mysql实例'
            resp = 13
        except Exception as e:
            reason = str(e)
            resp = 13
        return JsonResponse({"reason": reason, "resp": resp})
Beispiel #2
0
    def post(self, request, format=None):
        reason = "ok"
        raw_data = json.loads(request.data)
        need_params = ('project', 'area', 'purpose', 'host', 'port', 'user', 'password')
        try:
            for param in need_params:
                if raw_data.get(param, None) is None:
                    raise Exception("%s: 参数没有" % (param))

            project = GameProject.objects.get(project_name_en=raw_data.get('project'))
            area = raw_data.get('area')
            cmdb_area = Area.objects.get(Q(chinese_name=area) | Q(short_name=area))
            purpose = raw_data.get('purpose')
            host = raw_data.get('host')
            port = raw_data.get('port')
            user = raw_data.get('user')
            password = raw_data.get('password')

            white_list = raw_data.get('white_list', None)

            if white_list is not None:
                if not isinstance(white_list, list):
                    raise Exception('white_list格式需要为list')

                white_list = json.dumps(white_list)

            myins = MysqlInstance.objects.create(
                project=project, area=area, purpose=purpose, white_list=white_list,
                host=host, port=port, user=user, password=password, cmdb_area=cmdb_area)
            reason = myins.show_api()
            resp = 1
            # 新增记录
            source_ip = get_ip(request)
            MyqlHistoryRecord.objects.create(mysql=myins, create_user=request.user, type=1, source_ip=source_ip)

        except Area.DoesNotExist:
            reason = '地区不存在,必须使用cmdb地区表中地区'
            resp = 13
        except GameProject.DoesNotExist:
            reason = '项目英文名不存在'
            resp = 13
        except Exception as e:
            reason = str(e)
            resp = 13
        return JsonResponse({"reason": reason, "resp": resp})
Beispiel #3
0
    def post(self, request, format=None):
        reason = "ok"
        resp = 0
        log = CleanUserLog()

        data = json.loads(request.data)
        source_ip = get_ip(request)
        log.logger.info('收到回调: ' + json.dumps(data) + ',源IP: ' + source_ip)
        username = data.pop('username', '')

        try:
            with transaction.atomic():
                user = User.objects.select_for_update().get(
                    first_name=username)
                # profile = user.profile
                ucs = UserClearStatus.objects.select_for_update().get(
                    profile=user.profile)
                server_permission = json.loads(ucs.server_permission)
                server_permission.update(**data)
                ucs.server_permission = json.dumps(server_permission)
                ucs.save(update_fields=['server_permission'])
                # 刷新页面
            ws_notify_clean_user(user.id)

        except User.DoesNotExist:
            log.logger.error('%s用户不存在' % (username))
            resp = 1
            reason = "用户%s不存在" % (username)
            log.logger.info("用户%s不存在" % (username))
        except UserClearStatus.DoesNotExist:
            log.logger.error('用户%s清除状态不存在,没有创建' % (username))
            reason = "用户%s清除状态不存在,没有创建" % (username)
            resp = 1
            log.logger.info("用户%s清除状态不存在,没有创建" % (username))
        except Exception as e:
            reason = str(e)
            resp = 1
            log.logger.info('管理机清除用户%s后回调cmdb失败' % (username, str(e)))
        return JsonResponse({"resp": resp, "reason": reason})
Beispiel #4
0
    def post(self, request, format=None):
        reason = "ok"
        raw_data = json.loads(request.data)
        # need_params = ('old_instance', 'new_instance')

        try:
            source_ip = get_ip(request)
            if raw_data.get('old_instance', None) is None:
                raise Exception('old_instance查询参数没有')
            if raw_data.get('new_instance', None) is None:
                raise Exception('new_instance修改参数没有')

            old_instance = raw_data.get('old_instance')
            new_instance = raw_data.get('new_instance')

            myins = MysqlInstance.objects.get(**old_instance)

            update_fields = ('project', 'area', 'purpose', 'host', 'port', 'user', 'password', 'white_list')
            update_data = {}

            for f in update_fields:
                field_data = new_instance.get(f, None)
                if field_data is not None:
                    if f == 'project':
                        field_data = GameProject.objects.get(project_name_en=field_data)
                        update_data[f] = field_data
                    elif f == 'white_list':
                        if not isinstance(field_data, list):
                            raise Exception('white_list格式需要为list')
                        update_data[f] = json.dumps(field_data)
                    elif f == 'area':
                        area = Area.objects.get(Q(chinese_name=field_data) | Q(short_name=field_data))
                        update_data['cmdb_area'] = area
                    else:
                        update_data[f] = field_data
                else:
                    if f == 'white_list':
                        update_data[f] = None

            for attr, value in update_data.items():
                old_content = myins.__getattribute__(attr)
                setattr(myins, attr, value)
                # 修改记录
                if attr == 'white_list' and value is None:
                    continue
                alter_field = MysqlInstance._meta.get_field(attr).help_text
                if attr == 'password':
                    old_content = value = ''
                MyqlHistoryRecord.objects.create(mysql=myins, create_user=request.user, type=2,
                                                 old_content=old_content, new_content=value, alter_field=alter_field,
                                                 source_ip=source_ip)
            myins.save()

            reason = myins.show_api()

            resp = 1

        except Area.DoesNotExist:
            reason = '地区不存在,必须使用cmdb地区表中地区'
            resp = 13
        except MysqlInstance.DoesNotExist:
            reason = '找不到mysql实例'
            resp = 13
        except GameProject.DoesNotExist:
            reason = '项目英文名不存在'
            resp = 13
        except MultipleObjectsReturned:
            reason = 'old_instance找到的记录不唯一'
            resp = 13
        except Exception as e:
            reason = str(e)
            resp = 13
        return JsonResponse({"reason": reason, "resp": resp})
Beispiel #5
0
def create_txcloud_mysql(request):
    """创建云数据库实例mysql"""
    if request.method == 'POST':
        success = True
        data = ''
        password = ''
        port = ''
        try:
            if request.user not in get_cloud_platform_administrator():
                raise Exception('权限受限')
            raw_data = json.loads(request.body.decode('utf-8'))
            cmdb_project = raw_data.pop('cmdb_project')
            project_obj = GameProject.objects.get(pk=cmdb_project)
            cloud_account = project_obj.cloud_account
            area = raw_data.pop('area')
            area_obj = Area.objects.get(pk=area)
            purpose = raw_data.pop('purpose')
            pay_type = raw_data.pop('pay_type')
            if pay_type == 'PRE_PAID':
                action = 'CreateDBInstance'
            elif pay_type == 'HOUR_PAID':
                action = 'CreateDBInstanceHour'
                raw_data.pop('Period')
            else:
                raise Exception('未知的计费类型')
            region = raw_data.pop('region')
            is_init = raw_data.pop('is_init', '0')

            if is_init == '1':
                # 增加初始化参数
                password = gen_password()
                raw_data['Password'] = password
                lower_case_table_names = raw_data.pop('lower_case_table_names')
                character_set_server = raw_data.pop('character_set_server')
                raw_data['ParamList'] = {
                    'lower_case_table_names': lower_case_table_names,
                    'character_set_server': character_set_server
                }
                port = raw_data.get('Port')
            else:
                raw_data.pop('Port')

            version = '2017-03-20'
            host = 'cdb.tencentcloudapi.com'
            service = 'cdb'
            if PRODUCTION_ENV:
                obj = TXCloudTC3(cloud_account.secret_id,
                                 cloud_account.secret_key,
                                 version=version,
                                 region=region,
                                 action=action,
                                 params=raw_data,
                                 host=host,
                                 service=service)
                success, data = obj.python_request()
            else:
                data = ['cdb-pxdvxhnk']
            if success:
                # 插入数据库实例列表
                tx_region, created = Region.objects.get_or_create(code=region,
                                                                  defaults={
                                                                      'code':
                                                                      region,
                                                                      'city':
                                                                      '',
                                                                      'region':
                                                                      ''
                                                                  })
                for i in data:
                    mysql = MysqlInstance.objects.create(
                        project=project_obj,
                        area=area_obj.chinese_name,
                        purpose=purpose,
                        port=port,
                        user='******',
                        password=password,
                        cmdb_area=area_obj,
                        instance_id=i,
                        status=0,
                        open_wan=0,
                        tx_region=tx_region)
                    # 新增记录
                    source_ip = get_ip(request)
                    MyqlHistoryRecord.objects.create(mysql=mysql,
                                                     create_user=request.user,
                                                     type=1,
                                                     source_ip=source_ip)
                    # 查询实例状态
                    query_mysql_info.delay(region, cloud_account.secret_id,
                                           cloud_account.secret_key,
                                           cloud_account.__str__(), [i])
            else:
                raise Exception(data)

        except Exception as e:
            success = False
            data = str(e)
        finally:
            return JsonResponse({'success': success, 'data': data})