Example #1
0
def validate_port_range_or_none(data, valid_values=None):
    """Validate data is a range of TCP/UDP port numbers

    :param data: The data to validate
    :param valid_values: Not used!
    :returns: None if data is an int between 0 and 65535, or two ints between 0
        and 65535 with a colon between them, otherwise a human readable message
        as to why data is invalid.
    """
    if data is None:
        return
    data = str(data)
    ports = data.split(':')
    if len(ports) > 2:
        msg = _("Port range must be two integers separated by a colon.")
        LOG.debug(msg)
        return msg
    for p in ports:
        if len(p) == 0:
            msg = _("Port range must be two integers separated by a colon.")
            LOG.debug(msg)
            return msg
        if not netutils.is_valid_port(p):
            msg = _("Invalid port: %s.") % p
            LOG.debug(msg)
            return msg
    if len(ports) > 1 and ports[0] > ports[1]:
        msg = _("First port in a port range must be lower than the second "
                "port.")
        LOG.debug(msg)
        return msg
Example #2
0
def drop_privileges(user=None, group=None):
    """Drop privileges to user/group privileges."""
    if user is None and group is None:
        return

    if os.geteuid() != 0:
        msg = _('Root permissions are required to drop privileges.')
        LOG.critical(msg)
        raise exceptions.FailToDropPrivilegesExit(msg)

    if group is not None:
        try:
            os.setgroups([])
        except OSError:
            msg = _('Failed to remove supplemental groups')
            LOG.critical(msg)
            raise exceptions.FailToDropPrivilegesExit(msg)
        setgid(group)

    if user is not None:
        setuid(user)

    LOG.info(_LI("Process runs with uid/gid: %(uid)s/%(gid)s"), {
        'uid': os.getuid(),
        'gid': os.getgid()
    })
Example #3
0
def validate_integer(data, valid_values=None):
    """This function validates if the data is an integer.

    It checks both number or string provided to validate it's an
    integer and returns a message with the error if it's not

    :param data: The string or number to validate as integer.
    :param valid_values: values to limit the 'data' to.
    :returns: None if data is an integer, otherwise a human readable message
        indicating why validation failed..
    """

    if valid_values is not None:
        msg = validate_values(data=data, valid_values=valid_values)
        if msg:
            return msg

    msg = _("'%s' is not an integer") % data
    try:
        fl_n = float(data)
        int_n = int(data)
    except (ValueError, TypeError, OverflowError):
        LOG.debug(msg)
        return msg

    # Fail test if non equal or boolean
    if fl_n != int_n:
        LOG.debug(msg)
        return msg
    elif isinstance(data, bool):
        msg = _("'%s' is not an integer:boolean") % data
        LOG.debug(msg)
        return msg
Example #4
0
def _verify_dict_keys(expected_keys, target_dict, strict=True):
    """Verify expected keys in a dictionary.

    :param expected_keys: A list of keys expected to be present.
    :param target_dict: The dictionary which should be verified.
    :param strict: Specifies whether additional keys are allowed to be present.
    :returns: None if the expected keys are found. Otherwise a human readable
        message indicating why the validation failed.
    """
    if not isinstance(target_dict, dict):
        msg = (_("Invalid input. '%(target_dict)s' must be a dictionary "
                 "with keys: %(expected_keys)s") % {
                     'target_dict': target_dict,
                     'expected_keys': expected_keys
                 })
        LOG.debug(msg)
        return msg

    expected_keys = set(expected_keys)
    provided_keys = set(target_dict.keys())

    predicate = expected_keys.__eq__ if strict else expected_keys.issubset

    if not predicate(provided_keys):
        msg = (_("Validation of dictionary's keys failed. "
                 "Expected keys: %(expected_keys)s "
                 "Provided keys: %(provided_keys)s") % {
                     'expected_keys': expected_keys,
                     'provided_keys': provided_keys
                 })
        LOG.debug(msg)
        return msg
Example #5
0
def validate_hostroutes(data, valid_values=None):
    """Validate a list of unique host route dicts.

    :param data: The data to validate. To be valid it must be a list like
        structure of host route dicts, each containing 'destination' and
        'nexthop' key values.
    :param valid_values: Not used!
    :returns: None if data is a valid list of unique host route dicts,
        otherwise a human readable message indicating why validation failed.
    """
    if not isinstance(data, list):
        msg = _("Invalid data format for hostroute: '%s'") % data
        LOG.debug(msg)
        return msg

    expected_keys = ['destination', 'nexthop']
    hostroutes = []
    for hostroute in data:
        msg = _verify_dict_keys(expected_keys, hostroute)
        if msg:
            return msg
        msg = validate_subnet(hostroute['destination'])
        if msg:
            return msg
        msg = validate_ip_address(hostroute['nexthop'])
        if msg:
            return msg
        if hostroute in hostroutes:
            msg = _("Duplicate hostroute '%s'") % hostroute
            LOG.debug(msg)
            return msg
        hostroutes.append(hostroute)
Example #6
0
def validate_nameservers(data, valid_values=None):
    """Validate a list of unique IP addresses.

    :param data: The data to validate.
    :param valid_values: Not used!
    :returns: None if data is a list of valid IP addresses, otherwise
        a human readable message is returned indicating why validation failed.
    """
    if not hasattr(data, '__iter__'):
        msg = _("Invalid data format for nameserver: '%s'") % data
        LOG.debug(msg)
        return msg

    hosts = []
    for host in data:
        # This must be an IP address only
        msg = validate_ip_address(host)
        if msg:
            msg = _("'%(host)s' is not a valid nameserver. %(msg)s") % {
                'host': host,
                'msg': msg
            }
            LOG.debug(msg)
            return msg
        if host in hosts:
            msg = _("Duplicate nameserver '%s'") % host
            LOG.debug(msg)
            return msg
        hosts.append(host)
Example #7
0
 def __init__(self,
              connection=None,
              timeout=None,
              schema_name=None,
              idl_class=None,
              idl_factory=None):
     self.idl = None
     self.is_running = True
     self.timeout = timeout
     self.txns = TransactionQueue(1)
     self.lock = threading.Lock()
     if idl_factory:
         if connection or schema_name:
             raise TypeError(
                 _('Connection: Takes either idl_factory, or '
                   'connection and schema_name. Both given'))
         self.idl_factory = idl_factory
     else:
         if not connection or not schema_name:
             raise TypeError(
                 _('Connection: Takes either idl_factory, or '
                   'connection and schema_name. Neither given'))
         self.idl_factory = self._idl_factory
         self.connection = connection
         self.schema_name = schema_name
         self.idl_class = idl_class or idl.Idl
         self._schema_filter = None
 def steamapi_refresh(self, uids=None):
   print("Updating")
   try:
       self.switcher.steam_skins = self.switcher.get_steam_skins()
       self.switcher.update_steamuids()
       self.switcher.get_steamapi_usersummary(uids)
       self.load_accounts()
   except Exception as e:
       self.tray_icon.showMessage(_("ERROR"), _("Something when wrong updating \n{0}").format(str(e)),
                                  self.switcher_logo)
Example #9
0
 def is_address_ready():
     try:
         addr_info = self.list(to=address)[0]
     except IndexError:
         raise AddressNotReady(
             address=address,
             reason=_('Address not present on interface'))
     if not addr_info['tentative']:
         return True
     if addr_info['dadfailed']:
         raise AddressNotReady(address=address,
                               reason=_('Duplicate address detected'))
Example #10
0
 def is_address_ready():
     try:
         addr_info = self.list(to=address)[0]
     except IndexError:
         raise AddressNotReady(
             address=address,
             reason=_('Address not present on interface'))
     if not addr_info['tentative']:
         return True
     if addr_info['dadfailed']:
         raise AddressNotReady(
             address=address, reason=_('Duplicate address detected'))
Example #11
0
  def steam_login(self, login_name: str, ignore_after_login_behavior=False):
    try:
      self.switcher.login_with(login_name)
    except PermissionError:
      self.tray_icon.showMessage(_("Permission error"), _("Are you running as administrator?"), self.switcher_logo)

    if not ignore_after_login_behavior:
      if self.switcher.settings["behavior_after_login"] == "close":
        self.exit_app()
      elif self.switcher.settings["behavior_after_login"] == "minimize":
        print("minimize to taskbar not implemented")
        self.hide()
      elif self.switcher.settings["behavior_after_login"] == "minimize_tray":
        self.hide()
Example #12
0
    def systemtray(self, parent=None):
        self.tray_menu = QMenu(parent)
        self.tray_icon = QSystemTrayIcon(QIcon("logo.png"))
        self.tray_icon.setToolTip(
            _("Program to quickly switch between steam accounts"))

        login_menu = QMenu(_("Login with"))
        self.tray_menu.addMenu(login_menu)

        def populate_login_menu():
            login_menu.clear()
            menu_accounts = []
            accounts, avatars = self.load_accounts(no_populate=True)
            if not accounts:
                login_menu.setEnabled(False)
            else:
                login_menu.setEnabled(True)
                for login_name, user in accounts:
                    menu_accounts.append(
                        QAction(user.get("steam_name", login_name),
                                self,
                                data=str(login_name)))
                    menu_accounts[-1].setToolTip(
                        "Login with {0}".format(login_name))
                    if self.switcher.settings["show_avatars"]:
                        menu_accounts[-1].setIcon(
                            QIcon(
                                avatars.get(login_name,
                                            self.switcher.default_avatar)))
                    menu_accounts[-1].triggered.connect(
                        lambda: self.steam_login(str(menu_accounts[-1].data()),
                                                 True))
                login_menu.addActions(menu_accounts)

        def activated(reason):
            self.tray_menu.addMenu(TopBar.settings_menu)
            self.tray_menu.addSeparator()
            self.tray_menu.addAction(_("Exit"), self.exit_app)
            self.tray_icon.setContextMenu(self.tray_menu)
            if reason == QSystemTrayIcon.Trigger:
                if self.isVisible():
                    self.hide()
                else:
                    self.show()
            else:
                populate_login_menu()

        self.tray_icon.activated.connect(activated)
    def __init__(self, cmd, run_as_root=False, respawn_interval=None,
                 namespace=None, log_output=False, die_on_error=False):
        """Constructor.

        :param cmd: The list of command arguments to invoke.
        :param run_as_root: The process should run with elevated privileges.
        :param respawn_interval: Optional, the interval in seconds to wait
               to respawn after unexpected process death. Respawn will
               only be attempted if a value of 0 or greater is provided.
        :param namespace: Optional, start the command in the specified
               namespace.
        :param log_output: Optional, also log received output.
        :param die_on_error: Optional, kills the process on stderr output.
        """
        self.cmd_without_namespace = cmd
        self._cmd = ip_lib.add_namespace_to_cmd(cmd, namespace)
        self.run_as_root = run_as_root
        if respawn_interval is not None and respawn_interval < 0:
            raise ValueError(_('respawn_interval must be >= 0 if provided.'))
        self.respawn_interval = respawn_interval
        self._process = None
        self._is_running = False
        self._kill_event = None
        self._reset_queues()
        self._watchers = []
        self.log_output = log_output
        self.die_on_error = die_on_error
    def __init__(self,
                 cmd,
                 run_as_root=False,
                 respawn_interval=None,
                 namespace=None,
                 log_output=False,
                 die_on_error=False):
        """Constructor.

        :param cmd: The list of command arguments to invoke.
        :param run_as_root: The process should run with elevated privileges.
        :param respawn_interval: Optional, the interval in seconds to wait
               to respawn after unexpected process death. Respawn will
               only be attempted if a value of 0 or greater is provided.
        :param namespace: Optional, start the command in the specified
               namespace.
        :param log_output: Optional, also log received output.
        :param die_on_error: Optional, kills the process on stderr output.
        """
        self.cmd_without_namespace = cmd
        self._cmd = ip_lib.add_namespace_to_cmd(cmd, namespace)
        self.run_as_root = run_as_root
        if respawn_interval is not None and respawn_interval < 0:
            raise ValueError(_('respawn_interval must be >= 0 if provided.'))
        self.respawn_interval = respawn_interval
        self._process = None
        self._is_running = False
        self._kill_event = None
        self._reset_queues()
        self._watchers = []
        self.log_output = log_output
        self.die_on_error = die_on_error
Example #15
0
class Wise2cException(Exception):
    """Base Wise2c Exception.

    To correctly use this class, inherit from it and define
    a 'message' property. That message will get printf'd
    with the keyword arguments provided to the constructor.
    """
    message = _("An unknown exception occurred.")

    def __init__(self, **kwargs):
        try:
            super(Wise2cException, self).__init__(self.message % kwargs)
            self.msg = self.message % kwargs
        except Exception:
            with excutils.save_and_reraise_exception() as ctxt:
                if not self.use_fatal_exceptions():
                    ctxt.reraise = False
                    # at least get the core message out if something happened
                    super(Wise2cException, self).__init__(self.message)

    if six.PY2:

        def __unicode__(self):
            return unicode(self.msg)

    def __str__(self):
        return self.msg

    def use_fatal_exceptions(self):
        return False
Example #16
0
    def wait_until_address_ready(self, address, wait_time=30):
        """Wait until an address is no longer marked 'tentative'

        raises AddressNotReady if times out or address not present on interface
        """
        def is_address_ready():
            try:
                addr_info = self.list(to=address)[0]
            except IndexError:
                raise AddressNotReady(
                    address=address,
                    reason=_('Address not present on interface'))
            if not addr_info['tentative']:
                return True
            if addr_info['dadfailed']:
                raise AddressNotReady(address=address,
                                      reason=_('Duplicate address detected'))

        errmsg = _("Exceeded %s second limit waiting for "
                   "address to leave the tentative state.") % wait_time
        common.wait_until_true(is_address_ready,
                               timeout=wait_time,
                               sleep=0.20,
                               exception=AddressNotReady(address=address,
                                                         reason=errmsg))
Example #17
0
    def add_rule(self,
                 chain,
                 rule,
                 wrap=True,
                 top=False,
                 tag=None,
                 comment=None):
        """Add a rule to the table.

        This is just like what you'd feed to iptables, just without
        the '-A <chain name>' bit at the start.

        However, if you need to jump to one of your wrapped chains,
        prepend its name with a '$' which will ensure the wrapping
        is applied correctly.

        """
        chain = get_chain_name(chain, wrap)
        if wrap and chain not in self.chains:
            raise LookupError(_('Unknown chain: %r') % chain)

        if '$' in rule:
            rule = ' '.join(
                self._wrap_target_chain(e, wrap) for e in rule.split(' '))

        self.rules.append(
            IptablesRule(chain, rule, wrap, top, self.wrap_name, tag, comment))
Example #18
0
def _validate_list_of_items(item_validator, data, *args, **kwargs):
    if not isinstance(data, list):
        msg = _("'%s' is not a list") % data
        return msg

    dups = _collect_duplicates(data)

    if dups:
        msg = _("Duplicate items in the list: '%s'") % ', '.join(
            [str(d) for d in dups])
        return msg

    for item in data:
        msg = item_validator(item, *args, **kwargs)
        if msg:
            return msg
Example #19
0
    def deprecated(self, msg, *args, **kwargs):
        """Call this method when a deprecated feature is used.

        If the system is configured for fatal deprecations then the message
        is logged at the 'critical' level and :class:`DeprecatedConfig` will
        be raised.

        Otherwise, the message will be logged (once) at the 'warn' level.

        :raises: :class:`DeprecatedConfig` if the system is configured for
                 fatal deprecations.

        """
        stdmsg = _("Deprecated: %s") % msg
        if CONF.fatal_deprecations:
            self.critical(stdmsg, *args, **kwargs)
            raise DeprecatedConfig(msg=stdmsg)

        # Using a list because a tuple with dict can't be stored in a set.
        sent_args = self._deprecated_messages_sent.setdefault(msg, list())

        if args in sent_args:
            # Already logged this message, so don't log it again.
            return

        sent_args.append(args)
        self.warn(stdmsg, *args, **kwargs)
Example #20
0
def validate_ip_pools(data, valid_values=None):
    """Validate that start and end IP addresses are present.

    In addition to this the IP addresses will also be validated.

    :param data: The data to validate. Must be a list-like structure of
        IP pool dicts that each have a 'start' and 'end' key value.
    :param valid_values: Not used!
    :returns: None if data is a valid list of IP pools, otherwise a message
        indicating why the data is invalid.
    """
    if not isinstance(data, list):
        msg = _("Invalid data format for IP pool: '%s'") % data
        LOG.debug(msg)
        return msg

    expected_keys = ['start', 'end']
    for ip_pool in data:
        msg = _verify_dict_keys(expected_keys, ip_pool)
        if msg:
            return msg
        for k in expected_keys:
            msg = validate_ip_address(ip_pool[k])
            if msg:
                return msg
Example #21
0
def validate_values(data, valid_values=None, valid_values_display=None):
    """Validate that the provided 'data' is within 'valid_values'.

    :param data: The data to check within valid_values.
    :param valid_values: A collection of values that 'data' must be in to be
        valid. The collection can be any type that supports the 'in' operation.
    :param valid_values_display: A string to display that describes the valid
        values. This string is only displayed when an invalid value is
        encountered.
        If no string is provided, the string "valid_values" will be used.
    :returns: The message to return if data not in valid_values.
    :raises: TypeError if the values for 'data' or 'valid_values' are not
        compatible for comparison or doesn't have __contains__.
        If TypeError is raised this is considered a programming error and the
        inputs (data) and (valid_values) must be checked so this is never
        raised on validation.
    """

    # If valid_values is not specified we don't check against it.
    if valid_values is None:
        return

    # Check if we can use 'in' to find membership of data in valid_values
    contains = getattr(valid_values, "__contains__", None)
    if callable(contains):
        try:
            if data not in valid_values:
                valid_values_display = valid_values_display or 'valid_values'
                msg = (_("%(data)s is not in %(valid_values)s") % {
                    'data': data,
                    'valid_values': valid_values_display
                })
                LOG.debug(msg)
                return msg
        except TypeError:
            # This is a programming error
            msg = (_("'data' of type '%(typedata)s' and 'valid_values'"
                     "of type '%(typevalues)s' are not "
                     "compatible for comparison") % {
                         'typedata': type(data),
                         'typevalues': type(valid_values)
                     })
            raise TypeError(msg)
    else:
        # This is a programming error
        msg = (_("'valid_values' does not support membership operations"))
        raise TypeError(msg)
Example #22
0
def validate_subports(data, valid_values=None):
    """Validate data is a list of subnet port dicts.

    :param data: The data to validate.
    :param valid_values: Not used!
    :returns: None if data is a list of subport dicts each with a unique valid
        port_id, segmentation_id and segmentation_type. Otherwise a human
        readable message is returned indicating why the data is invalid.
    """
    if not isinstance(data, list):
        msg = _("Invalid data format for subports: '%s' is not a list") % data
        LOG.debug(msg)
        return msg

    subport_ids = set()
    segmentations = collections.defaultdict(set)
    for subport in data:
        if not isinstance(subport, dict):
            msg = _("Invalid data format for subport: "
                    "'%s' is not a dict") % subport
            LOG.debug(msg)
            return msg

        # Expect a non duplicated and valid port_id for the subport
        if 'port_id' not in subport:
            msg = _("A valid port UUID must be specified")
            LOG.debug(msg)
            return msg
        elif validate_uuid(subport["port_id"]):
            msg = _("Invalid UUID for subport: '%s'") % subport["port_id"]
            return msg
        elif subport["port_id"] in subport_ids:
            msg = _("Non unique UUID for subport: '%s'") % subport["port_id"]
            return msg
        subport_ids.add(subport["port_id"])

        # Validate that both segmentation ID and segmentation type are
        # specified, and that the client does not duplicate segmentation
        # IDs (unless it is explicitly asked to inherit segmentation
        # details from the underlying subport's network).
        segmentation_type = subport.get("segmentation_type")
        if segmentation_type == 'inherit':
            return
        segmentation_id = subport.get("segmentation_id")
        if (not segmentation_type or not segmentation_id) and len(subport) > 1:
            msg = _("Invalid subport details '%s': missing segmentation "
                    "information. Must specify both segmentation_id and "
                    "segmentation_type") % subport
            LOG.debug(msg)
            return msg
        if segmentation_id in segmentations.get(segmentation_type, []):
            msg = _("Segmentation ID '%(seg_id)s' for '%(subport)s' is not "
                    "unique") % {
                        "seg_id": segmentation_id,
                        "subport": subport["port_id"]
                    }
            LOG.debug(msg)
            return msg
        if segmentation_id:
            segmentations[segmentation_type].add(segmentation_id)
 def button_enabled():
     num_selected = len(
         import_accounts_list.selectionModel().selectedRows())
     import_button.setText(
         _("Import {0} accounts").format(num_selected))
     if num_selected:
         import_button.setEnabled(True)
     else:
         import_button.setEnabled(False)
Example #24
0
def validate_ip_address(data, valid_values=None):
    """Validate data is an IP address.

    :param data: The data to validate.
    :param valid_values: Not used!
    :returns: None if data is an IP address, otherwise a human readable
        message indicating why data isn't an IP address.
    """
    msg = None
    try:
        # netaddr.core.ZEROFILL is only applicable to IPv4.
        # it will remove leading zeros from IPv4 address octets.
        ip = netaddr.IPAddress(validate_no_whitespace(data),
                               flags=netaddr.core.ZEROFILL)
        # The followings are quick checks for IPv6 (has ':') and
        # IPv4.  (has 3 periods like 'xx.xx.xx.xx')
        # NOTE(yamamoto): netaddr uses libraries provided by the underlying
        # platform to convert addresses.  For example, inet_aton(3).
        # Some platforms, including NetBSD and OS X, have inet_aton
        # implementation which accepts more varying forms of addresses than
        # we want to accept here.  The following check is to reject such
        # addresses.  For Example:
        #   >>> netaddr.IPAddress('1' * 59)
        #   IPAddress('199.28.113.199')
        #   >>> netaddr.IPAddress(str(int('1' * 59) & 0xffffffff))
        #   IPAddress('199.28.113.199')
        #   >>>
        if ':' not in data and data.count('.') != 3:
            msg = _("'%s' is not a valid IP address") % data
        # A leading '0' in IPv4 address may be interpreted as an octal number,
        # e.g. 011 octal is 9 decimal. Since there is no standard saying
        # whether IP address with leading '0's should be interpreted as octal
        # or decimal, hence we reject leading '0's to avoid ambiguity.
        elif ip.version == 4 and str(ip) != data:
            msg = _("'%(data)s' is not an accepted IP address, "
                    "'%(ip)s' is recommended") % {
                        "data": data,
                        "ip": ip
                    }
    except Exception:
        msg = _("'%s' is not a valid IP address") % data
    if msg:
        LOG.debug(msg)
    return msg
Example #25
0
def validate_non_negative(data, valid_values=None):
    """Validate data is a positive int.

    :param data: The data to validate
    :param valid_values: Not used!
    :returns: None if data is an int and is positive, otherwise a human
        readable message as to why data is invalid.
    """
    try:
        data = int(data)
    except (ValueError, TypeError):
        msg = _("'%s' is not an integer") % data
        LOG.debug(msg)
        return msg

    if data < 0:
        msg = _("'%s' should be non-negative") % data
        LOG.debug(msg)
        return msg
Example #26
0
def main():
    config.init(sys.argv[1:])
    config.setup_logging()
    n_utils.log_opt_values(LOG)
    if not CONF.config_file:
        sys.exit(
            _("ERROR: Unable to find configuration file via the default"
              " search paths (~/.neutron/, ~/, /etc/neutron/, /etc/) and"
              " the '--config-file' option!"))
    run()
Example #27
0
    def show_rightclick_menu(self):
        """

        :type self: SteamAccountSwitcherGui
        """

        right_menu = QMenu()

        selected = self.accounts_list.currentItem()
        if not self.accounts_list.selectedItems():
            add_account_action = QAction(_("Add account"), self)
            add_account_action.triggered.connect(
                lambda: self.account_dialog(True))
            right_menu.addAction(add_account_action)
            right_menu.exec_(QCursor.pos())
            return
        login_name = selected.data(5)
        account = self.switcher.settings["users"].get(login_name, {})

        login_action = QAction(_("Login"), self)
        edit_action = QAction(_("Edit"), self)
        delete_action = QAction(_("Delete"), self)
        open_profile_action = QAction(_("Steam profile"), self)
        steampage_menu = QMenu(_("Steam profile"), self)

        edit_action.setIcon(QIcon.fromTheme("document-edit"))
        delete_action.setIcon(QIcon.fromTheme("edit-delete"))
        open_profile_action.setIcon(QIcon.fromTheme("internet-web-browser"))

        right_menu.addActions([login_action, edit_action, delete_action])
        right_menu.addSeparator()
        right_menu.addAction(open_profile_action)
        right_menu.addMenu(steampage_menu)

        login_action.triggered.connect(lambda: self.steam_login(login_name))
        edit_action.triggered.connect(lambda: self.account_dialog())
        delete_action.triggered.connect(
            lambda: self.remove_account(login_name))

        open_profile_action.triggered.connect(
            lambda: self.open_steam_profile(account))

        steampage_menu.triggered.connect(
            lambda: self.open_steam_profile(account))

        steampage_menu_actions = QActionGroup(steampage_menu)
        steampage_menu_inventory = QAction(_('Inventory'),
                                           steampage_menu_actions,
                                           checkable=True,
                                           data="nothing")

        open_profile_action.setDisabled(True)
        if account.get("steam_user", {}).get("profileurl"):
            open_profile_action.setEnabled(True)
            steampage_menu.addActions([steampage_menu_inventory])

        if self.accounts_list.selectedItems():
            right_menu.exec_(QCursor.pos())
Example #28
0
def validate_dict(data, key_specs=None):
    """Validate data is a dict optionally containing a specific set of keys.

    :param data: The data to validate.
    :param key_specs: The optional list of keys that must be contained in
        data.
    :returns: None if data is a dict and (optionally) contains only key_specs.
        Otherwise a human readable message is returned indicating why data is
        not valid.
    """
    if not isinstance(data, dict):
        msg = _("'%s' is not a dictionary") % data
        LOG.debug(msg)
        return msg
    # Do not perform any further validation, if no constraints are supplied
    if not key_specs:
        return

    # Check whether all required keys are present
    required_keys = [
        key for key, spec in key_specs.items() if spec.get('required')
    ]

    if required_keys:
        msg = _verify_dict_keys(required_keys, data, False)
        if msg:
            return msg

    # Check whether unexpected keys are supplied in data
    unexpected_keys = [key for key in data if key not in key_specs]
    if unexpected_keys:
        msg = _("Unexpected keys supplied: %s") % ', '.join(unexpected_keys)
        LOG.debug(msg)
        return msg

    # Perform validation and conversion of all values
    # according to the specifications.
    for key, key_validator in [(k, v) for k, v in key_specs.items()
                               if k in data]:
        msg = _validate_dict_item(key, key_validator, data)
        if msg:
            return msg
Example #29
0
def execute(cmd,
            process_input=None,
            addl_env=None,
            check_exit_code=True,
            return_stderr=False,
            log_fail_as_error=True,
            extra_ok_codes=None,
            run_as_root=False):
    try:
        if process_input is not None:
            _process_input = encodeutils.to_utf8(process_input)
        else:
            _process_input = None

        # if run_as_root and cfg.CONF.AGENT.root_helper_daemon:
        if False:
            returncode, _stdout, _stderr = (execute_rootwrap_daemon(
                cmd, process_input, addl_env))
        else:
            obj, cmd = create_process(cmd,
                                      run_as_root=run_as_root,
                                      addl_env=addl_env)
            _stdout, _stderr = obj.communicate(_process_input)
            returncode = obj.returncode
            obj.stdin.close()
        _stdout = common.safe_decode_utf8(_stdout)
        _stderr = common.safe_decode_utf8(_stderr)

        extra_ok_codes = extra_ok_codes or []
        if returncode and returncode not in extra_ok_codes:
            msg = _("Exit code: %(returncode)d; "
                    "Stdin: %(stdin)s; "
                    "Stdout: %(stdout)s; "
                    "Stderr: %(stderr)s") % {
                        'returncode': returncode,
                        'stdin': process_input or '',
                        'stdout': _stdout,
                        'stderr': _stderr
                    }

            if log_fail_as_error:
                LOG.error(msg)
            if check_exit_code:
                raise RuntimeError(msg)
        else:
            LOG.debug("Exit code: %d", returncode)

    finally:
        # NOTE(termie): this appears to be necessary to let the subprocess
        #               call clean something up in between calls, without
        #               it two execute calls in a row hangs the second one
        greenthread.sleep(0)

    return (_stdout, _stderr) if return_stderr else _stdout
Example #30
0
def setuid(user_id_or_name):
    try:
        new_uid = int(user_id_or_name)
    except (TypeError, ValueError):
        new_uid = pwd.getpwnam(user_id_or_name).pw_uid
    if new_uid != 0:
        try:
            os.setuid(new_uid)
        except OSError:
            msg = _('Failed to set uid %s') % new_uid
            LOG.critical(msg)
            raise exceptions.FailToDropPrivilegesExit(msg)
Example #31
0
def setgid(group_id_or_name):
    try:
        new_gid = int(group_id_or_name)
    except (TypeError, ValueError):
        new_gid = grp.getgrnam(group_id_or_name).gr_gid
    if new_gid != 0:
        try:
            os.setgid(new_gid)
        except OSError:
            msg = _('Failed to set gid %s') % new_gid
            LOG.critical(msg)
            raise exceptions.FailToDropPrivilegesExit(msg)
Example #32
0
def validate_uuid(data, valid_values=None):
    """Validate data is UUID like.

    :param data: The data to validate.
    :param valid_values: Not used!
    :returns: None if data is UUID like in form, otherwise a human readable
        message indicating why data is invalid.
    """
    if not uuidutils.is_uuid_like(data):
        msg = _("'%s' is not a valid UUID") % data
        LOG.debug(msg)
        return msg
Example #33
0
def setgid(group_id_or_name):
    try:
        new_gid = int(group_id_or_name)
    except (TypeError, ValueError):
        new_gid = grp.getgrnam(group_id_or_name).gr_gid
    if new_gid != 0:
        try:
            os.setgid(new_gid)
        except OSError:
            msg = _('Failed to set gid %s') % new_gid
            LOG.critical(msg)
            raise exceptions.FailToDropPrivilegesExit(msg)
 def defer_apply(self):
     """Defer apply context."""
     self.defer_apply_on()
     try:
         yield
     finally:
         try:
             self.defer_apply_off()
         except Exception:
             msg = _('Failure applying iptables rules')
             LOG.exception(msg)
             raise common.IpTablesApplyException(msg)
Example #35
0
def setuid(user_id_or_name):
    try:
        new_uid = int(user_id_or_name)
    except (TypeError, ValueError):
        new_uid = pwd.getpwnam(user_id_or_name).pw_uid
    if new_uid != 0:
        try:
            os.setuid(new_uid)
        except OSError:
            msg = _('Failed to set uid %s') % new_uid
            LOG.critical(msg)
            raise exceptions.FailToDropPrivilegesExit(msg)
Example #36
0
def validate_string(data, max_len=None):
    """Validate data is a string object optionally capping it length.

    :param data: The data to validate.
    :param max_len: An optional cap on the length of the string.
    :returns: None if the data is a valid string type and (optionally) within
        the given max_len. Otherwise a human readable message indicating why
        the data is invalid.
    """
    if not isinstance(data, six.string_types):
        msg = _("'%s' is not a valid string") % data
        LOG.debug(msg)
        return msg

    if max_len is not None and len(data) > max_len:
        msg = (_("'%(data)s' exceeds maximum length of %(max_len)s") % {
            'data': data,
            'max_len': max_len
        })
        LOG.debug(msg)
        return msg
    def start(self, block=False):
        """Launch a process and monitor it asynchronously.

        :param block: Block until the process has started.
        :raises eventlet.timeout.Timeout if blocking is True and the process
                did not start in time.
        """
        LOG.debug('Launching async process [%s].', self.cmd)
        if self._is_running:
            raise AsyncProcessException(_('Process is already started'))
        else:
            self._spawn()

        if block:
            common_utils.wait_until_true(self.is_active)
Example #38
0
def drop_privileges(user=None, group=None):
    """Drop privileges to user/group privileges."""
    if user is None and group is None:
        return

    if os.geteuid() != 0:
        msg = _('Root permissions are required to drop privileges.')
        LOG.critical(msg)
        raise exceptions.FailToDropPrivilegesExit(msg)

    if group is not None:
        try:
            os.setgroups([])
        except OSError:
            msg = _('Failed to remove supplemental groups')
            LOG.critical(msg)
            raise exceptions.FailToDropPrivilegesExit(msg)
        setgid(group)

    if user is not None:
        setuid(user)

    LOG.info(_LI("Process runs with uid/gid: %(uid)s/%(gid)s"),
             {'uid': os.getuid(), 'gid': os.getgid()})
Example #39
0
def execute(cmd, process_input=None, addl_env=None,
            check_exit_code=True, return_stderr=False, log_fail_as_error=True,
            extra_ok_codes=None, run_as_root=False):
    try:
        if process_input is not None:
            _process_input = encodeutils.to_utf8(process_input)
        else:
            _process_input = None

        # if run_as_root and cfg.CONF.AGENT.root_helper_daemon:
        if False:
            returncode, _stdout, _stderr = (
                execute_rootwrap_daemon(cmd, process_input, addl_env))
        else:
            obj, cmd = create_process(cmd, run_as_root=run_as_root,
                                      addl_env=addl_env)
            _stdout, _stderr = obj.communicate(_process_input)
            returncode = obj.returncode
            obj.stdin.close()
        _stdout = common.safe_decode_utf8(_stdout)
        _stderr = common.safe_decode_utf8(_stderr)

        extra_ok_codes = extra_ok_codes or []
        if returncode and returncode not in extra_ok_codes:
            msg = _("Exit code: %(returncode)d; "
                    "Stdin: %(stdin)s; "
                    "Stdout: %(stdout)s; "
                    "Stderr: %(stderr)s") % {
                        'returncode': returncode,
                        'stdin': process_input or '',
                        'stdout': _stdout,
                        'stderr': _stderr}

            if log_fail_as_error:
                LOG.error(msg)
            if check_exit_code:
                raise RuntimeError(msg)
        else:
            LOG.debug("Exit code: %d", returncode)

    finally:
        # NOTE(termie): this appears to be necessary to let the subprocess
        #               call clean something up in between calls, without
        #               it two execute calls in a row hangs the second one
        greenthread.sleep(0)

    return (_stdout, _stderr) if return_stderr else _stdout
    def stop(self, block=False, kill_signal=signal.SIGKILL):
        """Halt the process and watcher threads.

        :param block: Block until the process has stopped.
        :param kill_signal: Number of signal that will be sent to the process
                            when terminating the process
        :raises eventlet.timeout.Timeout if blocking is True and the process
                did not stop in time.
        """
        if self._is_running:
            LOG.debug('Halting async process [%s].', self.cmd)
            self._kill(kill_signal)
        else:
            raise AsyncProcessException(_('Process is not running.'))

        if block:
            common_utils.wait_until_true(lambda: not self.is_active())
Example #41
0
    def wait_until_address_ready(self, address, wait_time=30):
        """Wait until an address is no longer marked 'tentative'

        raises AddressNotReady if times out or address not present on interface
        """
        def is_address_ready():
            try:
                addr_info = self.list(to=address)[0]
            except IndexError:
                raise AddressNotReady(
                    address=address,
                    reason=_('Address not present on interface'))
            if not addr_info['tentative']:
                return True
            if addr_info['dadfailed']:
                raise AddressNotReady(
                    address=address, reason=_('Duplicate address detected'))
        errmsg = _("Exceeded %s second limit waiting for "
                   "address to leave the tentative state.") % wait_time
        common.wait_until_true(
            is_address_ready, timeout=wait_time, sleep=0.20,
            exception=AddressNotReady(address=address, reason=errmsg))
    def add_rule(self, chain, rule, wrap=True, top=False, tag=None,
                 comment=None):
        """Add a rule to the table.

        This is just like what you'd feed to iptables, just without
        the '-A <chain name>' bit at the start.

        However, if you need to jump to one of your wrapped chains,
        prepend its name with a '$' which will ensure the wrapping
        is applied correctly.

        """
        chain = get_chain_name(chain, wrap)
        if wrap and chain not in self.chains:
            raise LookupError(_('Unknown chain: %r') % chain)

        if '$' in rule:
            rule = ' '.join(
                self._wrap_target_chain(e, wrap) for e in rule.split(' '))

        self.rules.append(IptablesRule(chain, rule, wrap, top, self.wrap_name,
                                       tag, comment))
Example #43
0
def _find_facility_from_conf():
    facility_names = logging.handlers.SysLogHandler.facility_names
    facility = getattr(logging.handlers.SysLogHandler,
                       CONF.syslog_log_facility,
                       None)

    if facility is None and CONF.syslog_log_facility in facility_names:
        facility = facility_names.get(CONF.syslog_log_facility)

    if facility is None:
        valid_facilities = facility_names.keys()
        consts = ['LOG_AUTH', 'LOG_AUTHPRIV', 'LOG_CRON', 'LOG_DAEMON',
                  'LOG_FTP', 'LOG_KERN', 'LOG_LPR', 'LOG_MAIL', 'LOG_NEWS',
                  'LOG_AUTH', 'LOG_SYSLOG', 'LOG_USER', 'LOG_UUCP',
                  'LOG_LOCAL0', 'LOG_LOCAL1', 'LOG_LOCAL2', 'LOG_LOCAL3',
                  'LOG_LOCAL4', 'LOG_LOCAL5', 'LOG_LOCAL6', 'LOG_LOCAL7']
        valid_facilities.extend(consts)
        raise TypeError(_('syslog facility must be one of: %s') %
                        ', '.join("'%s'" % fac
                                  for fac in valid_facilities))

    return facility
Example #44
0
    #
    # These variables default to respectively:
    #
    #  import oslo_log
    #  oslo_log._options.DEFAULT_LOG_LEVELS
    #  oslo_log._options.log_opts[0].default
    #

    extra_log_level_defaults = [
        'dogpile=INFO',
        'routes=INFO'
        ]

    logging.set_defaults(
        default_log_levels=logging.get_default_log_levels() +
        extra_log_level_defaults)

    # Required setup based on configuration and domain
    logging.setup(CONF, DOMAIN)


if __name__ == '__main__':
    prepare()
    # NOTE: These examples use Oslo i18n marker functions

    LOG.info(_LI("Welcome to Oslo Logging"))
    LOG.debug("A debugging message")  # Debug messages are not translated
    LOG.warning(_LW("A warning occured"))
    LOG.error(_LE("An error occured"))
    LOG.exception(_("An Exception occured"))
Example #45
0
from oslo_config import cfg
from oslo_log import log as logging
from oslo_log import versionutils
import six

from _i18n import _, _LE, _LI, _LW
from linux import ip_lib
from linux import utils
import common

LOG = logging.getLogger(__name__)

OPTS = [
    cfg.StrOpt('ovs_integration_bridge',
               default='br-int',
               help=_('Name of Open vSwitch bridge to use')),
    cfg.BoolOpt('ovs_use_veth',
                default=False,
                help=_('Uses veth for an OVS interface or not. '
                       'Support kernels with limited namespace support '
                       '(e.g. RHEL 6.5) so long as ovs_use_veth is set to '
                       'True.')),
    cfg.IntOpt('network_device_mtu',
               deprecated_for_removal=True,
               help=_('MTU setting for device. This option will be removed in '
                      'Newton. Please use the system-wide segment_mtu setting '
                      'which the agents will take into account when wiring '
                      'VIFs.')),
]

from oslo_log import log as logging
from oslo_utils import fileutils
import six

from _i18n import _, _LW, _LE
from linux import ip_lib
from linux import utils
import common as common_utils

LOG = logging.getLogger(__name__)


OPTS = [
    cfg.StrOpt('external_pids',
               default='$state_path/external/pids',
               help=_('Location to store child pid files')),
]


cfg.CONF.register_opts(OPTS)
common_utils.register_process_monitor_opts(cfg.CONF)


@six.add_metaclass(abc.ABCMeta)
class MonitoredProcess(object):
    @abc.abstractproperty
    def active(self):
        """Boolean representing the running state of the process."""

    @abc.abstractmethod
    def enable(self):
Example #47
0
    #  import oslo_log
    #  oslo_log._options.DEFAULT_LOG_LEVELS
    #  oslo_log._options.log_opts[0].default
    #

    extra_log_level_defaults = [
        'dogpile=INFO',
        'routes=INFO'
        ]

    logging.set_defaults(
        default_log_levels=logging.get_default_log_levels() +
        extra_log_level_defaults)

    # Required setup based on configuration and domain
    logging.setup(CONF, DOMAIN)


if __name__ == '__main__':
    prepare()
    # NOTE: These examples use Oslo i18n marker functions

    LOG.info(_LI("Welcome to Oslo Logging"))
    LOG.debug("A debugging message")  # Debug messages are not translated
    LOG.warning(_LW("A warning occurred"))
    LOG.error(_LE("An error occurred"))
    try:
        raise Exception(_("This is exceptional"))
    except Exception:
        LOG.exception(_LE("An Exception occurred"))
Example #48
0
DEFAULT_NETWORK_MTU = 1500
IPV6_MIN_MTU = 1280
SYNCHRONIZED_PREFIX = 'wise2c-'
TAP_DEVICE_PREFIX = 'tap'
IP_VERSION_4 = 4
IP_VERSION_6 = 6
IPv4_ANY = '0.0.0.0/0'
IPv6_ANY = '::/0'
IP_ANY = {IP_VERSION_4: IPv4_ANY, IP_VERSION_6: IPv6_ANY}
# Linux interface max length
DEVICE_NAME_MAX_LEN = 15

PROCESS_MONITOR_OPTS = [
    cfg.StrOpt('check_child_processes_action', default='respawn',
               choices=['respawn', 'exit'],
               help=_('Action to be executed when a child process dies')),
    cfg.IntOpt('check_child_processes_interval', default=60,
               help=_('Interval between checks of child process liveness '
                      '(seconds), use 0 to disable')),
]

def wait_until_true(predicate, timeout=60, sleep=1, exception=None):
    """
    Wait until callable predicate is evaluated as True

    :param predicate: Callable deciding whether waiting should continue.
    Best practice is to instantiate predicate with functools.partial()
    :param timeout: Timeout in seconds how long should function wait.
    :param sleep: Polling interval for results in seconds.
    :param exception: Exception class for eventlet.Timeout.
    (see doc for eventlet.Timeout for more information)
Example #49
0
import netaddr
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import excutils
import six

from _i18n import _, _LE
import utils
import common

LOG = logging.getLogger(__name__)

OPTS = [
    cfg.BoolOpt('ip_lib_force_root',
                default=False,
                help=_('Force ip_lib calls to use the root helper')),
]


LOOPBACK_DEVNAME = 'lo'

SYS_NET_PATH = '/sys/class/net'
DEFAULT_GW_PATTERN = re.compile(r"via (\S+)")
METRIC_PATTERN = re.compile(r"metric (\S+)")
DEVICE_NAME_PATTERN = re.compile(r"(\d+?): (\S+?):.*")


def remove_interface_suffix(interface):
    """Remove a possible "<if>@<endpoint>" suffix from an interface' name.

    This suffix can appear in some kernel versions, and intends on specifying,