Example #1
0
 def test_rpcmeta_exec_rpc_format_json_lt_14_2(self, mock_warn):
     self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager)
     self.dev._facts['version_info'] = version_info('13.1X46-D15.3')
     self.rpc.get_system_users_information(dict(format='json'))
     mock_warn.assert_has_calls(
         call.warn('Native JSON support is only from 14.2 onwards',
                   RuntimeWarning))
Example #2
0
 def test_rpcmeta_exec_rpc_format_json_gt_14_2(self):
     self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager)
     self.dev._facts['version_info'] = version_info('15.1X46-D15.3')
     op = self.rpc.get_system_users_information(dict(format='json'))
     self.assertEqual(
         op['system-users-information'][0]['uptime-information'][0]
         ['date-time'][0]['data'], u'4:43AM')
Example #3
0
    def test_version_to_yaml(self):
        import yaml

        self.assertEqual(
            yaml.dump(version_info("11.4R7.5")),
            "build: 5\nmajor: !!python/tuple\n- 11\n- 4\nminor: '7'\ntype: R\n",
        )
Example #4
0
 def test_rpcmeta_exec_rpc_format_json_gt_14_2(self):
     self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager)
     self.dev.facts._cache['version_info'] = version_info('15.1X46-D15.3')
     op = self.rpc.get_system_users_information(dict(format='json'))
     self.assertEqual(op['system-users-information'][0]
                      ['uptime-information'][0]['date-time'][0]['data'],
                      u'4:43AM')
Example #5
0
 def test_version_to_json(self):
     import json
     self.assertEqual(eval(json.dumps(version_info('11.4R7.5'))), {
         "major": [11, 4],
         "type": "R",
         "build": 5,
         "minor": "7"
     })
Example #6
0
 def test_rpcmeta_exec_rpc_format_json_lt_14_2(self, mock_warn):
     self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager)
     self.dev.facts._cache["version_info"] = version_info("13.1X46-D15.3")
     self.rpc.get_system_users_information(dict(format="json"))
     mock_warn.assert_has_calls([
         call.warn("Native JSON support is only from 14.2 onwards",
                   RuntimeWarning)
     ])
Example #7
0
 def test_get_config_format_json_JSONLoadError_with_line(self):
     self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager)
     self.dev.facts._cache['version_info'] = version_info('15.1X46-D15.3')
     try:
         self.dev.rpc.get_config(options={'format': 'json'})
     except JSONLoadError as ex:
         self.assertTrue(re.search(
             "Expecting \'?,\'? delimiter: line 17 column 39 \(char 516\)",
             ex.ex_msg) is not None)
def test_update_facts(device):
    new_version = {
        'version':      '14.1R1',
        'version_RE0':  '14.1R1',
        'version_RE1':  '14.1R1',
        'version_info': version_info('14.1R1')
    }
    device_facts.update(new_version)
    assert device.facts['version'] == '14.1R1'
Example #9
0
 def test_rpcmeta_exec_rpc_format_json_gt_14_2(self):
     self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager)
     self.dev.facts._cache["version_info"] = version_info("15.1X46-D15.3")
     op = self.rpc.get_system_users_information(dict(format="json"))
     self.assertEqual(
         op["system-users-information"][0]["uptime-information"][0]
         ["date-time"][0]["data"],
         u"4:43AM",
     )
Example #10
0
 def test_get_config_format_json_JSONLoadError_with_line(self):
     self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager)
     self.dev.facts._cache['version_info'] = version_info('15.1X46-D15.3')
     try:
         self.dev.rpc.get_config(options={'format': 'json'})
     except JSONLoadError as ex:
         self.assertTrue(
             re.search(
                 "Expecting \'?,\'? delimiter: line 17 column 39 \(char 516\)",
                 ex.ex_msg) is not None)
         'status': 'OK',
         'up_time': '19 days, 16 hours, 58 minutes, 11 seconds'},
 'domain': 'mocked.juniper.domain',
 'fqdn': 'mx960.mocked.juniper.domain',
 'hostname': 'mx960',
 'ifd_style': 'CLASSIC',
 'master': 'RE0',
 'model': 'mx960',
 'personality': 'MX',
 'serialnumber': 'JN1337NA1337',
 'switch_style': 'BRIDGE_DOMAIN',
 'vc_capable': False,
 'version': '13.3R8',
 'version_RE0': '13.3R8',
 'version_RE1': '13.3R8',
 'version_info': version_info('13.3R8')
}


@patch('ncclient.manager.connect')
def device(mock_connect, *args, **kwargs):
    """Juniper PyEZ Device Mock"""

    def get_facts():
        dev._facts = device_facts

    def mock_manager(*args, **kwargs):
        if 'device_params' in kwargs:
            # open connection
            device_params = kwargs['device_params']
            device_handler = make_device_handler(device_params)
def get_facts(device):
    """
    Gathers facts from the <get-software-information/> RPC.
    """
    junos_info = None
    hostname = None
    hostname_info = None
    model = None
    model_info = None
    version = None
    ver_info = None
    version_RE0 = None
    version_RE1 = None

    rsp = _get_software_information(device)

    if rsp.tag == 'software-information':
        si_rsp = [rsp]
    else:
        si_rsp = rsp.findall('.//software-information')

    for re_sw_info in si_rsp:
        re_name = re_sw_info.findtext('../re-name', 're0')
        re_model = re_sw_info.findtext('./product-model')
        re_hostname = re_sw_info.findtext('./host-name')
        # First try the <junos-version> tag present in >= 15.1
        re_version = re_sw_info.findtext('./junos-version')
        if re_version is None:
            # For < 15.1, get version from the "junos" package.
            try:
                re_pkg_info = re_sw_info.findtext(
                    './package-information[name="junos"]/comment'
                )
                if re_pkg_info is not None:
                    re_version = re.findall(r'\[(.*)\]', re_pkg_info)[0]
                else:
                    # Junos Node Slicing JDM case
                    re_pkg_info = re_sw_info.findtext(
                        './package-information[name="JUNOS version"]/comment'
                    )
                    if re_pkg_info is not None:
                        # In this case, re_pkg_info might look like this:
                        # JUNOS version : 17.4-20170703_dev_common.0-secure
                        # Match everything from last space until the end.
                        re_version = re.findall(r'.*\s+(.*)', re_pkg_info)[0]
                    else:
                        # NFX JDM case
                        re_pkg_info = re_sw_info.findtext(
                            './version-information[component="MGD"]/release'
                        )
                        re_version = re.findall(r'(.*\d+)', re_pkg_info)[0]
            except Exception:
                re_version = None
        if model_info is None and re_model is not None:
            model_info = {}
        if re_model is not None:
            model_info[re_name] = re_model.upper()
        if hostname_info is None and re_hostname is not None:
            hostname_info = {}
        if re_hostname is not None:
            hostname_info[re_name] = re_hostname
        if junos_info is None and re_version is not None:
            junos_info = {}
        if re_version is not None:
            junos_info[re_name] = {'text': re_version,
                                   'object': version_info(re_version), }

        # Check to see if re_name is the RE we are currently connected to.
        # There are at least five cases to handle.
        this_re = False
        # 1) this device doesn't support the current_re fact and there's only
        #    one RE.
        if device.facts['current_re'] is None and len(si_rsp) == 1:
            this_re = True
        # 2) re_name is in the current_re fact. The easy case.
        elif re_name in device.facts['current_re']:
            this_re = True
        # 3) Some single-RE devices (discovered on EX2200 running 11.4R1)
        # don't include 'reX' in the current_re list. Check for this
        # condition and still set default hostname, model, and version
        elif (re_name == 're0' and 're1' not in device.facts['current_re'] and
              'master' in device.facts['current_re']):
            this_re = True
        # 4) For an lcc in a TX(P) re_name is 're0' or 're1', but the
        # current_re fact is ['lcc1-re0', 'member1-re0', ...]. Check to see
        # if any iri_name endswith the re_name.
        if this_re is False:
            for iri_name in device.facts['current_re']:
                if iri_name.endswith('-' + re_name):
                    this_re = True
                    break
        # 5) For an MX configured with Node Virtualization then, re_name is
        #    bsys-reX, but the iri_name is still just reX.
        if this_re is False:
            for iri_name in device.facts['current_re']:
                if re_name == 'bsys-' + iri_name:
                    this_re = True
                    break
        # Set hostname, model, and version facts if we've found the RE to
        # which we are currently connected.
        if this_re is True:
            if hostname is None:
                hostname = re_hostname
            if model is None:
                model = re_model.upper()
            if version is None:
                version = re_version

    if version is None:
        version = '0.0I0.0'
    ver_info = version_info(version)
    if junos_info is not None:
        if 're0' in junos_info:
            version_RE0 = junos_info['re0']['text']
        elif 'node0' in junos_info:
            version_RE0 = junos_info['node0']['text']
        elif 'bsys-re0' in junos_info:
            if len(junos_info) > 4:
                version_RE0 = junos_info['bsys-re0']['text']
            else:
                for key in junos_info.keys():
                    if key.startswith('gnf') and key.endswith('re0'):
                        version_RE0 = junos_info[key]['text']
        elif 'server0' in junos_info:
            version_RE0 = junos_info['server0']['text']
        if 're1' in junos_info:
            version_RE1 = junos_info['re1']['text']
        elif 'node1' in junos_info:
            version_RE1 = junos_info['node1']['text']
        elif 'bsys-re1' in junos_info:
            if len(junos_info) > 4:
                version_RE1 = junos_info['bsys-re1']['text']
            else:
                for key in junos_info.keys():
                    if key.startswith('gnf') and key.endswith('re1'):
                        version_RE1 = junos_info[key]['text']
        elif 'server1' in junos_info:
            version_RE1 = junos_info['server1']['text']

    return {'junos_info': junos_info,
            'hostname': hostname,
            'hostname_info': hostname_info,
            'model': model,
            'model_info': model_info,
            'version': version,
            'version_info': ver_info,
            'version_RE0': version_RE0,
            'version_RE1': version_RE1, }
Example #13
0
 def test_version_info_repr(self):
     self.assertEqual(
         repr(version_info("11.4R7.5")),
         "junos.version_info(major=(11, 4), "
         "type=R, minor=7, build=5)",
     )
def get_facts(device):
    """
    Gathers facts from the <get-software-information/> RPC.
    """
    junos_info = None
    hostname = None
    hostname_info = None
    model = None
    model_info = None
    version = None
    ver_info = None
    version_RE0 = None
    version_RE1 = None

    rsp = _get_software_information(device)

    si_rsp = None
    if rsp.tag == 'software-information':
        si_rsp = [rsp]
    else:
        si_rsp = rsp.findall('.//software-information')

    for re_sw_info in si_rsp:
        re_name = re_sw_info.findtext('../re-name', 're0')
        re_model = re_sw_info.findtext('./product-model')
        re_hostname = re_sw_info.findtext('./host-name')
        # First try the <junos-version> tag present in >= 15.1
        re_version = re_sw_info.findtext('./junos-version')
        if re_version is None:
            # For < 15.1, get version from the "junos" package.
            try:
                re_pkg_info = re_sw_info.findtext(
                    './package-information[name="junos"]/comment'
                )
                if re_pkg_info is not None:
                    re_version = re.findall(r'\[(.*)\]', re_pkg_info)[0]
                else:
                    # NFX JDM case
                    re_pkg_info = re_sw_info.findtext(
                        './version-information[component="MGD"]/release'
                    )
                    re_version = re.findall(r'(.*\d+)', re_pkg_info)[0]
            except Exception:
                re_version = None
        if model_info is None and re_model is not None:
            model_info = {}
        if re_model is not None:
            model_info[re_name] = re_model.upper()
        if hostname_info is None and re_hostname is not None:
            hostname_info = {}
        if re_hostname is not None:
            hostname_info[re_name] = re_hostname
        if junos_info is None and re_version is not None:
            junos_info = {}
        if re_version is not None:
            junos_info[re_name] = {'text': re_version,
                                   'object': version_info(re_version), }

        # Check to see if re_name is the RE we are currently connected to.
        # There are at least four cases to handle.
        this_re = False
        # 1) this device doesn't support the current_re fact and there's only
        #    one RE.
        if device.facts['current_re'] is None and len(si_rsp) == 1:
            this_re = True
        # 2) re_name is in the current_re fact. The easy case.
        elif re_name in device.facts['current_re']:
            this_re = True
        # 3) Some single-RE devices (discovered on EX2200 running 11.4R1)
        # don't include 'reX' in the current_re list. Check for this
        # condition and still set default hostname, model, and version
        elif (re_name == 're0' and 're1' not in device.facts['current_re'] and
              'master' in device.facts['current_re']):
            this_re = True
        # 4) For an lcc in a TX(P) re_name is 're0' or 're1', but the
        # current_re fact is ['lcc1-re0', 'member1-re0', ...]. Check to see
        # if any iri_name endswith the name of the
        elif this_re is False:
            for iri_name in device.facts['current_re']:
                if iri_name.endswith('-' + re_name):
                    this_re = True
                    break
        # Set hostname, model, and version facts if the RE we are currently
        # connected to.
        if this_re is True:
            if hostname is None:
                hostname = re_hostname
            if model is None:
                model = re_model.upper()
            if version is None:
                version = re_version

    if version is None:
        version = '0.0I0.0'
    ver_info = version_info(version)
    if junos_info is not None and 're0' in junos_info:
        version_RE0 = junos_info['re0']['text']
    if junos_info is not None and 're1' in junos_info:
        version_RE1 = junos_info['re1']['text']

    return {'junos_info': junos_info,
            'hostname': hostname,
            'hostname_info': hostname_info,
            'model': model,
            'model_info': model_info,
            'version': version,
            'version_info': ver_info,
            'version_RE0': version_RE0,
            'version_RE1': version_RE1, }
 def test_version_info_repr(self):
     self.assertEqual(
         repr(version_info("11.4R7.5")), "junos.version_info(major=(11, 4), " "type=R, minor=7, build=5)"
     )
Example #16
0
 def test_version_iter(self):
     self.assertItemsEqual(
         version_info('11.4R7.5'),
         [('build', 5), ('major', (11, 4)), ('minor', '7'), ('type', 'R')])
Example #17
0
def facts_software_version(junos, facts):
    """
    The following facts are required:
        facts['master']

    The following facts are assigned:
        facts['hostname']
        facts['version']
        facts['version_<RE#>'] for each RE in dual-RE, cluster or VC system
        facts['version_info'] for master RE
    """

    x_swver = _get_swver(junos, facts)

    if not facts.get('model'):
        # try to extract the model from the version information
        facts['model'] = x_swver.findtext('.//product-model')

    # ------------------------------------------------------------------------
    # extract the version information out of the RPC response
    # ------------------------------------------------------------------------

    f_master = facts.get('master', 'RE0')

    if x_swver.tag == 'multi-routing-engine-results':
        # we need to find/identify each of the routing-engine (CPU) versions.
        if len(x_swver.xpath('./multi-routing-engine-item')) > 1:
            facts['2RE'] = True
        versions = []

        if isinstance(f_master, list):
            xpath = './multi-routing-engine-item[re-name="{0}"]/software-' \
                    'information/host-name'.format(f_master[0].lower())
        else:
            xpath = './multi-routing-engine-item[re-name="{0}"' \
                    ']/software-information/host-name'.format(f_master.lower())

        facts['hostname'] = x_swver.findtext(xpath)
        if facts['hostname'] is None:
            # then there the re-name is not what we are expecting; we should
            # handle this better, eh?  For now, just assume there is one
            # software-information element and take that host-name. @@@ hack.
            facts['hostname'] = x_swver.findtext(
                './/software-information/host-name')

        for re_sw in x_swver.xpath('.//software-information'):

            re_name = re_sw.xpath('preceding-sibling::re-name')[0].text

            # handle the cases where the "RE name" could be things like
            # "FPC<n>" or "ndoe<n>", and normalize to "RE<n>".
            re_name = re.sub(r'(\w+)(\d+)', 'RE\\2', re_name)

            # First try the <junos-version> tag present in >= 15.1
            swinfo = re_sw.findtext('junos-version', default=None)
            if not swinfo:
                # For < 15.1, get version from the "junos" package.
                pkginfo = re_sw.xpath(
                    'package-information[normalize-space(name)='
                    '"junos"]/comment')[0].text
                try:
                    swinfo = re.findall(r'\[(.*)\]', pkginfo)[0]
                except:
                    swinfo = "0.0I0.0"
            versions.append((re_name.upper(), swinfo))

        # now add the versions to the facts <dict>
        for re_ver in versions:
            facts['version_' + re_ver[0]] = re_ver[1]

        if f_master is not None:
            master = f_master[0] if isinstance(f_master, list) else f_master
            if 'version_' + master in facts:
                facts['version'] = facts['version_' + master]
            else:
                facts['version'] = versions[0][1]
        else:
            facts['version'] = versions[0][1]

    else:
        # single-RE
        facts['hostname'] = x_swver.findtext('host-name')

        # First try the <junos-version> tag present in >= 15.1
        swinfo = x_swver.findtext('.//junos-version', default=None)
        if not swinfo:
            # For < 15.1, get version from the "junos" package.
            pkginfo = x_swver.xpath(
                './/package-information[normalize-space(name)="junos"]/comment'
            )[0].text
            try:
                swinfo = re.findall(r'\[(.*)\]', pkginfo)[0]
            except:
                swinfo = "0.0I0.0"
        facts['version'] = swinfo

    # ------------------------------------------------------------------------
    # create a 'version_info' object based on the master version
    # ------------------------------------------------------------------------

    facts['version_info'] = version_info(facts['version'])
Example #18
0
 def test_version_info_eq(self):
     self.assertEqual(version_info('13.3-20131120'), (13, 3))
Example #19
0
 def test_version_iter(self):
     self.assertCountEqual(
         version_info("11.4R7.5"),
         [("build", 5), ("major", (11, 4)), ("minor", "7"), ("type", "R")],
     )
Example #20
0
 def test_version_feature_velocity(self):
     self.assertCountEqual(
         version_info("15.4F7.5"),
         [("build", 5), ("major", (15, 4)), ("minor", "7"), ("type", "F")],
     )
Example #21
0
 def test_version_info_gt_eq(self):
     self.assertGreaterEqual(version_info('13.3-20131120'), (12, 1))
Example #22
0
 def test_version_info_gt(self):
     self.assertTrue(version_info("13.3-20131120") > (12, 1))
Example #23
0
 def test_version_info_lt(self):
     self.assertTrue(version_info("13.3-20131120") < (14, 1))
 def test_version_info_gt(self):
     self.assertTrue(version_info("13.3-20131120") > (12, 1))
def get_facts(device):
    """
    Gathers facts from the <get-software-information/> RPC.
    """
    junos_info = None
    hostname = None
    hostname_info = None
    model = None
    model_info = None
    version = None
    ver_info = None
    version_RE0 = None
    version_RE1 = None

    rsp = _get_software_information(device)

    if rsp.tag == 'software-information':
        si_rsp = [rsp]
    else:
        si_rsp = rsp.findall('.//software-information')

    for re_sw_info in si_rsp:
        re_name = re_sw_info.findtext('../re-name', 're0')
        re_model = re_sw_info.findtext('./product-model')
        re_hostname = re_sw_info.findtext('./host-name')
        # First try the <junos-version> tag present in >= 15.1
        re_version = re_sw_info.findtext('./junos-version')
        if re_version is None:
            # For < 15.1, get version from the "junos" package.
            try:
                re_pkg_info = re_sw_info.findtext(
                    './package-information[name="junos"]/comment')
                if re_pkg_info is not None:
                    re_version = re.findall(r'\[(.*)\]', re_pkg_info)[0]
                else:
                    # Junos Node Slicing JDM case
                    re_pkg_info = re_sw_info.findtext(
                        './package-information[name="JUNOS version"]/comment')
                    if re_pkg_info is not None:
                        # In this case, re_pkg_info might look like this:
                        # JUNOS version : 17.4-20170703_dev_common.0-secure
                        # Match everything from last space until the end.
                        re_version = re.findall(r'.*\s+(.*)', re_pkg_info)[0]
                    else:
                        # NFX JDM case
                        re_pkg_info = re_sw_info.findtext(
                            './version-information[component="MGD"]/release')
                        re_version = re.findall(r'(.*\d+)', re_pkg_info)[0]
            except Exception:
                re_version = None
        if model_info is None and re_model is not None:
            model_info = {}
        if re_model is not None:
            model_info[re_name] = re_model.upper()
        if hostname_info is None and re_hostname is not None:
            hostname_info = {}
        if re_hostname is not None:
            hostname_info[re_name] = re_hostname
        if junos_info is None and re_version is not None:
            junos_info = {}
        if re_version is not None:
            junos_info[re_name] = {
                'text': re_version,
                'object': version_info(re_version),
            }

        # Check to see if re_name is the RE we are currently connected to.
        # There are at least five cases to handle.
        this_re = False
        # 1) this device doesn't support the current_re fact and there's only
        #    one RE.
        if device.facts['current_re'] is None and len(si_rsp) == 1:
            this_re = True
        # 2) re_name is in the current_re fact. The easy case.
        elif re_name in device.facts['current_re']:
            this_re = True
        # 3) Some single-RE devices (discovered on EX2200 running 11.4R1)
        # don't include 'reX' in the current_re list. Check for this
        # condition and still set default hostname, model, and version
        elif (re_name == 're0' and 're1' not in device.facts['current_re']
              and 'master' in device.facts['current_re']):
            this_re = True
        # 4) For an lcc in a TX(P) re_name is 're0' or 're1', but the
        # current_re fact is ['lcc1-re0', 'member1-re0', ...]. Check to see
        # if any iri_name endswith the re_name.
        if this_re is False:
            for iri_name in device.facts['current_re']:
                if iri_name.endswith('-' + re_name):
                    this_re = True
                    break
        # 5) For an MX configured with Node Virtualization then, re_name is
        #    bsys-reX, but the iri_name is still just reX.
        if this_re is False:
            for iri_name in device.facts['current_re']:
                if re_name == 'bsys-' + iri_name:
                    this_re = True
                    break
        # Set hostname, model, and version facts if we've found the RE to
        # which we are currently connected.
        if this_re is True:
            if hostname is None:
                hostname = re_hostname
            if model is None:
                model = re_model.upper()
            if version is None:
                version = re_version

    if version is None:
        version = '0.0I0.0'
    ver_info = version_info(version)
    if junos_info is not None:
        if 're0' in junos_info:
            version_RE0 = junos_info['re0']['text']
        elif 'node0' in junos_info:
            version_RE0 = junos_info['node0']['text']
        elif 'bsys-re0' in junos_info:
            version_RE0 = junos_info['bsys-re0']['text']
        elif 'server0' in junos_info:
            version_RE0 = junos_info['server0']['text']
        if 're1' in junos_info:
            version_RE1 = junos_info['re1']['text']
        elif 'node1' in junos_info:
            version_RE1 = junos_info['node1']['text']
        elif 'bsys-re1' in junos_info:
            version_RE1 = junos_info['bsys-re1']['text']
        elif 'server1' in junos_info:
            version_RE1 = junos_info['server1']['text']

    return {
        'junos_info': junos_info,
        'hostname': hostname,
        'hostname_info': hostname_info,
        'model': model,
        'model_info': model_info,
        'version': version,
        'version_info': ver_info,
        'version_RE0': version_RE0,
        'version_RE1': version_RE1,
    }
Example #26
0
from lxml import etree
from mock import patch, MagicMock, call, mock_open

if sys.version < "3":
    builtin_string = "__builtin__"
else:
    builtin_string = "builtins"

__author__ = "Nitin Kumar, Rick Sherman"
__credits__ = "Jeremy Schulman"

facts = {
    "domain": None,
    "hostname": "firefly",
    "ifd_style": "CLASSIC",
    "version_info": version_info("12.1X46-D15.3"),
    "2RE": True,
    "serialnumber": "aaf5fe5f9b88",
    "fqdn": "firefly",
    "virtual": True,
    "switch_style": "NONE",
    "version": "12.1X46-D15.3",
    "HOME": "/cf/var/home/rick",
    "srx_cluster": False,
    "version_RE0": "16.1-20160925.0",
    "version_RE1": "16.1-20160925.0",
    "model": "FIREFLY-PERIMETER",
    "_is_linux": False,
    "junos_info": {
        "re0": {
            "text": "16.1-20160925.0"
Example #27
0
def facts_software_version(junos, facts):
    """
    The following facts are required:
        facts['master']

    The following facts are assigned:
        facts['hostname']
        facts['version']
        facts['version_<RE#>'] for each RE in dual-RE, cluster or VC system
        facts['version_info'] for master RE
    """

    x_swver = _get_swver(junos, facts)

    if not facts.get("model"):
        # try to extract the model from the version information
        facts["model"] = x_swver.findtext(".//product-model")

    # ------------------------------------------------------------------------
    # extract the version information out of the RPC response
    # ------------------------------------------------------------------------

    f_master = facts.get("master", "RE0")

    if x_swver.tag == "multi-routing-engine-results":
        # we need to find/identify each of the routing-engine (CPU) versions.
        if len(x_swver.xpath("./multi-routing-engine-item")) > 1:
            facts["2RE"] = True
        versions = []

        if isinstance(f_master, list):
            xpath = ('./multi-routing-engine-item[re-name="{}"]/software-'
                     "information/host-name".format(f_master[0].lower()))
        else:
            xpath = ('./multi-routing-engine-item[re-name="{}"'
                     "]/software-information/host-name".format(
                         f_master.lower()))

        facts["hostname"] = x_swver.findtext(xpath)
        if facts["hostname"] is None:
            # then there the re-name is not what we are expecting; we should
            # handle this better, eh?  For now, just assume there is one
            # software-information element and take that host-name. @@@ hack.
            facts["hostname"] = x_swver.findtext(
                ".//software-information/host-name")

        for re_sw in x_swver.xpath(".//software-information"):

            re_name = re_sw.xpath("preceding-sibling::re-name")[0].text

            # handle the cases where the "RE name" could be things like
            # "FPC<n>" or "ndoe<n>", and normalize to "RE<n>".
            re_name = re.sub(r"(\w+)(\d+)", "RE\\2", re_name)

            # First try the <junos-version> tag present in >= 15.1
            swinfo = re_sw.findtext("junos-version", default=None)
            if not swinfo:
                # For < 15.1, get version from the "junos" package.
                pkginfo = re_sw.xpath(
                    "package-information[normalize-space(name)="
                    '"junos"]/comment')[0].text
                try:
                    swinfo = re.findall(r"\[(.*)\]", pkginfo)[0]
                except:
                    swinfo = "0.0I0.0"
            versions.append((re_name.upper(), swinfo))

        # now add the versions to the facts <dict>
        for re_ver in versions:
            facts["version_" + re_ver[0]] = re_ver[1]

        if f_master is not None:
            master = f_master[0] if isinstance(f_master, list) else f_master
            if "version_" + master in facts:
                facts["version"] = facts["version_" + master]
            else:
                facts["version"] = versions[0][1]
        else:
            facts["version"] = versions[0][1]

    else:
        # single-RE
        facts["hostname"] = x_swver.findtext("host-name")

        # First try the <junos-version> tag present in >= 15.1
        swinfo = x_swver.findtext(".//junos-version", default=None)
        if not swinfo:
            # For < 15.1, get version from the "junos" package.
            pkginfo = x_swver.xpath(
                './/package-information[normalize-space(name)="junos"]/comment'
            )[0].text
            try:
                swinfo = re.findall(r"\[(.*)\]", pkginfo)[0]
            except:
                swinfo = "0.0I0.0"
        facts["version"] = swinfo

    # ------------------------------------------------------------------------
    # create a 'version_info' object based on the master version
    # ------------------------------------------------------------------------

    facts["version_info"] = version_info(facts["version"])
Example #28
0
 def test_version_info_eq(self):
     self.assertTrue(version_info('13.3-20131120') == (13, 3))
Example #29
0
 def test_version_info_not_eq(self):
     self.assertNotEqual(version_info('13.3-20131120'), (15, 3))
Example #30
0
 def test_version_to_yaml(self):
     import yaml
     self.assertEqual(
         yaml.dump(version_info('11.4R7.5')),
         "build: 5\nmajor: !!python/tuple [11, 4]\nminor: '7'\ntype: R\n")
Example #31
0
 def test_version_info_lt_eq(self):
     self.assertLessEqual(version_info('13.3-20131120'), (14, 1))
Example #32
0
 def test_version_feature_velocity(self):
     self.assertItemsEqual(
         version_info('15.4F7.5'),
         [('build', 5), ('major', (15, 4)), ('minor', '7'), ('type', 'F')])
Example #33
0
 def test_version_info_X_type_non_hyphenated_nobuild(self):
     self.assertCountEqual(
         version_info("11.4X12"),
         [("build", None), ("major", (11, 4)), ("minor", "12"),
          ("type", "X")],
     )
Example #34
0
 def test_version_info_X_type_non_hyphenated_nobuild(self):
     self.assertItemsEqual(version_info('11.4X12'), [('build', None),
                                                     ('major', (11, 4)),
                                                     ('minor', '12'),
                                                     ('type', 'X')])
Example #35
0
 def test_version_info_after_type_len_else(self):
     self.assertEqual(version_info('12.1X46-D10').build, None)
Example #36
0
 def test_version_feature_velocity(self):
     self.assertItemsEqual(version_info('15.4F7.5'), [('build', 5),
                                                      ('major', (15, 4)),
                                                      ('minor', '7'),
                                                      ('type', 'F')])
Example #37
0
 def test_version_info_X_type_non_hyphenated_nobuild(self):
     self.assertItemsEqual(
         version_info('11.4X12'),
         [('build', None), ('major', (11, 4)), ('minor', '12'), ('type', 'X')])
def get_facts(device):
    """
    Gathers facts from the <get-software-information/> RPC.
    """
    junos_info = None
    hostname = None
    hostname_info = None
    model = None
    model_info = None
    version = None
    ver_info = None
    version_RE0 = None
    version_RE1 = None

    rsp = _get_software_information(device)

    si_rsp = None
    if rsp.tag == 'software-information':
        si_rsp = [rsp]
    else:
        si_rsp = rsp.findall('.//software-information')

    for re_sw_info in si_rsp:
        re_name = re_sw_info.findtext('../re-name', 're0')
        re_model = re_sw_info.findtext('./product-model')
        re_hostname = re_sw_info.findtext('./host-name')
        # First try the <junos-version> tag present in >= 15.1
        re_version = re_sw_info.findtext('./junos-version')
        if re_version is None:
            # For < 15.1, get version from the "junos" package.
            try:
                re_pkg_info = re_sw_info.xpath(
                    './package-information[name="junos"]/comment'
                )[0].text
                re_version = re.findall(r'\[(.*)\]', re_pkg_info)[0]
            except:
                re_version = None
        if model_info is None and re_model is not None:
            model_info = {}
        if re_model is not None:
            model_info[re_name] = re_model.upper()
        if hostname_info is None and re_hostname is not None:
            hostname_info = {}
        if re_hostname is not None:
            hostname_info[re_name] = re_hostname
        if junos_info is None and re_version is not None:
            junos_info = {}
        if re_version is not None:
            junos_info[re_name] = {'text': re_version,
                                   'object': version_info(re_version), }

        # Check to see if re_name is the RE we are currently connected to.
        # There are at least three cases to handle.
        this_re = False
        # 1) re_name is in the current_re fact. The easy case.
        if re_name in device.facts['current_re']:
            this_re = True
        # 2) Some single-RE devices (discovered on EX2200 running 11.4R1)
        # don't include 'reX' in the current_re list. Check for this
        # condition and still set default hostname, model, and version
        elif (re_name == 're0' and 're1' not in device.facts['current_re'] and
              'master' in device.facts['current_re']):
            this_re = True
        # 3) For an lcc in a TX(P) re_name is 're0' or 're1', but the
        # current_re fact is ['lcc1-re0', 'member1-re0', ...]. Check to see
        # if any iri_name endswith the name of the
        elif this_re is False:
            for iri_name in device.facts['current_re']:
                if iri_name.endswith('-' + re_name):
                    this_re = True
                    break
        # Set hostname, model, and version facts if the RE we are currently
        # connected to.
        if this_re is True:
            if hostname is None:
                hostname = re_hostname
            if model is None:
                model = re_model.upper()
            if version is None:
                version = re_version

    if version is None:
        version = '0.0I0.0'
    ver_info = version_info(version)
    if junos_info is not None and 're0' in junos_info:
        version_RE0 = junos_info['re0']['text']
    if junos_info is not None and 're1' in junos_info:
        version_RE1 = junos_info['re1']['text']

    return {'junos_info': junos_info,
            'hostname': hostname,
            'hostname_info': hostname_info,
            'model': model,
            'model_info': model_info,
            'version': version,
            'version_info': ver_info,
            'version_RE0': version_RE0,
            'version_RE1': version_RE1, }
Example #39
0
 def test_rpcmeta_exec_rpc_format_json_lt_14_2(self, mock_warn):
     self.dev._conn.rpc = MagicMock(side_effect=self._mock_manager)
     self.dev.facts._cache['version_info'] = version_info('13.1X46-D15.3')
     self.rpc.get_system_users_information(dict(format='json'))
     mock_warn.assert_has_calls([call.warn(
         'Native JSON support is only from 14.2 onwards', RuntimeWarning)])
Example #40
0
 def test_version_to_yaml(self):
     import yaml
     self.assertEqual(
         yaml.dump(version_info('11.4R7.5')),
         "build: 5\nmajor: !!python/tuple [11, 4]\nminor: '7'\ntype: R\n")
Example #41
0
from lxml import etree
from mock import patch, MagicMock, call, mock_open

if sys.version < '3':
    builtin_string = '__builtin__'
else:
    builtin_string = 'builtins'

__author__ = "Nitin Kumar, Rick Sherman"
__credits__ = "Jeremy Schulman"

facts = {
    'domain': None,
    'hostname': 'firefly',
    'ifd_style': 'CLASSIC',
    'version_info': version_info('12.1X46-D15.3'),
    '2RE': True,
    'serialnumber': 'aaf5fe5f9b88',
    'fqdn': 'firefly',
    'virtual': True,
    'switch_style': 'NONE',
    'version': '12.1X46-D15.3',
    'HOME': '/cf/var/home/rick',
    'srx_cluster': False,
    'version_RE0': '16.1-20160925.0',
    'version_RE1': '16.1-20160925.0',
    'model': 'FIREFLY-PERIMETER',
    'RE0': {
        'status': 'Testing',
        'last_reboot_reason': 'Router rebooted after a '
        'normal shutdown.',
Example #42
0
from mock import MagicMock, patch, mock_open
import os
from lxml import etree

from ncclient.manager import Manager, make_device_handler
from ncclient.transport import SSHSession
import ncclient.transport.errors as NcErrors

from jnpr.junos.facts.swver import version_info
from jnpr.junos import Device
from jnpr.junos.exception import RpcError
from jnpr.junos import exception as EzErrors


facts = {'domain': None, 'hostname': 'firefly', 'ifd_style': 'CLASSIC',
         'version_info': version_info('12.1X46-D15.3'),
         '2RE': False, 'serialnumber': 'aaf5fe5f9b88', 'fqdn': 'firefly',
         'virtual': True, 'switch_style': 'NONE', 'version': '12.1X46-D15.3',
         'HOME': '/cf/var/home/rick', 'srx_cluster': False,
         'model': 'FIREFLY-PERIMETER',
         'RE0': {'status': 'Testing',
                 'last_reboot_reason': 'Router rebooted after a '
                 'normal shutdown.',
                 'model': 'FIREFLY-PERIMETER RE',
                 'up_time': '6 hours, 29 minutes, 30 seconds'},
         'vc_capable': False, 'personality': 'SRX_BRANCH'}


@attr('unit')
class Test_MyTemplateLoader(unittest.TestCase):
    def setUp(self):
Example #43
0
 def test_version_info_constructor_else_exception(self):
     self.assertEqual(version_info('11.4R7').build, '7')
 def test_version_info_lt(self):
     self.assertTrue(version_info("13.3-20131120") < (14, 1))
Example #45
0
 def test_version_info_lt_eq(self):
     self.assertTrue(version_info('13.3-20131120') <= (14, 1))
Example #46
0
 def test_version_info_constructor_else_exception(self):
     self.assertEqual(version_info('11.4R7').build, '7')
Example #47
0
from ncclient.manager import Manager, make_device_handler
from ncclient.transport import SSHSession
import ncclient.transport.errors as NcErrors
from ncclient.operations import RPCError, TimeoutExpiredError

from jnpr.junos.facts.swver import version_info
from jnpr.junos import Device
from jnpr.junos.exception import RpcError
from jnpr.junos import exception as EzErrors


facts = {
    "domain": None,
    "hostname": "firefly",
    "ifd_style": "CLASSIC",
    "version_info": version_info("12.1X46-D15.3"),
    "2RE": False,
    "serialnumber": "aaf5fe5f9b88",
    "fqdn": "firefly",
    "virtual": True,
    "switch_style": "NONE",
    "version": "12.1X46-D15.3",
    "HOME": "/cf/var/home/rick",
    "srx_cluster": False,
    "model": "FIREFLY-PERIMETER",
    "RE0": {
        "status": "Testing",
        "last_reboot_reason": "Router rebooted after a " "normal shutdown.",
        "model": "FIREFLY-PERIMETER RE",
        "up_time": "6 hours, 29 minutes, 30 seconds",
    },
Example #48
0
 def test_version_info_repr(self):
     self.assertEqual(repr(version_info('11.4R7.5')),
                      'junos.version_info(major=(11, 4), '
                      'type=R, minor=7, build=5)')
Example #49
0
 def test_version_info_lt_eq(self):
     self.assertTrue(version_info('13.3-20131120') <= (14, 1))
Example #50
0
 def test_version_iter(self):
     self.assertItemsEqual(version_info('11.4R7.5'), [('build', 5),
                                                      ('major', (11, 4)),
                                                      ('minor', '7'),
                                                      ('type', 'R')])
Example #51
0
 def test_version_info_gt_eq(self):
     self.assertTrue(version_info('13.3-20131120') >= (12, 1))
Example #52
0
 def test_version_info_after_type_len_else(self):
     self.assertEqual(version_info('12.1X46-D10').build, None)
Example #53
0
 def test_version_info_eq(self):
     self.assertTrue(version_info('13.3-20131120') == (13, 3))
Example #54
0
 def test_version_info_repr(self):
     self.assertEqual(
         repr(version_info('11.4R7.5')),
         'junos.version_info(major=(11, 4), '
         'type=R, minor=7, build=5)')
Example #55
0
 def test_version_info_not_eq(self):
     self.assertTrue(version_info('13.3-20131120') != (15, 3))
Example #56
0
 def test_version_info_gt_eq(self):
     self.assertTrue(version_info('13.3-20131120') >= (12, 1))
Example #57
0
 def test_version_to_json(self):
     import json
     self.assertEqual(eval(json.dumps(version_info('11.4R7.5'))),
                      {"major": [11, 4], "type": "R", "build": 5, "minor": "7"})
Example #58
0
 def test_version_info_not_eq(self):
     self.assertTrue(version_info('13.3-20131120') != (15, 3))
def get_facts(device):
    """
    Gathers facts from the <get-software-information/> RPC.
    """
    junos_info = None
    hostname = None
    hostname_info = None
    model = None
    model_info = None
    version = None
    ver_info = None
    version_RE0 = None
    version_RE1 = None

    rsp = _get_software_information(device)

    if rsp.tag == "software-information":
        si_rsp = [rsp]
    else:
        si_rsp = rsp.findall(".//software-information")

    for re_sw_info in si_rsp:
        re_name = re_sw_info.findtext("../re-name", "re0")
        re_model = re_sw_info.findtext("./product-model")
        re_hostname = re_sw_info.findtext("./host-name")
        # First try the <junos-version> tag present in >= 15.1
        re_version = re_sw_info.findtext("./junos-version")
        if re_version is None:
            # For < 15.1, get version from the "junos" package.
            try:
                re_pkg_info = re_sw_info.findtext(
                    './package-information[name="junos"]/comment'
                )
                if re_pkg_info is not None:
                    re_version = re.findall(r"\[(.*)\]", re_pkg_info)[0]
                else:
                    # Junos Node Slicing JDM case
                    re_pkg_info = re_sw_info.findtext(
                        './package-information[name="JUNOS version"]/comment'
                    )
                    if re_pkg_info is not None:
                        # In this case, re_pkg_info might look like this:
                        # JUNOS version : 17.4-20170703_dev_common.0-secure
                        # Match everything from last space until the end.
                        re_version = re.findall(r".*\s+(.*)", re_pkg_info)[0]
                    else:
                        # NFX JDM case
                        re_pkg_info = re_sw_info.findtext(
                            './version-information[component="MGD"]/release'
                        )
                        re_version = re.findall(r"(.*\d+)", re_pkg_info)[0]
            except Exception:
                re_version = None
        if model_info is None and re_model is not None:
            model_info = {}
        if re_model is not None:
            model_info[re_name] = re_model.upper()
        if hostname_info is None and re_hostname is not None:
            hostname_info = {}
        if re_hostname is not None:
            hostname_info[re_name] = re_hostname
        if junos_info is None and re_version is not None:
            junos_info = {}
        if re_version is not None:
            junos_info[re_name] = {
                "text": re_version,
                "object": version_info(re_version),
            }

        # Check to see if re_name is the RE we are currently connected to.
        # There are at least five cases to handle.
        this_re = False
        # 1) this device doesn't support the current_re fact and there's only
        #    one RE.
        if device.facts["current_re"] is None and len(si_rsp) == 1:
            this_re = True
        # 2) re_name is in the current_re fact. The easy case.
        elif re_name in device.facts["current_re"]:
            this_re = True
        # 3) Some single-RE devices (discovered on EX2200 running 11.4R1)
        # don't include 'reX' in the current_re list. Check for this
        # condition and still set default hostname, model, and version
        elif (
            re_name == "re0"
            and "re1" not in device.facts["current_re"]
            and "master" in device.facts["current_re"]
        ):
            this_re = True
        # 4) For an lcc in a TX(P) re_name is 're0' or 're1', but the
        # current_re fact is ['lcc1-re0', 'member1-re0', ...]. Check to see
        # if any iri_name endswith the re_name.
        if this_re is False:
            for iri_name in device.facts["current_re"]:
                if iri_name.endswith("-" + re_name):
                    this_re = True
                    break
        # 5) For an MX configured with Node Virtualization then, re_name is
        #    bsys-reX, but the iri_name is still just reX.
        if this_re is False:
            for iri_name in device.facts["current_re"]:
                if re_name == "bsys-" + iri_name:
                    this_re = True
                    break
        # Set hostname, model, and version facts if we've found the RE to
        # which we are currently connected.
        if this_re is True:
            if hostname is None:
                hostname = re_hostname
            if model is None:
                model = re_model.upper()
            if version is None:
                version = re_version

    if version is None:
        version = "0.0I0.0"
    ver_info = version_info(version)
    if junos_info is not None:
        if "re0" in junos_info:
            version_RE0 = junos_info["re0"]["text"]
        elif "node0" in junos_info:
            version_RE0 = junos_info["node0"]["text"]
        elif "bsys-re0" in junos_info:
            if len(junos_info) > 4:
                version_RE0 = junos_info["bsys-re0"]["text"]
            else:
                for key in junos_info.keys():
                    if key.startswith("gnf") and key.endswith("re0"):
                        version_RE0 = junos_info[key]["text"]
        elif "server0" in junos_info:
            version_RE0 = junos_info["server0"]["text"]
        if "re1" in junos_info:
            version_RE1 = junos_info["re1"]["text"]
        elif "node1" in junos_info:
            version_RE1 = junos_info["node1"]["text"]
        elif "bsys-re1" in junos_info:
            if len(junos_info) > 4:
                version_RE1 = junos_info["bsys-re1"]["text"]
            else:
                for key in junos_info.keys():
                    if key.startswith("gnf") and key.endswith("re1"):
                        version_RE1 = junos_info[key]["text"]
        elif "server1" in junos_info:
            version_RE1 = junos_info["server1"]["text"]

    return {
        "junos_info": junos_info,
        "hostname": hostname,
        "hostname_info": hostname_info,
        "model": model,
        "model_info": model_info,
        "version": version,
        "version_info": ver_info,
        "version_RE0": version_RE0,
        "version_RE1": version_RE1,
    }