/usr/lib/python2.7/dist-packages/pyeapi/utils.py is in python-pyeapi 0.8.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | #
# Copyright (c) 2014, Arista Networks, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# Neither the name of Arista Networks nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import os
import sys
import imp
import inspect
import logging
import logging.handlers
import collections
from itertools import tee
try:
# Try Python 3.x import first
from itertools import zip_longest
except ImportError:
# Use Python 2.7 import as a fallback
from itertools import izip_longest as zip_longest
_LOGGER = logging.getLogger(__name__)
_LOGGER.setLevel(logging.DEBUG)
# Create a handler to log messages to syslog
if sys.platform == "darwin":
_syslog_handler = logging.handlers.SysLogHandler(address='/var/run/syslog')
else:
_syslog_handler = logging.handlers.SysLogHandler()
_LOGGER.addHandler(_syslog_handler)
# Create a handler to log messages to stderr
_stderr_formatter = logging.Formatter('\n\n**** LOG NOTE ****\n%(message)s\n')
_stderr_handler = logging.StreamHandler()
_stderr_handler.setFormatter(_stderr_formatter)
_LOGGER.addHandler(_stderr_handler)
def import_module(name):
""" Imports a module into the current runtime environment
This function emulates the Python import system that allows for
importing full path modules. It will break down the module and
import each part (or skip if it is already loaded in cache).
Args:
name (str): The name of the module to import. This should be
the full path of the module
Returns:
The module that was imported
"""
parts = name.split('.')
path = None
module_name = ''
fhandle = None
for index, part in enumerate(parts):
module_name = part if index == 0 else '%s.%s' % (module_name, part)
path = [path] if path is not None else path
try:
fhandle, path, descr = imp.find_module(part, path)
if module_name in sys.modules:
# since imp.load_module works like reload, need to be sure not
# to reload a previously loaded module
mod = sys.modules[module_name]
else:
mod = imp.load_module(module_name, fhandle, path, descr)
finally:
# lets be sure to clean up after ourselves
if fhandle:
fhandle.close()
return mod
def load_module(name):
""" Attempts to load a module into the current environment
This function will load a module specified by name. The module
name is first checked to see if it is already loaded and will return
the module if it is. If the module hasn't been previously loaded
it will attempt to import it
Args:
name (str): Specifies the full name of the module. For instance
pyeapi.api.vlans
Returns:
The module that has been imported or retrieved from the sys modules
"""
try:
mod = None
mod = sys.modules[name]
except KeyError:
mod = import_module(name)
finally:
if not mod:
raise ImportError('unable to import module %s' % name)
return mod
class ProxyCall(object):
def __init__(self, proxy, method):
self.proxy = proxy
self.method = method
def __call__(self, *args, **kwargs):
return self.proxy(self.method, *args, **kwargs)
def islocalconnection():
""" Checks if running locally on EOS device or remotely
This function will return a boolean indicating if the current
execution environment is running locally on an EOS device (True) or
running remotely and communicating over HTTP/S (False)
Returns:
A boolean value that indicates whether or not the current
thread is local or remote
"""
return os.path.exists('/etc/Eos-release')
def debug(text):
"""Log a message to syslog and stderr
Args:
text (str): The string object to print
"""
frame = inspect.currentframe().f_back
module = frame.f_globals['__name__']
func = frame.f_code.co_name
msg = "%s.%s: %s" % (module, func, text)
_LOGGER.debug(msg)
def make_iterable(value):
"""Converts the supplied value to a list object
This function will inspect the supplied value and return an
iterable in the form of a list.
Args:
value (object): An valid Python object
Returns:
An iterable object of type list
"""
if sys.version_info <= (3, 0):
# Convert unicode values to strings for Python 2
if isinstance(value, unicode):
value = str(value)
if isinstance(value, str):
value = [value]
if not isinstance(value, collections.Iterable):
raise TypeError('value must be an iterable object')
return value
def lookahead(it):
it1, it2 = tee(iter(it))
next(it2)
return zip_longest(it1, it2)
def expand_range(arg, value_delimiter=',', range_delimiter='-'):
"""
Expands a delimited string of ranged integers into a list of strings
:param arg: The string range to expand
:param value_delimiter: The delimiter that separates values
:param range_delimiter: The delimiter that signifies a range of values
:return: An array of expanded string values
:rtype: list
"""
values = list()
expanded = arg.split(value_delimiter)
for item in expanded:
if range_delimiter in item:
start, end = item.split(range_delimiter)
_expand = range(int(start), int(end) + 1)
values.extend([str(x) for x in _expand])
else:
values.extend([item])
return [str(x) for x in values]
def collapse_range(arg, value_delimiter=',', range_delimiter='-'):
"""
Collapses a list of values into a range set
:param arg: The list of values to collapse
:param value_delimiter: The delimiter that separates values
:param range_delimiter: The delimiter that separates a value range
:return: An array of collapsed string values
:rtype: list
"""
values = list()
expanded = arg.split(value_delimiter)
range_start = None
for v1, v2 in lookahead(expanded):
if v2:
v1 = int(v1)
v2 = int(v2)
if (v1 + 1) == v2:
if not range_start:
range_start = v1
elif range_start:
item = '{}{}{}'.format(range_start, range_delimiter, v1)
values.extend([item])
range_start = None
else:
values.extend([v1])
elif range_start:
item = '{}{}{}'.format(range_start, range_delimiter, v1)
values.extend([item])
range_start = None
else:
values.extend([v1])
return [str(x) for x in values]
|