Exemplo n.º 1
0
 def get(self, request):
     response = {}
     if request.user.has_perm('resources.view_idc'):
         idc_id = request.GET.get('id', None)
         if not idc_id:
             response['status'] = 1
             response['errmsg'] = 'idc ID 为空'
             return JsonResponse(response)
         try:
             idc = Idc.objects.filter(id=idc_id).values(
                 'id', 'name', 'full_name', 'address', 'phone', 'email',
                 'contact')
             response['status'] = 0
             response['idc_obj'] = list(idc)[0]
             GetLogger().get_logger().info('Get idc object success')
             return JsonResponse(response)
         except:
             GetLogger().get_logger().error(traceback.format_exc())
             response['status'] = 1
             response['errmsg'] = '查询出错'
             return JsonResponse(response)
     else:
         response['status'] = 1
         response['errmsg'] = '没有查询idc权限'
         return JsonResponse(response)
Exemplo n.º 2
0
    def get_db_by_cluster(self, master_host, master_port, master_user,
                          master_pass):
        list_db = []
        conn = None
        cursor = None

        try:
            conn = pymysql.connect(host=master_host,
                                   port=master_port,
                                   user=master_user,
                                   passwd=master_pass,
                                   charset='utf8mb4')
            cursor = conn.cursor()
            sql = 'show database'
            n = cursor.execute(sql)
            list_db = [
                row[0] for row in cursor.fetchall()
                if row[0] not in (('information_schema', 'performance_schema',
                                   'mysql', 'test', 'sys'))
            ]
        except pymysql.Warning as e:
            GetLogger().get_logger().error(e)
        except pymysql.Error as e:
            GetLogger().get_logger().error(e)
        finally:
            if cursor is not None:
                cursor.close()
            if conn is not None:
                conn.commit()
                conn.close()
        return list_db
Exemplo n.º 3
0
 def post(self, request):
     response = {}
     graphid = request.POST.get('graph_id')
     productid = request.POST.get('productid')
     try:
         product_obj = Product.objects.get(pk=productid)
         graph_obj = Graph.objects.get(pk=graphid)
     except:
         GetLogger().get_logger().error(traceback.format_exc())
         response['status'] = 1
         response['errmsg'] = '数据输入出错了,找不到对应模型'
         return JsonResponse(response)
     if product_obj.pid == 0:
         response['status'] = 1
         response['errmsg'] = '请选择次级业务线'
         return JsonResponse(response)
     try:
         #product_obj.graph_set.add(graph_obj)
         graph_obj.product.add(product_obj.id)
         graph_obj.save()
     except:
         GetLogger().get_logger().error(traceback.format_exc())
         response['status'] = 1
         response['errmsg'] = '添加关系出错了'
         return JsonResponse(response)
     response['status'] = 0
     return JsonResponse(response)
Exemplo n.º 4
0
    def get(self, request):
        ret = []
        servers = Server.objects.filter(
            server_purpose=request.GET.get('id', None))
        GetLogger().get_logger().info('服务器列表长度: {}'.format(len(servers)))
        for server in servers:
            data = {}
            data['hostname'] = server.hostname
            data['id'] = server.id

            if hasattr(server, 'zabbixhost'):
                GetLogger().get_logger().info('{}有监控'.format(server.hostname))
                data['monitor'] = True
                templates = Zabbix().get_templates(
                    hostids=server.zabbixhost.hostid)
                if templates:
                    data['templates_flag'] = True
                    data['templates'] = templates
                else:
                    data['templates_flag'] = False
            else:
                GetLogger().get_logger().info('{}没有监控'.format(server.hostname))
                data['monitor'] = False
            ret.append(data)
        return JsonResponse(ret, safe=False)
Exemplo n.º 5
0
 def get(self, request):
     ret = {'status': 0}
     try:
         cache_host()
     except Exception as e:
         GetLogger().get_logger().error('zabbix 同步失败')
     GetLogger().get_logger().info('zabbix 同步成功')
     return JsonResponse(ret)
Exemplo n.º 6
0
 def search(self, request):
     response = {}
     data = QueryDict(request.body)
     key_value = data.get('key', None)
     if not key_value:
         GetLogger().get_logger().error('搜索主机key_value为空')
     try:
         servers = Server.objects.filter(
             hostname__icontains=key_value).values('id', 'hostname')
     except Exception as e:
         GetLogger().get_logger().error('发生异常: {}'.format(e))
     servers = list(servers)
     return JsonResponse(servers, safe=False)
Exemplo n.º 7
0
 def get_context_data(self, **kwargs):
     context = super(GraphModifyView, self).get_context_data(**kwargs)
     graph_id = self.request.GET.get('graphid', None)
     try:
         graph_obj = Graph.objects.get(pk=graph_id)
     except:
         GetLogger().get_logger().error(traceback.format_exc())
     context['graph_obj'] = graph_obj
     try:
         cli = influxdbCli()
     except:
         GetLogger().get_logger().error(traceback.format_exc())
     context['measurements'] = cli.measurements
     return context
Exemplo n.º 8
0
 def patch(self, request):
     response = {}
     if request.user.has_perm('auth.change_permission'):
         permission_form = UpdatePermissionNameForm(QueryDict(request.body))
         if permission_form.is_valid():
             permission_name = permission_form.cleaned_data.get('name')
             permission_id = permission_form.cleaned_data.get('id')
             try:
                 permission_obj = Permission.objects.get(id=permission_id)
                 permission_obj.name = permission_name
                 permission_obj.save()
                 response['status'] = 0
                 return JsonResponse(response)
             except:
                 GetLogger().get_logger().error(traceback.format_exc())
                 response['status'] = 1
                 response['errmsg'] = '更改permission name 出错'
                 return JsonResponse(response)
         else:
             response['status'] = 1
             response['errmsg'] = '缺少数据'
             return JsonResponse(response)
     else:
         response['status'] = 1
         response['errmsg'] = '没有修改权限名的权限'
         return JsonResponse(response)
Exemplo n.º 9
0
 def _fetchall(self, sql, paramHost, paramPort, paramUser, paramPasswd,
               paramDb):
     '''
     封装mysql连接和获取结果集方法
     '''
     result = None
     conn = None
     cur = None
     try:
         conn = pymysql.connect(host=paramHost,
                                user=paramUser,
                                passwd=paramPasswd,
                                db=paramDb,
                                port=paramPort,
                                charset='utf8mb4')
         cur = conn.cursor()
         ret = cur.execute(sql)
         result = cur.fetchall()
     except pymysql.Error as e:
         GetLogger().get_logger().error("Mysql Error %d: %s" %
                                        (e.args[0], e.args[1]))
     finally:
         if cur is not None:
             cur.close()
         if conn is not None:
             conn.close()
     return result
Exemplo n.º 10
0
 def get(self, request):
     response = {}
     if request.user.has_perm('auth.view_group') and request.user.has_perm(
             'auth.view_user'):
         gid = request.GET.get('gid', None)
         if not gid:
             response['status'] = 1
             response['errmsg'] = 'gid不能为空'
             return JsonResponse(response)
         try:
             #查询用户组内成员
             #1
             group_obj = Group.objects.get(id=gid)
             members = group_obj.user_set.all()
             #2
             #User.objects.all().filter(用户组=组id)
             list_members = list(members.values('id', 'username'))
             response['status'] = 0
             response['list_members'] = list_members
             return JsonResponse(response)
         except:
             GetLogger().get_logger().error(traceback.format_exc())
             response['status'] = 1
             response['errmsg'] = '查找组成员错误'
             return JsonResponse(response)
     else:
         response['status'] = 1
         response['errmsg'] = '没有查看组内成员权限'
         return JsonResponse(response)
Exemplo n.º 11
0
 def delete(self, request):
     response = {'status': 0}
     if request.user.has_perm('auth.delete_group'):
         data = QueryDict(request.body)
         gid = data.get('gid', None)
         if not gid:
             response['status'] = 1
             response['errmsg'] = 'gid不能为空'
             return JsonResponse(response)
         group_obj = Group.objects.get(id=gid)
         if group_obj.user_set.all().count() > 0:
             response['status'] = 1
             response['errmsg'] = '不能删除,组内还有成员'
             return JsonResponse(response)
         if group_obj.permissions.all().count() > 0:
             response['status'] = 1
             response['errmsg'] = '不能删除,组内有赋权'
             return JsonResponse(response)
         try:
             group_obj.delete()
             response['status'] == 0
             return JsonResponse(response)
         except:
             GetLogger().get_logger().error(traceback.format_exc())
             response['status'] == 1
             response['errmsg'] == '删除组出错'
             return JsonResponse(response)
     else:
         response['status'] = 1
         response['errmsg'] = '没有删除用户组权限'
         return JsonResponse(response)
Exemplo n.º 12
0
 def post(self, request):
     response = {}
     if request.user.has_perm('auth.add_group'):
         group_name = request.POST.get('name', None)
         if not group_name:
             response['status'] = 1
             response['errmsg'] = '不能为空'
             return JsonResponse(response)
         try:
             group = Group(name=group_name)
             group.save()
             response['status'] = 0
             response['group_id'] = group.id
             response['group_name'] = group.name
         except IntegrityError:
             response['status'] = 1
             response['errmsg'] = '用户组以存在'
             GetLogger().get_logger().error(traceback.format_exc())
         except:
             response['status'] = 1
             response['errmsg'] = '添加用户组失败'
         return JsonResponse(response)
     else:
         response['status'] = 1
         response['errmsg'] = '没有添加用户组权限'
         return JsonResponse(response)
Exemplo n.º 13
0
    def delete(self, request):
        response = {'status': 0}
        if request.user.has_perm('auth.remove_user_from_group'):
            data = QueryDict(request.body)
            uid = data.get('uid', None)
            gid = data.get('gid', None)

            if not uid or not gid:
                response['status'] = 1
                response['errmsg'] = 'gid 或者 uid 为空'
                return JsonResponse(response)

            try:
                user_obj = User.objects.get(id=uid)
                group_obj = Group.objects.get(id=gid)
                user_obj.groups.remove(group_obj)
                #通过组删除用户
                #group_obj.user_set.remove(user_obj)
                return JsonResponse(response)

            except:
                GetLogger().get_logger().error(traceback.format_exc())
                response['status'] = 1
                response['errmsg'] = '删除组成员错误'
                return JsonResponse(response)
        else:
            response['status'] = 1
            response['errmsg'] = '没有移除用户的权限'
            return JsonResponse(response)
Exemplo n.º 14
0
def cache_host():
    #取出所有zabbix里的host信息
    zbhosts = process_zb_hosts(Zabbix().get_hosts())
    for host in zbhosts:
        #host数据格式
        #{'hostid': '10254', 'host': 'zabbix', 'ip': '192.168.1.1'}
        try:
            server_obj = Server.objects.get(inner_ip=host['ip'])
        except Server.DoesNotExist:
            GetLogger().get_logger().error('zabbix ip cmdb not exist')
        except Server.MultipleObjectsReturned:
            GetLogger().get_logger().error('ip cmdb more then once')
        else:
            host['server'] = server_obj
            zh = ZabbixHost(**host)
            zh.save()
Exemplo n.º 15
0
 def post(self, request):
     next_url = urlquote_plus(
         request.GET.get('next', None) if request.GET.
         get('next', None) else reverse('influx_graph_list'))
     form = UpdateGraphForm(request.POST)
     if form.is_valid():
         try:
             graph_id = form.cleaned_data.get('id')
             graph_obj = Graph.objects.get(pk=graph_id)
             graph_obj.title = form.cleaned_data.get('title')
             graph_obj.subtitle = form.cleaned_data.get('subtitle')
             graph_obj.unit = form.cleaned_data.get('unit')
             graph_obj.measurement = form.cleaned_data.get('measurement')
             graph_obj.auto_hostname = form.cleaned_data.get(
                 'auto_hostname')
             graph_obj.field_expression = form.cleaned_data.get(
                 'field_expression')
             graph_obj.tooltip_formatter = form.cleaned_data.get(
                 'tooltip_formatter')
             graph_obj.yaxis_formatter = form.cleaned_data.get(
                 'yaxis_formatter')
             graph_obj.save()
             return redirect('success', next=next_url)
         except Exception as e:
             GetLogger().get_logger().error(traceback.format_exc())
             return redirect('error', next=next_url, msg=e.args)
     else:
         return redirect('error', next=next_url, msg=form.errors.as_json())
Exemplo n.º 16
0
def _create_host(hostname, ip, group, template, port="10050"):
    params = {

        'host': hostname,
        'interfaces': [
            {
                'dns': '',
                'ip': ip,
                'main': 1,
                'port': port,
                'type': 1,
                'useip': 1
             }
        ],
        'groups': group,
        'templates': template
    }
    #print(params)
    try:
        ret = Zabbix().create_host(params)
        GetLogger().get_logger().info("创建zabbix host 完成:{}".format(json.dumps(ret)))
        if "hostids" in ret:
            return ret["hostids"][0]
        else:
            raise Exception(ret["hostids"][0])
    except Exception as e:
        raise Exception(e.args[0])
Exemplo n.º 17
0
 def get_args(self):
     productid = self.request.GET.get('product', None)
     try:
         return {'productid': int(productid)}
     except:
         GetLogger().get_logger().error(traceback.format_exc())
         return {}
Exemplo n.º 18
0
 def get_context_data(self, **kwargs):
     context = super(CreateGrapView, self).get_context_data(**kwargs)
     try:
         cli = influxdbCli()
         context['measurements'] = cli.measurements
     except:
         GetLogger().get_logger().error(traceback.format_exc())
     return context
Exemplo n.º 19
0
 def get(self, request):
     productid = request.GET.get('id', None)
     if productid:
         try:
             graphs = Graph.objects.exclude(product__id=productid).values(
                 'id', 'title')
         except:
             GetLogger().get_logger().error(traceback.format_exc())
     return JsonResponse(list(graphs), safe=False)
Exemplo n.º 20
0
 def get(self, request):
     sid = request.GET.get('sid', None)
     server_status_objs = ServerStatus.objects.all()
     try:
         server_obj = Server.objects.get(pk=sid)
     except Server.DoesNotExist:
         GetLogger().get_logger().error('%s' % traceback.format_exc())
     return JsonResponse(list(server_status_objs.values('id', 'name')),
                         safe=False)
Exemplo n.º 21
0
 def __init__(self):
     try:
         self.inception_host = settings.INCEPTION_HOST
         self.inception_port = int(settings.INCEPTION_PORT)
         self.inception_remote_backup_host = settings.INCEPTION_REMOTE_BACKUP_HOST
         self.inception_remote_backup_port = int(
             settings.INCEPTION_REMOTE_BACKUP_PORT)
         self.inception_remote_backup_user = settings.INCEPTION_REMOTE_BACKUP_USER
         self.inception_remote_backup_user = settings.INCEPTION_REMOTE_BACKUP_PASSWORD
     except:
         GetLogger().get_logger().error(traceback.format_exc())
Exemplo n.º 22
0
def process_zb_hosts(zbhosts):
    ret = []
    ip_list = []
    #拿到的数据
    # {'hostid': '10254', 'host': 'zabbix', 'interfaces': [{'ip': '192.168.1.2'}]}
    #整理以后的数据
    # {'hostid': '10254', 'host': 'zabbix', 'ip': '192.168.1.1'}
    for host in zbhosts:
        try:
            ip = host['interfaces'][0]['ip']
        except:
            GetLogger().get_logger().error(traceback.format_exc())
        del host['interfaces']
        host['ip'] = ip
        ret.append(host)
        if ip in ip_list:
            GetLogger().get_logger().error('ip 重复')
        else:
            ip_list.append(ip)
    return ret
Exemplo n.º 23
0
 def patch(self, request):
     response = {'status': 0}
     data = QueryDict(request.body)
     sid = data.get('sid', None)
     ssid = data.get('ssid', None)
     try:
         server_obj = Server.objects.get(pk=sid)
         GetLogger().get_logger().info('patch1 ok')
     except Server.DoesNotExist:
         response['status'] = 1
         response['errmsg'] = '服务器不存在'
         GetLogger().get_logger().error('%s' % traceback.format_exc())
         return JsonResponse(response)
     try:
         server_status_obj = ServerStatus.objects.get(pk=ssid)
         GetLogger().get_logger().info('patch2 ok')
     except ServerStatus.DoesNotExist:
         response['status'] = 1
         response['errmsg'] = '服务器状态不存在'
         GetLogger().get_logger().error('%s' % traceback.format_exc())
         return JsonResponse(response)
     try:
         server_obj.status = server_status_obj
         server_obj.save()
         GetLogger().get_logger().info('patch3 ok')
     except:
         response['status'] = 1
         response['errmsg'] = '更改服务器状态出错'
         GetLogger().get_logger().error('%s' % traceback.format_exc())
         return JsonResponse(response)
     return JsonResponse(response)
Exemplo n.º 24
0
 def post(self, request):
     response = {}
     product_form = ModifyProductForm(request.POST)
     if product_form.is_valid():
         try:
             pid = product_form.cleaned_data.get('id')
             product_obj = Product.objects.get(pk=pid)
             product_obj.service_name = product_form.cleaned_data.get('service_name')
             product_obj.module_letter = product_form.cleaned_data.get('module_letter')
             product_obj.dev_interface = product_form.cleaned_data.get('dev_interface')
             product_obj.op_interface = product_form.cleaned_data.get('op_interface')
             product_obj.save()
             response['status'] = 0
         except Exception as e:
             GetLogger().get_logger().error('修改业务线出错: {}'.format(e))
             response['status'] = 1
             response['errmsg'] = '修改业务线出错'
     else:
         GetLogger().get_logger().error('数据验证错误')
         response['status'] = 1
         response['errmsg'] = '数据验证错误'
     return JsonResponse(response)
Exemplo n.º 25
0
    def get(self, request):
        #数据请求格式 graph_id=7 & graph_time=30m &product_id=1
        ret = {"status": 0}
        graph_id = request.GET.get("graph_id", None)
        graph_time = request.GET.get("graph_time", None)
        product_id = request.GET.get("product_id", None)

        try:
            graph_obj = Graph.objects.get(pk=graph_id)
        except:
            GetLogger().get_logger().error(traceback.format_exc())
            ret['status'] = 1
            ret['errmsg'] = "graph 不存在"
            return JsonResponse(ret)

        try:
            product_obj = Product.objects.get(pk=product_id)
            if product_obj.pid == 0:
                ret['status'] = 1
                ret['errmsg'] = "顶级业务线没有图形"
                return JsonResponse(ret)
        except:
            GetLogger().get_logger().error(traceback.format_exc())
            ret['status'] = 1
            ret['errmsg'] = '业务线异常'
            return JsonResponse(ret)

        client = influxdbCli()
        client.hostnames = [
            s["hostname"] for s in Server.objects.filter(
                server_purpose__exact=product_obj.id).values('hostname')
        ]
        client.graph_obj = graph_obj
        client.graph_time = graph_time

        client.query()
        ret['series'] = client.series
        ret['categories'] = client.categories
        return JsonResponse(ret, safe=False)
Exemplo n.º 26
0
 def post(self, request):
     product_form = AddProductForm(request.POST)
     if product_form.is_valid():
         product = Product(**product_form.cleaned_data)
         try:
             product.save()
             return redirect("success", next="product_manage")
         except Exception as e:
             GetLogger().get_logger().error(traceback.format_ext())
             return redirect("error", next="product_manage", msg=e.args)
     else:
         return redirect("error", next="product_manage",
                         msg=json.dumps(json.loads(product_form.errors.as_json()), ensure_ascii=False))
Exemplo n.º 27
0
    def post(self, request):
        next_url = request.GET.get("next", None) if request.GET.get(
            'next', None) else 'server_list'
        server_id = request.POST.get('id', None)
        service_id = request.POST.get('service_id', None)
        server_purpose = request.POST.get('server_purpose', None)
        try:
            server_obj = Server.objects.get(pk=server_id)
            product_service_id = Product.objects.get(pk=service_id)
            product_server_purpose = Product.objects.get(pk=server_purpose)
            GetLogger().get_logger().info('ServerModifyProductView ok')
        except:
            GetLogger().get_logger().error('%s' % traceback.format_exc())
            return redirect("error", next="server_list", msg="传参错误")

        if product_server_purpose.pid != product_service_id.id:
            return Http404
        server_obj.service_id = product_service_id.id
        server_obj.server_purpose = product_server_purpose.id
        server_obj.save(update_fields=["service_id", "server_purpose"])
        return redirect(
            reverse("success", kwargs={"next": urlquote_plus(next_url)}))
Exemplo n.º 28
0
def ServerInfoAutoReport(request):
    if request.method == "POST":
        data = request.POST.dict()
        data['check_update_time'] = datetime.datetime.now()
        try:
            Server.objects.get(uuid__exact=data['uuid'])
            Server.objects.filter(uuid=data['uuid']).update(**data)
            '''
            s.hostname = data['hostanme']
            s.check_update_time = datatime.now()
            s.save(update_fields=['hostname'])
            '''
            GetLogger().get_logger().info('ServerInfoAutoReport ok')
        except Server.DoesNotExist:
            s = Server(**data)
            server_status_obj = ServerStatus.objects.get(pk=1)
            s.status = server_status_obj
            s.save()
            GetLogger().get_logger().error('%s' % traceback.format_exc())
        return HttpResponse("success")
    else:
        return HttpResponse("method error")
Exemplo n.º 29
0
 def delete(self, request):
     response = {}
     data = QueryDict(request.body)
     graphid = data.get('graph_id', None)
     productid = data.get('productid', None)
     try:
         product_obj = Product.objects.get(pk=productid)
         graph_obj = Graph.objects.get(pk=graphid)
     except:
         GetLogger().get_logger().error(traceback.format_exc())
         response['status'] = 1
         response['errmsg'] = '数据输入错误,找不到对应模型'
         return JsonResponse(response)
     try:
         graph_obj.product.remove(product_obj.id)
         graph_obj.save()
     except:
         GetLogger().get_logger().error(traceback.format_exc())
         response['status'] = 1
         response['errmsg'] = '移除关系出错'
         return JsonResponse(response)
     response['status'] = 0
     return JsonResponse(response)
Exemplo n.º 30
0
 def post(self, request):
     #print(request.POST)
     #print(reverse("success", kwargs={"next": "user_list"}))
     add_idc_form = request.POST.copy()
     add_idc_form.pop('csrfmiddlewaretoken')
     add_idc_dict = add_idc_form.dict()
     try:
         idc = Idc(**add_idc_dict)
         idc.save()
         return redirect("success", next="idc_list")
     except:
         GetLogger().get_logger().error(traceback.format_exc())
         errmsg = '添加idc信息错误'
         return redirect("error", next="idc_add", msg=errmsg)