Merge pull request #118 from spotify/base_new_methods

Base new methods
This commit is contained in:
David Barroso committed 2015-12-15 15:51:21 +01:00
commit 6bcdce8d43
14 files changed
+367 -266

No files matched your search

+103 -22
View File
@@ -12,14 +12,11 @@
# License for the specific language governing permissions and limitations under
# the License.
import re
from pyFG.fortios import FortiOS, FortiConfig, logger
from pyFG.exceptions import FailedCommit, CommandExecutionException
from base import NetworkDriver
from exceptions import ReplaceConfigException, MergeConfigException
from utils.string_parsers import colon_separated_string_to_dict, convert_uptime_string_seconds
from napalm.utils.string_parsers import colon_separated_string_to_dict, convert_uptime_string_seconds
def execute_get(device, cmd, separator=':', auto=False):
@@ -174,12 +171,13 @@ class FortiOSDriver(NetworkDriver):
return interface_statistics
def get_bgp_neighbors(self):
@staticmethod
def _search_line_in_lines(search, lines):
for l in lines:
if search in l:
return l
def search_line_in_lines(search, lines):
for l in lines:
if search in l:
return l
def get_bgp_neighbors(self):
families = ['ipv4', 'ipv6']
terms = dict({'accepted_prefixes': 'accepted', 'sent_prefixes': 'announced'})
@@ -224,7 +222,7 @@ class FortiOSDriver(NetworkDriver):
block = detail_output[x:]
for term, fortiname in terms.iteritems():
text = search_line_in_lines('%s prefixes' % fortiname, block)
text = self._search_line_in_lines('%s prefixes' % fortiname, block)
t = [int(s) for s in text.split() if s.isdigit()][0]
neighbor_dict['address_family'][family][term] = t
@@ -258,27 +256,110 @@ class FortiOSDriver(NetworkDriver):
elif (data[1].startswith('RX packets') or data[1].startswith('TX packets')) and if_name:
if_data = data[1].split(' ')
direction = if_data[0].lower()
interface_counters[if_name][direction + '_unicast_packets'] = if_data[1].split(':')[1]
interface_counters[if_name][direction + '_errors'] = if_data[2].split(':')[1]
interface_counters[if_name][direction + '_discards'] = if_data[2].split(':')[1]
interface_counters[if_name][direction + '_unicast_packets'] = int(if_data[1].split(':')[1])
interface_counters[if_name][direction + '_errors'] = int(if_data[2].split(':')[1])
interface_counters[if_name][direction + '_discards'] = int(if_data[2].split(':')[1])
interface_counters[if_name][direction + '_multicast_packets'] = -1
interface_counters[if_name][direction + '_broadcast_packets'] = -1
elif data[1].startswith('RX bytes'):
if_data = data[1].split(' ')
interface_counters[if_name]['rx_octets'] = if_data[1].split(':')[1]
interface_counters[if_name]['rx_octets'] = int(if_data[1].split(':')[1])
try:
interface_counters[if_name]['tx_octets'] = if_data[6].split(':')[1]
interface_counters[if_name]['tx_octets'] = int(if_data[6].split(':')[1])
except IndexError:
interface_counters[if_name]['tx_octets'] = if_data[7].split(':')[1]
interface_counters[if_name]['tx_octets'] = int(if_data[7].split(':')[1])
return interface_counters
def get_lldp_neighbors(self):
return {}
def get_environment(self):
# def get_environment(self):
# sensors_output = self.device.execute_command('execute sensor list')
# from pprint import pprint
# pprint(sensors_output)
#
# return {}
def parse_string(line):
return re.sub(' +', ' ', line.lower())
def search_disabled(line):
m = re.search("(.+?) (.+?) alarm=(.+?) \(scanning disabled\)", line)
return m.group(2)
def search_normal(line):
m = re.search("(.+?) (.+?) alarm=(.+?) value=(.+?) threshold_status=(.+?)", line)
return m
def get_fans(fan_lines):
output = dict()
for fan_line in fan_lines:
if 'disabled' in fan_line:
name = search_disabled(fan_line)
output[name] = dict(status=False)
continue
m = search_normal(fan_line)
output[m.group(2)] = dict(status=True)
return output
def get_cpu(cpu_lines):
output = dict()
for l in cpu_lines:
m = re.search('(.+?) states: (.+?)% user (.+?)% system (.+?)% nice (.+?)% idle', l)
cpuname = m.group(1)
idle = m.group(5)
output[cpuname] = {
'%usage': 100.0 - int(idle)
}
return output
def get_memory(memory_line):
total, used = int(memory_line[1]) >> 20, int(memory_line[2]) >> 20 # convert from byte to MB
return dict(available_ram=total, used_ram=used)
def get_temperature(temperature_lines, detail_block):
output = dict()
for temp_line in temperature_lines:
if 'disabled' in temp_line:
sensor_name = search_disabled(temp_line)
output[sensor_name] = {'is_alert': False, 'is_critical': False, 'temperature': 0.0}
continue
m = search_normal(temp_line)
sensor_name, temp_value, status = m.group(2), m.group(4), int(m.group(5))
is_alert = True if status == 1 else False
# find block
fullline = self._search_line_in_lines(sensor_name, detail_block)
index_line = detail_block.index(fullline)
sensor_block = detail_block[index_line:]
v = int(self._search_line_in_lines('upper_non_recoverable', sensor_block).split('=')[1])
output[sensor_name] = dict(temperature=float(temp_value), is_alert=is_alert,
is_critical=True if v > temp_value else False)
return output
out = dict()
sensors_block = [parse_string(x) for x in self.device.execute_command('execute sensor detail') if x]
# temp
temp_lines = [x for x in sensors_block if any([True for y in ['dts', 'temp', 'adt7490'] if y in x])]
out['temperature'] = get_temperature(temp_lines, sensors_block)
# fans
out['fans'] = get_fans([x for x in sensors_block if 'fan' in x and 'temp' not in x])
# cpu
out['cpu'] = get_cpu(
[x for x in self.device.execute_command('get system performance status | grep CPU')[1:] if x])
# memory
memory_command = 'diag hard sys mem | grep Mem:'
t = [x for x in re.split('\s+', self.device.execute_command(memory_command)[0]) if x]
out['memory'] = get_memory(t)
# power, not implemented
sensors = [x.split()[1] for x in sensors_block if x.split()[0].isdigit()]
psus = {x for x in sensors if x.startswith('ps')}
out['power'] = {t: {'status': True, 'capacity': -1.0, 'output': -1.0} for t in psus}
return out
+3 -4
View File
@@ -20,7 +20,6 @@ from pyFG.fortios import FortiConfig
class TestConfigFortiOSDriver(unittest.TestCase, TestConfigNetworkDriver):
@classmethod
def setUpClass(cls):
hostname = '192.168.76.13'
@@ -33,7 +32,6 @@ class TestConfigFortiOSDriver(unittest.TestCase, TestConfigNetworkDriver):
class TestGetterFortiOSDriver(unittest.TestCase, TestGettersNetworkDriver):
@classmethod
def setUpClass(cls):
cls.mock = True
@@ -58,9 +56,10 @@ class FakeFortiOSDevice:
return data_file.read().splitlines()
def execute_command(self, command):
return self.read_txt_file('fortios/mock_data/{}.txt'.format(command.replace(' ', '_')))
return self.read_txt_file(
'fortios/mock_data/{}.txt'.format(command.replace(' ', '_').replace('|', '').replace(':', '')))
def load_config(self, config_block):
self.running_config = FortiConfig('running')
self.running_config.parse_config_output(self.read_txt_file('fortios/mock_data/{}.txt'.format(
config_block.replace(' ', '_'))))
config_block.replace(' ', '_'))))
@@ -0,0 +1 @@
Mem: 8349081600 1204281344 7144800256 0 137478144 329146368 102465536
@@ -0,0 +1,255 @@
1 P1V8_SFR_V alarm=0 value=1.8135 threshold_status=0
type=2/1
upper_non_recoverable=1.9801
upper_critical=1.9507
upper_non_critical=1.8919
lower_non_critical=1.7155
lower_critical=1.6567
lower_non_recoverable=1.6273
2 AD_1.2VA alarm=0 value=1.2059 threshold_status=0
type=2/1
upper_non_recoverable=1.3235
upper_critical=1.3039
upper_non_critical=1.2647
lower_non_critical=1.1373
lower_critical=1.1079
lower_non_recoverable=1.0883
3 AD_+12V alarm=0 value=12.1065 threshold_status=0
type=2/1
upper_non_recoverable=13.7585
upper_critical=13.1685
upper_non_critical=12.6375
lower_non_critical=11.3985
lower_critical=10.8085
lower_non_recoverable=10.2185
4 AD_1V_10G alarm=0 value=1.0099 threshold_status=0
type=2/1
upper_non_recoverable=1.1079
upper_critical=1.0883
upper_non_critical=1.0589
lower_non_critical=0.9511
lower_critical=0.9217
lower_non_recoverable=0.9021
5 AD_1.5VA alarm=0 value=1.4999 threshold_status=0
type=2/1
upper_non_recoverable=1.6567
upper_critical=1.6273
upper_non_critical=1.5783
lower_non_critical=1.4313
lower_critical=1.3823
lower_non_recoverable=1.3529
6 AD_1P05_PCH alarm=0 value=1.0491 threshold_status=0
type=2/1
upper_non_recoverable=1.1569
upper_critical=1.1373
upper_non_critical=1.1079
lower_non_critical=0.9903
lower_critical=0.9707
lower_non_recoverable=0.9511
7 AD_1.2VSW alarm=0 value=1.2157 threshold_status=0
type=2/1
upper_non_recoverable=1.3235
upper_critical=1.3039
upper_non_critical=1.2843
lower_non_critical=1.1373
lower_critical=1.1079
lower_non_recoverable=1.0883
8 VCCP alarm=0 value=1.0788 threshold_status=0
type=2/1
upper_non_recoverable=1.5117
upper_critical=1.4649
upper_non_critical=1.4064
lower_non_critical=0.6459
lower_critical=0.6225
lower_non_recoverable=0.5991
9 P1V1_VTT alarm=0 value=1.1118 threshold_status=0
type=2/1
upper_non_recoverable=1.2086
upper_critical=1.1822
upper_non_critical=1.1558
lower_non_critical=1.0502
lower_critical=1.015
lower_non_recoverable=0.9886
10 +12V alarm=0 value=12.089762 threshold_status=0
type=2/1
upper_non_recoverable=13.825762
upper_critical=13.205762
upper_non_critical=12.647762
lower_non_critical=11.469762
lower_critical=10.911762
lower_non_recoverable=10.291762
11 +5V alarm=0 value=5.05405 threshold_status=0
type=2/1
upper_non_recoverable=5.52565
upper_critical=5.44705
upper_non_critical=5.42085
lower_non_critical=4.79205
lower_critical=4.63485
lower_non_recoverable=4.53005
12 P3V3_STBY alarm=0 value=3.33765 threshold_status=0
type=2/1
upper_non_recoverable=3.63005
upper_critical=3.56125
upper_non_critical=3.47525
lower_non_critical=3.13125
lower_critical=3.02805
lower_non_recoverable=2.95925
13 DTS CPU alarm=0 value=54 threshold_status=0
type=1/1
upper_non_recoverable=85
upper_critical=80
upper_non_critical=75
14 ADT7490 Local alarm=0 value=48 threshold_status=0
type=1/1
upper_non_recoverable=80
upper_critical=75
upper_non_critical=70
15 ADT7490 Rem1 alarm=0 value=58 threshold_status=0
type=1/1
upper_non_recoverable=85
upper_critical=80
upper_non_critical=75
16 ADT7490 Rem2 alarm=0 value=56 threshold_status=0
type=1/1
upper_non_recoverable=82
upper_critical=77
upper_non_critical=72
17 LM75 alarm=0 value=47 threshold_status=0
type=1/1
upper_non_recoverable=83
upper_critical=78
upper_non_critical=73
18 Fan 1 alarm=0 value=6700 threshold_status=0
type=4/1
upper_non_recoverable=25000
upper_critical=24000
upper_non_critical=22000
lower_non_critical=4000
lower_critical=3000
lower_non_recoverable=2000
19 Fan 2 alarm=0 value=6700 threshold_status=0
type=4/1
upper_non_recoverable=25000
upper_critical=24000
upper_non_critical=22000
lower_non_critical=4000
lower_critical=3000
lower_non_recoverable=2000
20 Fan 3 alarm=0 value=6900 threshold_status=0
type=4/1
upper_non_recoverable=25000
upper_critical=24000
upper_non_critical=22000
lower_non_critical=4000
lower_critical=3000
lower_non_recoverable=2000
21 Fan 4 alarm=0 value=6900 threshold_status=0
type=4/1
upper_non_recoverable=25000
upper_critical=24000
upper_non_critical=22000
lower_non_critical=4000
lower_critical=3000
lower_non_recoverable=2000
22 Fan 5 alarm=0 value=6200 threshold_status=0
type=4/1
upper_non_recoverable=25000
upper_critical=24000
upper_non_critical=22000
lower_non_critical=4000
lower_critical=3000
lower_non_recoverable=2000
23 PS1 Temp alarm=0 value=41 threshold_status=0
type=1/1
upper_non_recoverable=78
upper_critical=73
upper_non_critical=68
24 PS1 Fan 1 alarm=0 value=6784 threshold_status=0
type=4/1
upper_non_recoverable=32000
upper_critical=29056
upper_non_critical=26112
lower_non_critical=1024
lower_critical=768
lower_non_recoverable=512
25 PS1 VIN alarm=0 value=230 threshold_status=0
type=2/1
upper_non_recoverable=255
upper_critical=254
upper_non_critical=250
lower_non_critical=38
lower_critical=36
lower_non_recoverable=34
26 PS1 VOUT alarm=0 value=12.032 threshold_status=0
type=2/1
upper_non_recoverable=13.229
upper_critical=12.977
upper_non_critical=12.662
lower_non_critical=11.528
lower_critical=11.15
lower_non_recoverable=10.898
27 PS1 Status alarm=0
type=8/111
upper_non_recoverable=0
upper_critical=0
upper_non_critical=0
28 PS2 Temp alarm=0 (scanning disabled)
type=1/1
upper_non_recoverable=78
upper_critical=73
upper_non_critical=68
29 PS2 Fan 1 alarm=0 (scanning disabled)
type=4/1
upper_non_recoverable=32000
upper_critical=29056
upper_non_critical=26112
lower_non_critical=1024
lower_critical=768
lower_non_recoverable=512
30 PS2 VIN alarm=0 (scanning disabled)
type=2/1
upper_non_recoverable=255
upper_critical=254
upper_non_critical=250
lower_non_critical=38
lower_critical=36
lower_non_recoverable=34
31 PS2 VOUT alarm=0 (scanning disabled)
type=2/1
upper_non_recoverable=13.229
upper_critical=12.977
upper_non_critical=12.662
lower_non_critical=11.528
lower_critical=11.15
lower_non_recoverable=10.898
32 PS2 Status alarm=0 (not detected)
type=8/111
upper_non_recoverable=0
upper_critical=0
upper_non_critical=0
33 INA219 PS1 Vsht alarm=0 value=0.00832 threshold_status=0
type=2/1
upper_non_recoverable=0.03232
upper_critical=0.03104
upper_non_critical=0.03008
34 INA219 PS1 Vbus alarm=0 value=12.032 threshold_status=0
type=2/1
upper_non_recoverable=13.312
upper_critical=13.056
upper_non_critical=12.672
lower_non_critical=11.392
lower_critical=11.136
lower_non_recoverable=10.88
35 INA219 PS2 Vsht alarm=0 value=0.00032 threshold_status=0
type=2/1
upper_non_recoverable=0.03232
upper_critical=0.03104
upper_non_critical=0.03008
36 INA219 PS2 Vbus alarm=0 value=12.032 threshold_status=0
type=2/1
upper_non_recoverable=13.312
upper_critical=13.056
upper_non_critical=12.672
lower_non_critical=11.392
lower_critical=11.136
lower_non_recoverable=10.88
@@ -0,0 +1,5 @@
CPU states: 0% user 5% system 0% nice 95% idle
CPU0 states: 0% user 8% system 0% nice 92% idle
CPU1 states: 0% user 4% system 0% nice 96% idle
CPU2 states: 0% user 4% system 0% nice 96% idle
CPU3 states: 0% user 4% system 0% nice 96% idle
-1
View File
@@ -1 +0,0 @@
# TODO move utils folder inside napalm
-7
View File
@@ -1,7 +0,0 @@
"""
Load tables/views
"""
from jnpr.junos.factory import loadyaml
from os.path import splitext
_YAML_ = splitext(__file__)[0] + '.yml'
globals().update(loadyaml(_YAML_))
-133
View File
@@ -1,133 +0,0 @@
---
####
#### Interface table
####
junos_iface_table:
rpc: get-interface-information
args:
extensive: True
args_key: interface_name
item: physical-interface
view: junos_iface_view
junos_iface_view:
fields:
is_up: { oper-status: True=up }
is_enabled: { admin-status: True=up }
description: { description: unicode }
last_flapped: { interface-flapped/@seconds: int }
#mode: logical-interface/address-family/address-family-name
speed: speed
mac_address: current-physical-address
####
#### BGP tables
####
junos_route_instance_table:
rpc: get-instance-information
item: instance-core
key: instance-name
view: junos_route_instance_view
junos_route_instance_view:
fields:
name: instance-name
junos_bgp_uptime_table:
rpc: get-bgp-summary-information
args:
instance: ''
item: bgp-peer
key: peer-address
view: junos_bgp_uptime_view
junos_bgp_uptime_view:
fields:
uptime: { elapsed-time/@seconds: int }
tables: bgp-rib/name
junos_bgp_table:
rpc: get-bgp-neighbor-information
item: bgp-peer
key: peer-address
view: junos_bgp_view
junos_bgp_view:
fields:
remote_as: { peer-as: int }
description: description
is_up: { peer-state: True=Established }
is_enabled: { peer-state: False=True }
received_prefixes: { bgp-rib/received-prefix-count: int }
accepted_prefixes: { bgp-rib/accepted-prefix-count: int }
sent_prefixes: { bgp-rib/advertised-prefix-count: int }
tables: bgp-rib/name
local_as: { local-as: int }
peer_as: { peer-as: int }
local_id: local-id
remote_id: peer-id
####
#### LLDP table
####
junos_lldp_table:
rpc: get-lldp-neighbors-information
item: lldp-neighbor-information
key: lldp-local-port-id | lldp-local-interface
view: junos_lldp_view
junos_lldp_view:
fields:
hostname: lldp-remote-system-name
port: lldp-remote-port-description | lldp-remote-port-id
####
#### Interface counters
####
junos_iface_counter_table:
rpc: get-interface-information
args:
extensive: True
interface_name: '[vmfgx][mle]*'
args_key: interface_name
item: physical-interface
view: junos_iface_counter_view
junos_iface_counter_view:
groups:
ts: traffic-statistics
rxerrs: input-error-list
txerrs: output-error-list
ethernet_traffic_types: ethernet-mac-statistics
# fields that are part of groups are called
# "fields_<group-name>"
fields_ethernet_traffic_types:
rx_broadcast_packets: { input-broadcasts: int }
tx_broadcast_packets: { output-broadcasts: int }
rx_unicast_packets: { input-unicasts: int }
tx_unicast_packets: { output-unicasts: int }
rx_multicast_packets: { input-multicasts: int }
tx_multicast_packets: { output-multicasts: int }
fields_ts:
rx_octets: { input-bytes: int }
tx_octets: { output-bytes: int }
fields_rxerrs:
rx_errors: { input-errors: int }
rx_discards: { input-discards: int }
fields_txerrs:
tx_errors: { output-errors: int }
tx_discards: { output-drops: int }
-99
View File
@@ -1,99 +0,0 @@
import re
def sorted_nicely( l ):
""" Sort the given iterable in the way that humans expect."""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
return sorted(l, key = alphanum_key)
def colon_separated_string_to_dict(string, separator=':'):
'''
Converts a string in the format:
Name: Et3
Switchport: Enabled
Administrative Mode: trunk
Operational Mode: trunk
MAC Address Learning: enabled
Access Mode VLAN: 3 (VLAN0003)
Trunking Native Mode VLAN: 1 (default)
Administrative Native VLAN tagging: disabled
Administrative private VLAN mapping: ALL
Trunking VLANs Enabled: 2-3,5-7,20-21,23,100-200
Trunk Groups:
into a dictionary
'''
dictionary = dict()
for line in string.splitlines():
line_data = line.split(separator)
if len(line_data) > 1:
dictionary[line_data[0].strip()] = ''.join(line_data[1:]).strip()
elif len(line_data) == 1:
dictionary[line_data[0].strip()] = None
else:
raise Exception('Something went wrong parsing the colo separated string {}'.format(line))
return dictionary
def hyphen_range(string):
'''
Expands a string of numbers separated by commas and hyphens into a list of integers.
For example: 2-3,5-7,20-21,23,100-200
'''
list_numbers = list()
temporary_list = string.split(',')
for element in temporary_list:
sub_element = element.split('-')
if len(sub_element) == 1:
list_numbers.append(int(sub_element[0]))
elif len(sub_element) == 2:
for x in range(int(sub_element[0]), int(sub_element[1])+1):
list_numbers.append(x)
else:
raise Exception('Something went wrong expanding the range'.format(string))
return list_numbers
def convert_uptime_string_seconds(uptime):
'''
Convert uptime strings to seconds. The string can be formatted various ways, eg.
1 hour, 56 minutes
'''
regex_1 = re.compile(r"((?P<weeks>\d+) week(s)?,\s+)?((?P<days>\d+) day(s)?,\s+)?((?P<hours>\d+) hour(s)?,\s+)?((?P<minutes>\d+) minute(s)?)")
regex_2 = re.compile(r"((?P<hours>\d+)):((?P<minutes>\d+)):((?P<seconds>\d+))")
regex_list = [regex_1, regex_2]
uptime_dict = dict()
for regex in regex_list:
uptime_dict = regex.search(uptime)
if uptime_dict is not None:
uptime_dict = uptime_dict.groupdict()
break
uptime_dict = dict()
uptime_seconds = 0
for unit, value in uptime_dict.iteritems():
if value != None:
if unit == 'weeks':
uptime_seconds += int(value) * 604800
elif unit == 'days':
uptime_seconds += int(value) * 86400
elif unit == 'hours':
uptime_seconds += int(value) * 3600
elif unit == 'minutes':
uptime_seconds += int(value) * 60
elif unit == 'seconds':
uptime_seconds += int(value)
else:
raise Exception('Unrecognized unit "{}" in uptime:{}'.format(unit, uptime))
return uptime_seconds