#!/usr/bin/env python

from jsonrpclib import Server 
import json
import requests 
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
import cvp

# CVP info
CVP_HOST = '127.0.0.1'
CVP_USER = 'cvpadmin'
CVP_PASSWD = 'arista'

# EAPI info
EAPI_TRANSPORT = 'http'
EAPI_USER = CVP_USER
EAPI_PASSWD = CVP_PASSWD

server = cvp.Cvp(CVP_HOST)
server.authenticate(CVP_USER, CVP_PASSWD)

nodes = {}
links = {}
topology = {'nodes':nodes, 'links':links}

linknames = {}

def getInfo(name,ip):
  eapi = Server('%s://%s:%s@%s/command-api' % (EAPI_TRANSPORT, EAPI_USER, EAPI_PASSWD, ip))

  commands = [
    'enable',
    'show lldp neighbors',
    'show hostname',
    'show snmp mib ifmib ifindex',
    'show sflow'
  ]
  response = eapi.runCmds(1, commands, 'json')

  lldp = response[1]['lldpNeighbors']
  hostname = response[2]['hostname']
  ifIndexes = response[3]['ifIndex']
  agentAddr = response[4]['ipv4Sources'][0]['ipv4Address']

  dev = {}
  nodes[hostname] = dev
  dev['agent'] = agentAddr
  ports = {}
  dev['ports'] = ports

  for p in ifIndexes:
    ports[p] = {'ifindex':ifIndexes[p]}

  for n in lldp:
    if '%s %s' % (hostname,n['port']) < '%s %s' % (n['neighborDevice'],n['neighborPort']):
      lname = '%s %s -> %s %s' % (hostname,n['port'],n['neighborDevice'],n['neighborPort'])
      if linknames.get(lname) == None:
        linknames[lname] = {'node1':hostname,'port1':n['port'],'node2':n['neighborDevice'],'port2':n['neighborPort']}
    else:
      lname = '%s %s -> %s %s' % (n['neighborDevice'],n['neighborPort'],hostname,n['port'])
      if linknames.get(lname) == None:
        linknames[lname] = {'node1':n['neighborDevice'],'port1':n['neighborPort'],'node2':hostname,'port2':n['port']}

def getInternalLinks():
  linkno = 1
  for n in linknames:
    entry = linknames[n]
    if nodes.get(entry['node1']) != None and nodes.get(entry['node2']) != None:
      links['L%s' % linkno] = entry
      linkno = linkno + 1

devicelist = server.getDevices()
for device in devicelist:
  try:
    getInfo(device.fqdn,device.ipAddress)
  except:
    print 'Exception while connecting to %s' % device.fqdn 

getInternalLinks()
requests.put('http://127.0.0.1:8008/app/fabric-view/scripts/fabric-view.js/topology/json',json=topology)
