# -*- coding: utf-8 -*-
'''
此job的目的用于比对
对比cmdb和zeus中的数据
'''
from application import db
from models.host import Host
from models.host_ip import HostIp
from models.device import Device
from models.device_ip import DeviceIp
from models.ip_address import IpAddress
from config import MIGRATE_DATABSE_URI
from sqlalchemy import *
import subprocess
import re

class Compare_cmdb_zeus:
    def run(self):
        print "==========start========="
        cmdbinfo = self.get_cmdbinfo()
        zeusinfo = self.get_zeusinfo()
        notinzeus = []
        nocmdbenough = {}
        nozuesenough = {}
        #compare
        if zeusinfo and  cmdbinfo:
            zeuskeys = zeusinfo.keys()
            for hostname,ips in cmdbinfo.items():
                if hostname in zeuskeys:
                    zeusips = zeusinfo[hostname]
                    for ip in ips:
                        if ip not in zeusips:
                            if hostname not in nocmdbenough.keys():
                                nocmdbenough[hostname] = []
                            nocmdbenough[hostname].append(ip)
                    for ip in zeusips:
                        if ip not in ips:
                            if hostname not in nozuesenough.keys():
                                nozuesenough[hostname] = []
                            nozuesenough[hostname].append(ip)
                else:
                    notinzeus.append(hostname)
        print '----------noenough:cmdb ip not in zeus ip----------'
        print nocmdbenough
        print '----------noenough:zeus ip not in cmdb ip----------'
        print nozuesenough
        print '----------not in zeus----------'
        print notinzeus
        print "==========end========="

    def run2(self):
        print "==========start========="
        self.hostname_ip()
        print "==========end========="



    def get_cmdbinfo(self):
        cmdbinfo={}
        hostinfo=Host.query.filter(Host.deleted == 0).all()
        if hostinfo:
            for host in hostinfo:
                hostname = host.hostname.lower()
                ip_ids = []
                ips = []
                if host.primary_ip_id > 0 :
                   ip_ids.append(host.primary_ip_id)
                if host.is_virtual == 0:
                    device_id = host.device_id
                    device_ips = DeviceIp.query.filter(and_(DeviceIp.device_id == device_id,DeviceIp.net_name_id == 0)).first()
                    if device_ips:
                        ip_ids.append(device_ips.ip_address_id)
                ipsinfo = HostIp.query.filter(HostIp.host_id == host.id).all()
                if ipsinfo:
                    for tmp_host_ip in ipsinfo:
                        if tmp_host_ip.ip_address_id not in ip_ids:
                            ip_ids.append(tmp_host_ip.ip_address_id)
                if ip_ids:
                    ipv4info = IpAddress.query.filter(IpAddress.id.in_(ip_ids)).all()
                    if ipv4info:
                        for tmp_ipv4 in ipv4info:
                            ips.append(tmp_ipv4.ipv4)
                hostname = hostname.lower()
                cmdbinfo[hostname] = ips

        return cmdbinfo



    def get_zeusinfo(self):
        zeusinfo={}
        engine = create_engine(MIGRATE_DATABSE_URI, encoding='utf-8',echo=False)
        connection = engine.connect()
        sql= "select id, label from `item` where type_id in (2,6)"
        hosts=connection.execute(sql).fetchall()
        if hosts:
            for host in hosts:
                hostname = host['label']
                ips = []
                if not hostname:
                    tmpsql="selet app_name from hosts where item_id = %d" %host['id']
                    tmphostsinfo=connection.execute(tmpsql).fetchone()
                    if tmphostsinfo:
                        hostname = tmphostsinfo['app_name']
                id = host['id']
                ipsql = "select ipv4 from network where item_id = %s"%id
                ipv4info = connection.execute(ipsql).fetchall()
                if ipv4info:
                    for tmp_ipv4 in ipv4info:
                        ips.append(tmp_ipv4['ipv4'])
                hostname = hostname.lower()
                zeusinfo[hostname] = ips

        #print zeusinfo['img20-002']
        return zeusinfo



    def hostname_ip(self):
        cmdbinfo=self.get_cmdbinfo()
        deadinfo = []
        rackinfo = {}
        if cmdbinfo:
            for hostname,ips in cmdbinfo.items():
                pingaling = subprocess.Popen(["ping","-q", "-c 1", "-r", hostname], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
                line = pingaling.stdout.readline()
                ip=re.findall(r'\d+.\d+.\d+.\d+', line)
                if ip:
                    ip = ip[0]
                    if ip not in ips:
                       rackinfo[hostname] = ip
                else:
                    deadinfo.append(hostname)

        print '---------deadinfo---------'
        print deadinfo
        print '---------rackinfo---------'
        print rackinfo