Esempio n. 1
0
def version_in(version: str, ver: PrototypeImport) -> bool:
    # log.debug('version_in: %s < %s > %s', ver.min_version, version, ver.max_version)
    if ver.min_strict:
        if rpm.compare_versions(version, ver.min_version) <= 0:
            return False
    elif ver.min_version:
        if rpm.compare_versions(version, ver.min_version) < 0:
            return False
    if ver.max_strict:
        if rpm.compare_versions(version, ver.max_version) >= 0:
            return False
    elif ver.max_version:
        if rpm.compare_versions(version, ver.max_version) > 0:
            return False
    return True
Esempio n. 2
0
def version_in(version, ver):
    # log.debug('version_in: %s < %s > %s', ver.min_version, version, ver.max_version)
    if ver.min_strict:
        if rpm.compare_versions(version, ver.min_version) <= 0:
            return False
    else:
        if rpm.compare_versions(version, ver.min_version) < 0:
            return False
    if ver.max_strict:
        if rpm.compare_versions(version, ver.max_version) >= 0:
            return False
    else:
        if rpm.compare_versions(version, ver.max_version) > 0:
            return False
    return True
Esempio n. 3
0
def _run_action_and_assert_result(
    obj: Union[Cluster, Service, Host, Component, Provider],
    action_name: str,
    expected_status="success",
    timeout=None,
    **kwargs,
):
    """
    Run action and assert that status equals to 'status' argument
    """
    obj_name = obj.name if not isinstance(obj, Host) else obj.fqdn
    with allure.step(
            f"Perform action '{action_name}' for {obj.__class__.__name__} '{obj_name}'"
    ), _suggest_action_if_not_exists(obj, action_name):
        if rpm.compare_versions(
                obj.adcm_version,
                "2021.02.04.13") >= 0 and "verbose" not in kwargs:
            kwargs["verbose"] = options.verbose_actions  # pylint: disable=no-member
        obj.reread()
        try:
            action = obj.action(name=action_name)
            _add_actions_info(action=action, expected_status=expected_status)
            task = action.run(**kwargs)
        except ErrorMessage as err:
            ADCMError.raise_if_suitable(err.error.title)
            raise
        wait_for_task_and_assert_result(task=task,
                                        action_name=action_name,
                                        status=expected_status,
                                        timeout=timeout)
        return task
Esempio n. 4
0
def determine_cves(package, version, os, cve_data):
    vulnerabilities = []
    if package in cve_data:
        cves = cve_data[package]

        for cve in cves:
            if os in cves[cve]["releases"].keys():
                urgency = cves[cve]["releases"][os]["urgency"]
                if "fixed_version" in cves[cve]["releases"][os]:
                    fixed = cves[cve]["releases"][os]["fixed_version"]
                    vulnerable = rpm.compare_versions(fixed, version) > 0
                else:
                    fixed = False
                    vulnerable = True
                if vulnerable:
                    latest = cves[cve]["releases"][os]["repositories"][os]
                    vulnerability = {
                        "cve": cve,
                        "urgency": urgency,
                        "fixed": fixed,
                        "installed": version,
                        "latest": latest,
                    }
                    vulnerabilities.append(vulnerability)
    return vulnerabilities
Esempio n. 5
0
 def _check_min_version(self):
     try:
         version = self._api.objects.info.list()['adcm_version']
     except (KeyError, AttributeError):
         version = "0"
     if rpm.compare_versions(self._MIN_VERSION, version) > 0:
         raise ADCMApiError(
             "That client supports ADCM versions >= {}".format(
                 self._MIN_VERSION))
Esempio n. 6
0
def rpm_nvr_compare(nvr_a, nvr_b):
    """Compare the version-release parts of two name-release-version strings by RPM rules."""

    n_a, v_a, r_a = nvr_a.rsplit('-', 2)
    n_b, v_b, r_b = nvr_b.rsplit('-', 2)

    if n_a != n_b:
        raise ValueError(f"{nvr_a} and {nvr_b} have different names")

    return compare_versions(nvr_a, nvr_b)
Esempio n. 7
0
def check_upgrade_version(obj: Union[Cluster, HostProvider], upgrade: Upgrade) -> Tuple[bool, str]:
    proto = obj.prototype
    # log.debug('check %s < %s > %s', upgrade.min_version, proto.version, upgrade.max_version)
    if upgrade.min_strict:
        if rpm.compare_versions(proto.version, upgrade.min_version) <= 0:
            msg = '{} version {} is less than or equal to upgrade min version {}'
            return False, msg.format(proto.type, proto.version, upgrade.min_version)
    else:
        if rpm.compare_versions(proto.version, upgrade.min_version) < 0:
            msg = '{} version {} is less than upgrade min version {}'
            return False, msg.format(proto.type, proto.version, upgrade.min_version)
    if upgrade.max_strict:
        if rpm.compare_versions(proto.version, upgrade.max_version) >= 0:
            msg = '{} version {} is more than or equal to upgrade max version {}'
            return False, msg.format(proto.type, proto.version, upgrade.max_version)
    else:
        if rpm.compare_versions(proto.version, upgrade.max_version) > 0:
            msg = '{} version {} is more than upgrade max version {}'
            return False, msg.format(proto.type, proto.version, upgrade.max_version)
    return True, ''
Esempio n. 8
0
 def __new__(cls, *args, **kwargs):
     """
     Set PATH=None, if adcm version < `2021.03.12.16`. See ADCM-1439.
     This method is associated with the action of the `legacy_server_implementaion()` decorator.
     """
     wrapper = args[0]
     instance = super().__new__(cls)
     # !!! If you change the version, do not forget to change it in the component()
     # and component_list() methods of the Service class as well as in the comments to them
     if rpm.compare_versions(wrapper.adcm_version, '2021.03.12.16') < 0:
         instance.PATH = None
     return instance
Esempio n. 9
0
def upgrade_adcm(adcm, bundle):
    old_proto = adcm.prototype
    new_proto = Prototype.objects.get(type='adcm', bundle=bundle)
    if rpm.compare_versions(old_proto.version, new_proto.version) >= 0:
        msg = 'Current adcm version {} is more than or equal to upgrade version {}'
        err('UPGRADE_ERROR', msg.format(old_proto.version, new_proto.version))
    with transaction.atomic():
        adcm.prototype = new_proto
        adcm.save()
        switch_config(adcm, new_proto, old_proto)
    log.info('upgrade adcm OK from version %s to %s', old_proto.version,
             adcm.prototype.version)
    return adcm
Esempio n. 10
0
def check_upgrade_version(obj, upgrade):
    proto = obj.prototype
    # log.debug('check %s < %s > %s', upgrade.min_version, proto.version, upgrade.max_version)
    if upgrade.min_strict:
        if rpm.compare_versions(proto.version, upgrade.min_version) <= 0:
            msg = '{} version {} is less than or equal to upgrade min version {}'
            return False, msg.format(proto.type, proto.version,
                                     upgrade.min_version)
    else:
        if rpm.compare_versions(proto.version, upgrade.min_version) < 0:
            msg = '{} version {} is less than upgrade min version {}'
            return False, msg.format(proto.type, proto.version,
                                     upgrade.min_version)
    if upgrade.max_strict:
        if rpm.compare_versions(proto.version, upgrade.max_version) >= 0:
            msg = '{} version {} is more than or equal to upgrade max version {}'
            return False, msg.format(proto.type, proto.version,
                                     upgrade.max_version)
    else:
        if rpm.compare_versions(proto.version, upgrade.max_version) > 0:
            msg = '{} version {} is more than upgrade max version {}'
            return False, msg.format(proto.type, proto.version,
                                     upgrade.max_version)
    return True, ''
Esempio n. 11
0
def order_model_versions(model):
    items = []
    for obj in model.objects.all():
        items.append(obj)
    ver = ""
    count = 0
    for obj in sorted(
            items,
            key=functools.cmp_to_key(lambda obj1, obj2: rpm.compare_versions(
                obj1.version, obj2.version))):
        if ver != obj.version:
            count += 1
        # log.debug("MODEL %s count: %s, %s %s", model, count, obj.name, obj.version)
        obj.version_order = count
        ver = obj.version
    # Update all table in one time. That is much faster than one by one method
    model.objects.bulk_update(items, ['version_order'])
Esempio n. 12
0
def process_adcm():
    sp = StagePrototype.objects.get(type='adcm')
    adcm = ADCM.objects.filter()
    if adcm:
        old_proto = adcm[0].prototype
        new_proto = sp
        if old_proto.version == new_proto.version:
            log.debug('adcm vesrion %s, skip upgrade', old_proto.version)
        elif rpm.compare_versions(old_proto.version, new_proto.version) < 0:
            bundle = copy_stage('adcm', sp)
            upgrade_adcm(adcm[0], bundle)
        else:
            msg = 'Current adcm version {} is more than or equal to upgrade version {}'
            err('UPGRADE_ERROR',
                msg.format(old_proto.version, new_proto.version))
    else:
        bundle = copy_stage('adcm', sp)
        init_adcm(bundle)
Esempio n. 13
0
    def run(self, **args) -> "Task":
        with allure_step(f"Run action {self.name}"):

            if 'hc' in args:
                allure_attach_json(args.get('hc'), name="Hostcomponent map")

            if 'config' in args and 'config_diff' in args:
                raise TypeError(
                    "only one argument is expected 'config' or 'config_diff'")

            if 'config' not in args:
                args['config'] = self._get_config()

                if 'config_diff' in args:
                    config_diff = args.pop('config_diff')
                    for item in self.config['config']:
                        if item['type'] == 'group':
                            continue

                        key, subkey = item['name'], item['subname']
                        if subkey and subkey in config_diff.get(key, {}):
                            args['config'][key][subkey] = config_diff[key][
                                subkey]
                        elif not subkey and key in config_diff:
                            args['config'][key] = config_diff[key]
            # check backward compatibility for `verbose` option
            if rpm.compare_versions(self.adcm_version, '2021.02.04.13') >= 0:
                args.setdefault('verbose', False)
            elif 'verbose' in args:
                warnings.warn(
                    f"ADCM {self.adcm_version} doesn't support action "
                    f"argument 'verbose'. It will be skipped")
                args.pop('verbose')
            try:
                data = self._subcall("run", "create", **args)
            except ErrorMessage as error:
                if (getattr(error.error, 'title', '') == '409 Conflict'
                        and 'has issues' in getattr(error.error, '_data',
                                                    {}).get('desc', '')):
                    raise ActionHasIssues from error
                raise error
            return Task(self._api, task_id=data["id"])
Esempio n. 14
0
def _filter_adcm_versions_from_tags(adcm_tags: List[str],
                                    min_ver: str) -> Iterator[str]:
    """
    >>> this = _filter_adcm_versions_from_tags
    >>> list(this(["2021021506","2021030114","2021031007","latest","2021.05.26.12","2021.06.17.06"], "2019.03.01.14"))
    ['2021021506', '2021030114', '2021031007', '2021.05.26.12', '2021.06.17.06']
    >>> list(this(["2021021506","2021030114","2021031007","latest","2021.05.26.12","2021.06.17.06"], "2021.03.01.14"))
    ['2021030114', '2021031007', '2021.05.26.12', '2021.06.17.06']
    >>> list(this(["2021021506","2021030114","2021031007","latest","2021.05.26.12","2021.06.17.06"], "2021.05.26.12"))
    ['2021.05.26.12', '2021.06.17.06']
    >>> list(this(["2021021506","2021030114","2021031007","latest","2021.05.26.12","2021.06.17.06"], "2022.05.26.12"))
    []
    """
    return filter(
        lambda x: (tag := x.replace(".", "")) and (tag.isdigit())  # noqa: W503
        and
        (rpm.compare_versions(f"{tag[:4]}.{tag[4:6]}.{tag[6:8]}.{tag[8:10]}",
                              min_ver[:13]) != -1),  # noqa: W503
        adcm_tags,
    )
Esempio n. 15
0
 def test_compare_versions(self):
     test_versions = [
         ('~', 'aoi', -1),
         ('aoi', '~', 1),
         ('~', '~', 0),
         ('~', '~a', -1),
         ('1a', 'a1', 1),
         ('1a', '1b', -1),
         ('a1', 'a2', -1),
         ('1.2.3', '1.2.4', -1),
         ('1.02.4', '1.02a.4', 1),
         ('1.02a.4', '1.02b.4', -1),
         ('12345.6', '12345.6', 0),
         ('0.2.3', '1.2.4', -1),
         ('~1.2.3', '1.2.3', -1),
         ('1.2.3.a', '1.2.3.~alpha', 1)
     ]
     for a, b, exp in test_versions:
         res = rpm.compare_versions(a, b)
         self.assertEqual(exp, res, msg='Got {0} when comparing {1} to '
                                        '{2}'.format(res, a, b))
Esempio n. 16
0
def test_compare_versions(ver_a, ver_b, exp):
    res = rpm.compare_versions(ver_a, ver_b)
    assert exp == res
Esempio n. 17
0
def check_adcm_version_changed(before: str, after: str) -> None:
    """Check if 'after' version is more recent that 'before'"""
    if rpm.compare_versions(after, before) < 1:
        raise AssertionError(
            "ADCM version after upgrade is older or equal to the version before"
        )
Esempio n. 18
0
 def _check_min_version(self):
     if rpm.compare_versions(self._MIN_VERSION,
                             self._api.adcm_version) > -1:
         raise ADCMApiError(
             "The client supports ADCM versions newer than '{}'".format(
                 self._MIN_VERSION))
Esempio n. 19
0
 def wrapper(self, *args, **kwargs):
     # adcm_version >= turnover_versions
     if rpm.compare_versions(self.adcm_version, turnover_version) < 0:
         return oldfunc(self, *args, **kwargs)
     return func(self, *args, **kwargs)
Esempio n. 20
0
 def wrapper(*args, **kwargs):
     # The ADCM version must be greater than or equal to the method version
     # args[0].adcm_version >= version
     if rpm.compare_versions(args[0].adcm_version, version) < 0:
         raise TooOldServerVersion(func.__name__, version)
     return func(*args, **kwargs)
Esempio n. 21
0
def check_adcm_version(bundle):
    if not bundle.adcm_min_version:
        return
    if rpm.compare_versions(bundle.adcm_min_version, ADCM_VERSION) > 0:
        msg = 'This bundle required ADCM version equal to {} or newer.'
        err('BUNDLE_VERSION_ERROR', msg.format(bundle.adcm_min_version))
Esempio n. 22
0
def test_compare_versions(ver_a, ver_b, exp):
    res = rpm.compare_versions(ver_a, ver_b)
    assert exp == res
Esempio n. 23
0
 def rpm_cmp_reverse(obj1, obj2):
     return rpm.compare_versions(obj2.name, obj1.name)