Ejemplo n.º 1
0
    def PoolAttach(self, pools, quantity, proxy_options, locale, sender=None):
        self.ensure_registered()
        pools = dbus_utils.dbus_to_python(pools, expected_type=list)
        quantity = dbus_utils.dbus_to_python(quantity, expected_type=int)
        proxy_options = dbus_utils.dbus_to_python(proxy_options,
                                                  expected_type=dict)

        locale = dbus_utils.dbus_to_python(locale, expected_type=str)
        Locale.set(locale)

        if quantity < 1:
            raise dbus.DBusException("Quantity must be a positive number.")

        cp = self.build_uep(proxy_options, proxy_only=True)
        attach_service = AttachService(cp)

        try:
            results = []
            for pool in pools:
                resp = attach_service.attach_pool(pool, quantity)
                results.append(json.dumps(resp))
        except Exception as e:
            log.exception(e)
            raise dbus.DBusException(str(e))

        # TODO Likely should only call this if something is actually attached
        entcertlib.EntCertActionInvoker().update()
        return results
Ejemplo n.º 2
0
    def ImagePush(self, image, pulp, satellite, verify_ssl, url, username,
                  password, activation_key, repo_id, registry_type, sign_by,
                  gnupghome, insecure, anonymous):
        p = Push()
        args = self.Args()
        args.image = image
        args.pulp = pulp
        args.satellite = satellite
        args.verify_ssl = verify_ssl
        args.insecure = insecure
        args.anonymous = anonymous
        args.url = None if not url else url
        args.username = None if not username else username
        args.password = None if not password else password
        args.activation_key = activation_key
        args.repo_id = repo_id
        registry = Decompose(image).registry
        if registry not in self.atomic.load_local_tokens(
        ) and not args.username or not args.password:
            raise dbus.DBusException(
                "There is no local token and no username/password were provided.  Please try "
                "again with a username and password")
        if args.satellite or args.pulp:
            if not args.username or args.password:
                raise dbus.DBusException(
                    "No username or password was provided for satellite or pulp.  Please try "
                    "again with a username and password")
            if not args.url:
                raise dbus.DBusException(
                    "No URL was provided for satellite or pulp.  Please try again "
                    "with a defined URL.")

        if not registry_type:
            args.reg_type = 'docker'
        else:
            args.reg_type = registry_type
        if args.reg_type not in REGISTRY_TYPE_CHOICES:
            raise dbus.DBusException(
                "Registry type must be one of '{}'.".format(
                    REGISTRY_TYPE_CHOICES))
        args.sign_by = None if not sign_by else sign_by
        args.gnupghome = None if not gnupghome else gnupghome
        p.set_args(args)
        try:
            return p.push()

        except Exception as e:
            raise dbus.DBusException(str(e))
Ejemplo n.º 3
0
 def update_brightness(self, change, backlight="default", sender=None):
     """Return brightness"""
     self.check_polkit(sender, "{0}.control".format(neptune.POLKIT_SERVICE))
     try:
         self.system.update_brightness(change, backlight)
     except neptune.Error as error:
         raise dbus.DBusException(error)
Ejemplo n.º 4
0
 def set_power(self, power, sender=None):
     """Return brightness"""
     self.check_polkit(sender, "{0}.control".format(neptune.POLKIT_SERVICE))
     try:
         self.system.set_power(power)
     except neptune.Error as error:
         raise dbus.DBusException(error)
Ejemplo n.º 5
0
    def connect_service(self, object_path, uuid, ok, err):
        service = get_service(Device(object_path), uuid)

        try:
            self.Applet.Plugins.RecentConns
        except KeyError:
            dprint("RecentConns plugin is unavailable")
        else:
            self.Applet.Plugins.RecentConns.notify(service)

        if service.group == 'serial':

            def reply(rfcomm):
                self.Applet.Plugins.Run("on_rfcomm_connected", service, rfcomm)
                ok(rfcomm)

            rets = self.Applet.Plugins.Run("rfcomm_connect_handler", service,
                                           reply, err)
            if True in rets:
                pass
            else:
                dprint("No handler registered")
                err(
                    dbus.DBusException(
                        "Service not supported\nPossibly the plugin that handles this service is not loaded"
                    ))
        else:

            def cb(_inst, ret):
                if ret:
                    raise StopException

            if not self.Applet.Plugins.RunEx("service_connect_handler", cb,
                                             service, ok, err):
                service.connect(reply_handler=ok, error_handler=err)
Ejemplo n.º 6
0
    def ListInstalledProducts(self,
                              filter_string,
                              proxy_options,
                              locale,
                              sender=None):

        # We reinitialize dependency injection here for following reason. When new product
        # certificate is installed (or existing is removed), then this change is not propagated to
        # CertSorter and other caches. Calling installed_products.list(filter_string) without
        # reinitialization of dependency injection would return old (cached) list of installed
        # products.
        init_dep_injection()

        filter_string = dbus_utils.dbus_to_python(filter_string,
                                                  expected_type=str)
        proxy_options = dbus_utils.dbus_to_python(proxy_options,
                                                  expected_type=dict)
        locale = dbus_utils.dbus_to_python(locale, expected_type=str)

        Locale.set(locale)

        cp = self.build_uep(proxy_options, proxy_only=True)

        installed_products = InstalledProducts(cp)

        try:
            response = installed_products.list(filter_string)
        except Exception as err:
            raise dbus.DBusException(str(err))

        return json.dumps(response)
Ejemplo n.º 7
0
    def AutoAttach(self, service_level, proxy_options, locale, sender=None):
        self.ensure_registered()
        service_level = dbus_utils.dbus_to_python(service_level,
                                                  expected_type=str) or None
        proxy_options = dbus_utils.dbus_to_python(proxy_options,
                                                  expected_type=dict)
        locale = dbus_utils.dbus_to_python(locale, expected_type=str)
        Locale.set(locale)

        cp = self.build_uep(proxy_options, proxy_only=True)

        # TODO: Change log.info() to:
        # raise dbus.DBusException('Auto-attaching is not allowed in simple content access mode')
        # in the next minor release of subscription-manager
        if is_simple_content_access(uep=cp) is True:
            log.info(
                "Calling D-Bus method AutoAttach() is deprecated, when Simple Content Access mode "
                "is used and it will be not be supported in the next minor release of "
                "subscription-manager")

        attach_service = AttachService(cp)

        try:
            resp = attach_service.attach_auto(service_level)
        except Exception as e:
            log.exception(e)
            raise dbus.DBusException(str(e))

        # TODO Likely should only call this if something is actually attached
        entcertlib.EntCertActionInvoker().update()
        return json.dumps(resp)
Ejemplo n.º 8
0
	def service_connect_handler(self, interface, object_path, method, args, ok, err):
		if interface == "org.bluez.Network" and method == "Connect":
			uuid = args[0]
			name = uuid16_to_name(uuid128_to_uuid16(uuid))
			d = Device(object_path)
			
			conn = self.find_active_connection(d.Address, "panu")
			if conn:
				err(dbus.DBusException(_("Already connected")))
			else:
				params = {}
				params["bluetooth"] = {"name": "bluetooth", "bdaddr":  str(d.Address), "type" : "panu"}
				params["connection"] = {"autoconnect": False, "id": str("%s on %s") % (name, d.Alias), "uuid" : str(uuid1()), "type": "bluetooth"}
				params['ipv4'] = {'addresses': dbus.Array([], dbus.Signature("i")), 'dns': dbus.Array([], dbus.Signature("i")), "method": "auto", "routes": dbus.Array([], dbus.Signature("i"))}		
			
				NewConnectionBuilder(self, params, ok, err)
				
			return True
			
		elif interface == "org.bluez.Network" and method == "Disconnect":
			d = Device(object_path)
			active_conn_path = self.find_active_connection(d.Address, "panu")
			if active_conn_path:
				self.bus.call_blocking("org.freedesktop.NetworkManager", 
						       "/org/freedesktop/NetworkManager", 
						       "org.freedesktop.NetworkManager", 
						       "DeactivateConnection", 
						       "o", 
						       [active_conn_path])
				ok()		       	
				return True
Ejemplo n.º 9
0
    def Unregister(self, proxy_options, locale, sender=None):
        """
        Definition and implementation of D-Bus method
        :param proxy_options: Definition of proxy settings
        :param locale: String with locale (e.g. de_DE.UTF-8)
        :param sender: Not used argument
        """
        proxy_options = dbus_utils.dbus_to_python(proxy_options,
                                                  expected_type=dict)
        locale = dbus_utils.dbus_to_python(locale, expected_type=str)

        Locale.set(locale)

        self.ensure_registered()

        uep = self.build_uep(proxy_options, proxy_only=True)

        try:
            UnregisterService(uep).unregister()
        except Exception as err:
            raise dbus.DBusException(str(err))

        # The system is unregistered now, restart virt-who to stop sending
        # host-to-guest mapping.
        restart_virt_who()
Ejemplo n.º 10
0
    def GetStatus(self, on_date, locale, sender=None):
        """
        Get status of entitlements
        :param on_date: Date
        :param locale: String with locale (e.g. de_DE.UTF-8)
        :param sender: Not used argument
        :return: String with JSON dump
        """
        on_date = dbus_utils.dbus_to_python(on_date, expected_type=str)
        locale = dbus_utils.dbus_to_python(locale, expected_type=str)

        if on_date == "":
            on_date = None
        else:
            on_date = self._parse_date(on_date)
        Locale.set(locale)

        try:
            # get_status doesn't need a Candlepin connection
            status = EntitlementService(None).get_status(on_date)
        except Exception as e:
            log.exception(e)
            raise dbus.DBusException(str(e))

        return json.dumps(status)
Ejemplo n.º 11
0
 def get_battery(self):
     """Return battery settings"""
     try:
         battery = self.system.get_battery()
     except neptune.Error as error:
         raise dbus.DBusException(error)
     return dict(zip(battery.keys(),
                     [str(val) for val in battery.values()]))
Ejemplo n.º 12
0
 def signal_wait_timeout(self):
     if not self.device or not self.connection:
         self.err_cb(
             dbus.DBusException(
                 "Network Manager did not support the connection"))
         if self.connection:
             self.remove_connection()
         self.cleanup()
Ejemplo n.º 13
0
def test__log_shutdown_inhibitors_fail(caplog):
    login_manager = unittest.mock.MagicMock()
    login_manager.ListInhibitors.side_effect = dbus.DBusException("mocked")
    with caplog.at_level(logging.DEBUG):
        systemctl_mqtt._dbus._log_shutdown_inhibitors(login_manager)
    assert len(caplog.records) == 1
    assert caplog.records[0].levelno == logging.WARNING
    assert caplog.records[0].message == "failed to fetch shutdown inhibitors: mocked"
Ejemplo n.º 14
0
    def PPPDisconnect(self, port, caller):
        self.confirm_authorization(caller, "org.blueman.pppd.pppconnect")
        p = subprocess.Popen(['ps', '-e', 'o', 'pid,args'], stdout=subprocess.PIPE)
        stdout, stderr = p.communicate()
        if p.returncode != 0:
            raise dbus.DBusException('Failed to retrieve list of process ids')

        pid = None
        for line in stdout.decode('utf-8').splitlines():
            if '/usr/sbin/pppd /dev/rfcomm%s' % port in line:
                pid = int(line.split(None, 1)[0])

        if pid is None:
            raise dbus.DBusException('No proces id found for pppd')
        else:
            os.kill(pid, signal.SIGTERM)
            return 'Succesfully killed pppd with pid %s' % pid
Ejemplo n.º 15
0
 def ClearAlarm(self, busname, sender):
     if not self._verifyNameOwner(busname, sender):
         raise dbus.DBusException("The bus name %s is not owned by %s" %
                                  (busname, sender))
     old = self.alarms.pop(busname, None)
     if not old is None:
         self.queue.remove(old)
         heapify(self.queue)
     self._schedule()
Ejemplo n.º 16
0
 def Get(self, interface, property_name):
     ''' Returns the property value.
     '''  # pylint: disable=unused-argument
     try:
         return self.properties[property_name]
     except KeyError:
         raise dbus.DBusException("Property %s does not exist" %
                                  property_name,
                                  name="MissingProperty")
Ejemplo n.º 17
0
	def on_device_state(self, state, oldstate, reason):
		dprint("state=",state, "oldstate=", oldstate, "reason=", reason)
		if state <= NMDeviceState.DISCONNECTED and NMDeviceState.DISCONNECTED < oldstate <= NMDeviceState.ACTIVATED:
			if self.err_cb:
				self.err_cb(dbus.DBusException("Connection was interrupted"))
			
			self.remove_connection()
			self.cleanup()
		
		elif state == NMDeviceState.FAILED:
			self.err_cb(dbus.DBusException("Network Manager Failed to activate the connection"))
			self.remove_connection()
			self.cleanup()		
		
		elif state == NMDeviceState.ACTIVATED:
			self.ok_cb()
			self.err_cb = None
			self.ok_cb = None
Ejemplo n.º 18
0
    def service_connect_handler(self, service, ok, err):
        if service.group != 'network':
            return

        if self.find_active_connection(service.device.Address, "panu"):
            err(dbus.DBusException(_("Already connected")))
        else:
            NewConnectionBuilder(self, service, ok, err)

        return True
Ejemplo n.º 19
0
 def reply(self, reply):
     dprint(self._agent_path, reply)
     if isclass(reply) and issubclass(reply, Error):
         self._error_handler(
             dbus.DBusException(name=('org.bluez.obex.Error.%s' %
                                      reply.__name__)))
     else:
         self._reply_handler(reply)
     self._reply_handler = None
     self._error_handler = None
Ejemplo n.º 20
0
    def on_device_state(self, state, oldstate, reason):
        dprint("state=", state, "oldstate=", oldstate, "reason=", reason)
        if (state <= self.DEVICE_STATE_DISCONNECTED or state == self.DEVICE_STATE_DEACTIVATING) and \
                                self.DEVICE_STATE_DISCONNECTED < oldstate <= self.DEVICE_STATE_ACTIVATED:
            if self.err_cb:
                self.err_cb(dbus.DBusException("Connection was interrupted"))

            self.remove_connection()
            self.cleanup()

        elif state == self.DEVICE_STATE_FAILED:
            self.err_cb(dbus.DBusException("Network Manager Failed to activate the connection"))
            self.remove_connection()
            self.cleanup()

        elif state == self.DEVICE_STATE_ACTIVATED:
            self.ok_cb()
            self.err_cb = None
            self.ok_cb = None
Ejemplo n.º 21
0
 def ImageUpdate(self, image, force=False):
     u = Update()
     args = self.Args()
     args.image = image
     args.name = image
     args.force = force
     u.set_args(args)
     try:
         return u.update()
     except Exception as e:
         raise dbus.DBusException(str(e))
Ejemplo n.º 22
0
 def _parse_date(on_date):
     """
     Return new datetime parsed from date
     :param on_date: String representing date
     :return It returns datetime.datime structure representing date
     """
     try:
         on_date = EntitlementService.parse_date(on_date)
     except ValueError as err:
         raise dbus.DBusException(err)
     return on_date
Ejemplo n.º 23
0
 def ImagePull(self, image, storage='', reg_type=''):
     p = Pull()
     args = self.Args()
     args.image = image
     args.storage = None if storage == '' else storage
     args.reg_type = None if reg_type == '' else reg_type
     p.set_args(args)
     try:
         return p.pull_image()
     except Exception as e:
         raise dbus.DBusException(str(e))
Ejemplo n.º 24
0
	def init_connection(self):
		self.cleanup()
		dprint("activating", self.connection, self.device)
		if not self.device or not self.connection:
			self.err_cb(dbus.DBusException("Network Manager did not support the connection"))
			if self.connection:
				self.remove_connection()
			self.cleanup()
		else:
			self.signals.Handle("dbus", self.parent.bus, self.on_device_state, "StateChanged", "org.freedesktop.NetworkManager.Device", path=self.device)
		
			self.parent.nm.ActivateConnection("org.freedesktop.NetworkManagerUserSettings", self.connection, self.device, self.connection)
    def modify_user_passwd(self,
                           new_password,
                           username,
                           old_password,
                           sender=None,
                           conn=None):
        if getpass.getuser() != username:
            if not authWithPolicyKit(
                    sender, conn, "com.deepin.passwdservice.modify-password"):
                raise dbus.DBusException("not authWithPolicyKit")

        return self.__modify_user_passwd(new_password, username, old_password)
Ejemplo n.º 26
0
 def Run(self, image, name='', spc=False, detach=False, command=''):
     r = Run()
     args = self.Args()
     args.image = image
     args.name = name if name is not '' else None
     args.spc = spc
     args.detach = detach
     args.command = command if command is not '' else []
     r.set_args(args)
     try:
         return r.run()
     except ValueError as e:
         raise dbus.DBusException(str(e))
Ejemplo n.º 27
0
 def get_values(self, name):
     """Return power setting"""
     if name in self.system.values:
         values = self.system.values[name]
         if len(values) < 20:
             return values
         else:
             return [
                 values[i] for i in range(0, len(values),
                                          int(len(values) / 20) + 1)
             ] + [values[-1]]
     else:
         raise dbus.DBusException("No values for {0}".format(name))
Ejemplo n.º 28
0
    def PoolAttach(self, pools, quantity, proxy_options, locale, sender=None):
        self.ensure_registered()
        pools = dbus_utils.dbus_to_python(pools, expected_type=list)
        quantity = dbus_utils.dbus_to_python(quantity, expected_type=int)
        proxy_options = dbus_utils.dbus_to_python(proxy_options,
                                                  expected_type=dict)

        locale = dbus_utils.dbus_to_python(locale, expected_type=str)
        Locale.set(locale)

        if quantity < 1:
            raise dbus.DBusException("Quantity must be a positive number.")

        cp = self.build_uep(proxy_options, proxy_only=True)

        # TODO: Change log.info() to:
        # raise dbus.DBusException('Attaching of pool(s) is not allowed in simple content access mode')
        # in the next minor release of subscription-manager
        if is_simple_content_access(uep=cp) is True:
            log.info(
                "Calling D-Bus method PoolAttach() is deprecated, when Simple Content Access mode "
                "is used and it will be not be supported in the next minor release of "
                "subscription-manager")

        attach_service = AttachService(cp)

        try:
            results = []
            for pool in pools:
                resp = attach_service.attach_pool(pool, quantity)
                results.append(json.dumps(resp))
        except Exception as e:
            log.exception(e)
            raise dbus.DBusException(str(e))

        # TODO Likely should only call this if something is actually attached
        entcertlib.EntCertActionInvoker().update()
        return results
Ejemplo n.º 29
0
 def GetValidFields(self, locale, sender=None):
     """
     Method for getting valid syspurpose attributes and values
     :param locale: string with locale
     :param sender: object representing application which called this method
     :return: string representing dictionary with valid fields
     """
     locale = dbus_utils.dbus_to_python(locale, expected_type=str)
     Locale.set(locale)
     cp = self.build_uep({})
     system_purpose = syspurpose.Syspurpose(cp)
     valid_fields = system_purpose.get_owner_syspurpose_valid_fields()
     if valid_fields is None:
         # When it is not possible to get valid fields, then raise exception
         if self.is_registered() is False:
             raise dbus.DBusException(
                 "Unable to get system purpose valid fields. System is not registered.",
             )
         else:
             raise dbus.DBusException(
                 "Unable to get system purpose valid fields.", )
     else:
         return json.dumps(valid_fields)
Ejemplo n.º 30
0
 def Run(self, image, name, spc, detach, ignore, command):
     r = Run()
     args = self.Args()
     args.image = image
     args.name = name
     args.spc = spc
     args.detach = detach
     args.command = command if command is not '' else []
     args.ignore = ignore
     r.set_args(args)
     try:
         return r.run()
     except ValueError as e:
         raise dbus.DBusException(str(e))