Esempio n. 1
0
	def test_pv_resize(self):

		self.assertTrue(len(self.objs[PV_INT]) > 0)

		if len(self.objs[PV_INT]) > 0:
			pv = ClientProxy(self.bus, self.objs[PV_INT][0].object_path,
								interfaces=(PV_INT, )).Pv

			original_size = pv.SizeBytes

			new_size = original_size / 2

			self.handle_return(
				pv.ReSize(
					dbus.UInt64(new_size),
					dbus.Int32(g_tmo),
					EOD))

			self._check_consistency()
			pv.update()

			self.assertTrue(pv.SizeBytes != original_size)
			self.handle_return(
				pv.ReSize(
					dbus.UInt64(0),
					dbus.Int32(g_tmo),
					EOD))
			self._check_consistency()
			pv.update()
			self.assertTrue(pv.SizeBytes == original_size)
Esempio n. 2
0
	def test_snapshot_merge_thin(self):
		# Create a thin LV, snapshot it and merge it
		vg = self._vg_create().Vg
		tp = self._create_lv(thinpool=True, vg=vg)
		lv_name = lv_n('_thin_lv')

		thin_path = self.handle_return(
			tp.ThinPool.LvCreate(
				dbus.String(lv_name),
				dbus.UInt64(mib(10)),
				dbus.Int32(g_tmo),
				EOD))

		self._validate_lookup("%s/%s" % (vg.Name, lv_name), thin_path)

		lv_p = ClientProxy(self.bus, thin_path,
							interfaces=(LV_INT, LV_COMMON_INT))

		ss_name = lv_p.LvCommon.Name + '_snap'
		snapshot_path = self.handle_return(
			lv_p.Lv.Snapshot(
				dbus.String(ss_name),
				dbus.UInt64(0),
				dbus.Int32(g_tmo),
				EOD))

		ss = ClientProxy(self.bus, snapshot_path,
							interfaces=(LV_INT, LV_COMMON_INT, SNAPSHOT_INT))

		job_path = self.handle_return(
			ss.Snapshot.Merge(
				dbus.Int32(g_tmo), EOD)
		)
		self.assertTrue(job_path == '/')
Esempio n. 3
0
    def test_create_with_format_auto_type_gpt(self):
        if not self._have_udftools():
            self.skipTest('Udftools needed to check automatic partition type update.')

        disk = self.get_object('/block_devices/' + os.path.basename(self.vdevs[0]))
        self.assertIsNotNone(disk)

        # create msdos partition table
        self._create_format(disk, 'gpt')

        self.addCleanup(self._remove_format, disk)

        # create partition with udf format and automatically set partition type
        # it should be ebd0a0a2-b9e5-4433-87c0-68b6b72699c7
        d = dbus.Dictionary(signature='sv')
        d['update-partition-type'] = True
        path = disk.CreatePartitionAndFormat(dbus.UInt64(1024**2), dbus.UInt64(100 * 1024**2), '', '',
                                             self.no_options, 'udf', d,
                                             dbus_interface=self.iface_prefix + '.PartitionTable')

        part = self.bus.get_object(self.iface_prefix, path)
        self.assertIsNotNone(part)

        self.addCleanup(self._remove_partition, part)
        self.addCleanup(self._remove_format, part)

        # check dbus properties
        dbus_type = self.get_property(part, '.Partition', 'Type')
        dbus_type.assertEqual('ebd0a0a2-b9e5-4433-87c0-68b6b72699c7')

        # check system values
        part_name = path.split('/')[-1]
        _ret, sys_type = self.run_command('blkid /dev/%s -p -o value -s PART_ENTRY_TYPE' % part_name)
        self.assertEqual(sys_type, 'ebd0a0a2-b9e5-4433-87c0-68b6b72699c7')
Esempio n. 4
0
    def test_40_cache(self):
        '''Basic LVM cache test'''

        vgname = 'udisks_test_cache_vg'

        # Use all the virtual devices
        devs = dbus.Array()
        for d in self.vdevs:
            dev_obj = self.get_object('/block_devices/' + os.path.basename(d))
            self.assertIsNotNone(dev_obj)
            devs.append(dev_obj)
        vg = self._create_vg(vgname, devs)
        self.addCleanup(self._remove_vg, vg)

        # Create the origin LV
        vgsize = int(self.get_property_raw(vg, '.VolumeGroup', 'FreeSize'))
        orig_lvname = 'udisks_test_origin_lv'
        lv_path = vg.CreatePlainVolume(orig_lvname,
                                       dbus.UInt64(vgsize / 2),
                                       self.no_options,
                                       dbus_interface=self.iface_prefix +
                                       '.VolumeGroup')
        lv = self.bus.get_object(self.iface_prefix, lv_path)
        self.assertIsNotNone(lv)

        ret, _out = self.run_command('lvs %s' %
                                     os.path.join(vgname, orig_lvname))
        self.assertEqual(ret, 0)

        # Create the caching LV
        cache_lvname = 'udisks_test_cache_lv'
        vgsize = int(self.get_property_raw(vg, '.VolumeGroup', 'FreeSize'))
        lv_cache_path = vg.CreatePlainVolume(cache_lvname,
                                             dbus.UInt64(vgsize / 2),
                                             self.no_options,
                                             dbus_interface=self.iface_prefix +
                                             '.VolumeGroup')
        cache_lv = self.bus.get_object(self.iface_prefix, lv_cache_path)
        self.assertIsNotNone(cache_lv)

        # Add the cache to the origin
        lv.CacheAttach('udisks_test_cache_lv',
                       self.no_options,
                       dbus_interface=self.iface_prefix + '.LogicalVolume')

        _ret, out = self.run_command('lvs %s/%s --noheadings -o segtype' %
                                     (vgname, orig_lvname))
        self.assertEqual(out, 'cache')

        # Split the cache
        lv.CacheSplit(self.no_options,
                      dbus_interface=self.iface_prefix + '.LogicalVolume')

        _ret, out = self.run_command('lvs %s/%s --noheadings -o lv_layout' %
                                     (vgname, orig_lvname))
        self.assertEqual(out, 'linear')

        _ret, out = self.run_command('lvs %s/%s --noheadings -o lv_layout' %
                                     (vgname, cache_lvname))
        self.assertEqual(out, 'cache,pool')
Esempio n. 5
0
def UpdateStatus(self, is_complete):
    '''Mock method to update the transfer status.

    If is_complete is False, this marks the transfer is active; otherwise it
    marks the transfer as complete. It is an error to call this method after
    calling it with is_complete as True.

    In both cases, it updates the number of bytes transferred to be the current
    size of the transfer file (whose filename was emitted in the
    TransferCreated signal).
    '''
    status = 'complete' if is_complete else 'active'
    transferred = os.path.getsize(self.props[TRANSFER_IFACE]['Filename'])

    self.props[TRANSFER_IFACE]['Status'] = status
    self.props[TRANSFER_IFACE]['Transferred'] = dbus.UInt64(transferred,
                                                            variant_level=1)

    self.EmitSignal(dbus.PROPERTIES_IFACE, 'PropertiesChanged', 'sa{sv}as', [
        TRANSFER_IFACE,
        {
            'Status': dbus.String(status, variant_level=1),
            'Transferred': dbus.UInt64(transferred, variant_level=1),
        },
        [],
    ])
Esempio n. 6
0
    def test_30_create_with_offset_size(self):
        opts = dbus.Dictionary(
            {
                "offset": dbus.UInt64(4096),
                "size": dbus.UInt64(4 * 1024**2)
            },
            signature=dbus.Signature('sv'))
        with open(self.LOOP_DEVICE_FILENAME, "r+b") as loop_file:
            fd = loop_file.fileno()
            loop_dev_obj_path = self.manager.LoopSetup(fd, opts)
        self.assertTrue(loop_dev_obj_path)
        self.assertTrue(loop_dev_obj_path.startswith(self.path_prefix))
        path, loop_dev = loop_dev_obj_path.rsplit("/", 1)
        self.addCleanup(self.run_command, "losetup -d /dev/%s" % loop_dev)

        loop_dev_obj = self.get_object(loop_dev_obj_path)

        # should use the right backing file
        raw = self.get_property(loop_dev_obj, '.Loop', 'BackingFile')
        # transcription to array of Bytes to string plus adding the trailing \0
        backing_file = self.str_to_ay(
            os.path.join(os.getcwd(), self.LOOP_DEVICE_FILENAME))
        raw.assertEqual(backing_file)

        # should use just the space specified by the 'size' argument
        size = self.get_property(loop_dev_obj, ".Block", "Size")
        size.assertEqual(4 * 1024**2)

        # should be writable
        ro = self.get_property(loop_dev_obj, ".Block", "ReadOnly")
        ro.assertFalse()
Esempio n. 7
0
def AddSeat(self, seat):
    '''Convenience method to add a seat.

    Return the object path of the new seat.
    '''
    seat_path = '/org/freedesktop/login1/seat/' + seat
    if seat_path in mockobject.objects:
        raise dbus.exceptions.DBusException('Seat %s already exists' % seat,
                                            name=MOCK_IFACE + '.SeatExists')

    self.AddObject(seat_path,
                   'org.freedesktop.login1.Seat',
                   {
                       'Sessions': dbus.Array([], signature='(so)'),
                       'CanGraphical': False,
                       'CanMultiSession': True,
                       'CanTTY': False,
                       'IdleHint': False,
                       'ActiveSession': ('', dbus.ObjectPath('/')),
                       'Id': seat,
                       'IdleSinceHint': dbus.UInt64(0),
                       'IdleSinceHintMonotonic': dbus.UInt64(0),
                   },
                   [
                       ('ActivateSession', 's', '', ''),
                       ('Terminate', '', '', '')
                   ])

    return seat_path
Esempio n. 8
0
    def test_resize_logical(self):
        vgname = 'udisks_test_vdo_vg'

        # create vg on our testing device
        vg = self._create_vg(vgname, [self.device])
        self.addCleanup(self._remove_vg, vg)

        vg_free = self.get_property(vg, '.VolumeGroup', 'FreeSize')
        lv_name = 'udisks_test_vdovlv'
        pool_name = 'udisks_test_vdopool'
        psize = vg_free.value
        vsize = psize
        lv_path = vg.CreateVDOVolume(lv_name,
                                     pool_name,
                                     dbus.UInt64(psize),
                                     dbus.UInt64(vsize),
                                     dbus.UInt64(0),
                                     True,
                                     True,
                                     "auto",
                                     self.no_options,
                                     dbus_interface=self.iface_prefix +
                                     '.VolumeGroup')
        self.assertIsNotNone(lv_path)

        lv = self.bus.get_object(self.iface_prefix, lv_path)
        self.assertIsNotNone(lv)

        lv.ResizeLogical(vsize * 5,
                         self.no_options,
                         dbus_interface=self.iface_prefix + '.VDOVolume')
        dbus_size = self.get_property(lv, '.LogicalVolume', 'Size')
        dbus_size.assertEqual(vsize * 5)
Esempio n. 9
0
    def test_format_parttype(self):

        disk = self.get_object('/block_devices/' + os.path.basename(self.vdevs[0]))
        self.assertIsNotNone(disk)

        # create partition table first
        disk.Format('dos', self.no_options, dbus_interface=self.iface_prefix + '.Block')

        # now create partition
        path = disk.CreatePartition(dbus.UInt64(1024**2), dbus.UInt64(100 * 1024**2),
                                    '', '', self.no_options,
                                    dbus_interface=self.iface_prefix + '.PartitionTable')

        part = self.bus.get_object(self.iface_prefix, path)
        self.assertIsNotNone(part)

        # now format it to swap with 'update-partition-type'
        d = dbus.Dictionary(signature='sv')
        d['update-partition-type'] = True
        part.Format('swap', d, dbus_interface=self.iface_prefix + '.Block')

        # part type should be set to swap (0x42 or 0x82)
        dbus_type = self.get_property(part, '.Partition', 'Type')
        dbus_type.assertIn(['0x42', '0x82'])

        part_name = str(part.object_path).split('/')[-1]
        _ret, sys_type = self.run_command('blkid /dev/%s -p -o value -s PART_ENTRY_TYPE' % part_name)
        self.assertIn(sys_type, ['0x42', '0x82'])
Esempio n. 10
0
def AddUser(self, uid, username, active):
    '''Convenience method to add a user.

    Return the object path of the new user.
    '''
    user_path = '/org/freedesktop/login1/user/%i' % uid
    if user_path in mockobject.objects:
        raise dbus.exceptions.DBusException('User %i already exists' % uid,
                                            name=MOCK_IFACE + '.UserExists')

    self.AddObject(user_path,
                   'org.freedesktop.login1.User',
                   {
                       'Sessions': dbus.Array([], signature='(so)'),
                       'IdleHint': False,
                       'DefaultControlGroup': 'systemd:/user/' + username,
                       'Name': username,
                       'RuntimePath': '/run/user/%i' % uid,
                       'Service': '',
                       'State': (active and 'active' or 'online'),
                       'Display': ('', dbus.ObjectPath('/')),
                       'UID': dbus.UInt32(uid),
                       'GID': dbus.UInt32(uid),
                       'IdleSinceHint': dbus.UInt64(0),
                       'IdleSinceHintMonotonic': dbus.UInt64(0),
                       'Timestamp': dbus.UInt64(42),
                       'TimestampMonotonic': dbus.UInt64(42),
                   },
                   [
                       ('Kill', 's', '', ''),
                       ('Terminate', '', '', ''),
                   ])

    return user_path
Esempio n. 11
0
    def test_fill_with_primary_partitions(self):
        disk = self.get_object('/block_devices/' +
                               os.path.basename(self.vdevs[0]))
        self.assertIsNotNone(disk)

        # create msdos partition table
        self._create_format(disk, 'dos')
        self.addCleanup(self._remove_format, disk)

        options = dbus.Dictionary({'partition-type': 'primary'},
                                  signature='sv')
        offset = 1024**2
        size = 10 * 1024**2
        for i in range(4):
            # create primary partition
            path = disk.CreatePartition(
                dbus.UInt64(offset + i * (offset + size)),
                dbus.UInt64(size),
                '',
                '',
                options,
                dbus_interface=self.iface_prefix + '.PartitionTable')
            self.udev_settle()

            part = self.bus.get_object(self.iface_prefix, path)
            self.assertIsNotNone(part)
            self.addCleanup(self._remove_partition, part)

            dbus_cont = self.get_property(part, '.Partition', 'IsContainer')
            dbus_cont.assertFalse()

            dbus_cont = self.get_property(part, '.Partition', 'IsContained')
            dbus_cont.assertFalse()
Esempio n. 12
0
	def test_lv_activate_deactivate(self):
		lv_p = self._create_lv()
		lv_p.update()

		self.handle_return(lv_p.Lv.Deactivate(
			dbus.UInt64(0), dbus.Int32(g_tmo), EOD))
		lv_p.update()
		self.assertFalse(lv_p.LvCommon.Active)
		self._check_consistency()

		self.handle_return(lv_p.Lv.Activate(
			dbus.UInt64(0), dbus.Int32(g_tmo), EOD))

		lv_p.update()
		self.assertTrue(lv_p.LvCommon.Active)
		self._check_consistency()

		# Try control flags
		for i in range(0, 5):

			self.handle_return(lv_p.Lv.Activate(
				dbus.UInt64(1 << i),
				dbus.Int32(g_tmo),
				EOD))

			self.assertTrue(lv_p.LvCommon.Active)
			self._check_consistency()
Esempio n. 13
0
    def _create_partition(self,
                          disk,
                          start=1024**2,
                          size=100 * 1024**2,
                          fmt='xfs',
                          type=''):
        if fmt:
            path = disk.CreatePartitionAndFormat(
                dbus.UInt64(start),
                dbus.UInt64(size),
                type,
                '',
                self.no_options,
                fmt,
                self.no_options,
                dbus_interface=self.iface_prefix + '.PartitionTable')
        else:
            path = disk.CreatePartition(dbus.UInt64(start),
                                        dbus.UInt64(size),
                                        type,
                                        '',
                                        self.no_options,
                                        dbus_interface=self.iface_prefix +
                                        '.PartitionTable')

        self.udev_settle()
        part = self.bus.get_object(self.iface_prefix, path)
        self.assertIsNotNone(part)

        return part
Esempio n. 14
0
    def test_create_gpt_partition(self):
        disk = self.get_object('/block_devices/' + os.path.basename(self.vdevs[0]))
        self.assertIsNotNone(disk)

        # create gpt partition table
        self._create_format(disk, 'gpt')
        pttype = self.get_property(disk, '.PartitionTable', 'Type')
        pttype.assertEqual('gpt')

        self.addCleanup(self._remove_format, disk)

        gpt_name = 'home'
        gpt_type = '933ac7e1-2eb4-4f13-b844-0e14e2aef915'

        # create partition
        path = disk.CreatePartition(dbus.UInt64(1024**2), dbus.UInt64(100 * 1024**2),
                                    gpt_type, gpt_name,
                                    self.no_options, dbus_interface=self.iface_prefix + '.PartitionTable')

        self.udev_settle()
        part = self.bus.get_object(self.iface_prefix, path)
        self.assertIsNotNone(part)

        self.addCleanup(self._remove_partition, part)

        # check dbus properties
        size = self.get_property(part, '.Partition', 'Size')
        size.assertEqual(100 * 1024**2)

        offset = self.get_property(part, '.Partition', 'Offset')
        offset.assertEqual(1024**2)

        dbus_name = self.get_property(part, '.Partition', 'Name')
        dbus_name.assertEqual(gpt_name)

        dbus_type = self.get_property(part, '.Partition', 'Type')
        dbus_type.assertEqual(gpt_type)

        # check system values
        part_name = path.split('/')[-1]
        disk_name = os.path.basename(self.vdevs[0])
        part_syspath = '/sys/block/%s/%s' % (disk_name, part_name)
        self.assertTrue(os.path.isdir(part_syspath))

        sys_size = int(self.read_file('%s/size' % part_syspath))
        self.assertEqual(sys_size * BLOCK_SIZE, 100 * 1024**2)

        sys_start = int(self.read_file('%s/start' % part_syspath))
        self.assertEqual(sys_start * BLOCK_SIZE, 1024**2)

        _ret, sys_name = self.run_command('lsblk -d -no PARTLABEL /dev/%s' % part_name)
        self.assertEqual(sys_name, gpt_name)

        # format the partition so blkid is able to display info about it
        # (yes, it is stupid, but this is how blkid works on CentOS/RHEL 7)
        _ret, _out = self.run_command('mkfs.ext2 /dev/%s' % part_name)

        _ret, sys_type = self.run_command('blkid /dev/%s -p -o value -s PART_ENTRY_TYPE' % part_name)
        self.assertEqual(sys_type, gpt_type)
Esempio n. 15
0
    def test_create_extended_partition(self):

        disk = self.get_object('/block_devices/' +
                               os.path.basename(self.vdevs[0]))
        self.assertIsNotNone(disk)

        # create msdos partition table
        self._create_format(disk, 'dos')
        self.addCleanup(self._remove_format, disk)

        # create extended partition
        ext_path = disk.CreatePartition(dbus.UInt64(0),
                                        dbus.UInt64(100 * 1024**2),
                                        '0x05',
                                        '',
                                        self.no_options,
                                        dbus_interface=self.iface_prefix +
                                        '.PartitionTable')
        self.udev_settle()

        ext_part = self.bus.get_object(self.iface_prefix, ext_path)
        self.assertIsNotNone(ext_part)

        self.addCleanup(self._remove_partition, ext_part)

        # check dbus type (0x05, 0x0f, 0x85 are all exteded types, see https://en.wikipedia.org/wiki/Partition_type#PID_05h)
        dbus_pttype = self.get_property(ext_part, '.Partition', 'Type')
        dbus_pttype.assertIn(['0x05', '0x0f', '0x85'])

        # check if its a 'container'
        dbus_cont = self.get_property(ext_part, '.Partition', 'IsContainer')
        dbus_cont.assertTrue()

        # check system type
        part_name = str(ext_part.object_path).split('/')[-1]
        _ret, sys_pttype = self.run_command('lsblk -d -no PARTTYPE /dev/%s' %
                                            part_name)
        self.assertIn(
            sys_pttype,
            ['0x5', '0xf', '0x85'])  # lsblk prints 0xf instead of 0x0f

        # create logical partition
        log_path = disk.CreatePartition(dbus.UInt64(1024**2),
                                        dbus.UInt64(50 * 1024**2),
                                        '',
                                        '',
                                        self.no_options,
                                        dbus_interface=self.iface_prefix +
                                        '.PartitionTable')
        self.udev_settle()

        log_part = self.bus.get_object(self.iface_prefix, log_path)
        self.assertIsNotNone(log_part)

        self.addCleanup(self._remove_partition, log_part)

        # check if its a 'contained'
        dbus_cont = self.get_property(log_part, '.Partition', 'IsContained')
        dbus_cont.assertTrue()
def add_seat(self, properties, is_self):
    # find a new name
    count = 0
    while True:
        id = 'seat%d' % count
        if id not in self.seats:
            break
        count += 1

    path = dbus.ObjectPath(SEAT_PATH + id)

    seat_props = {
        'Id':
        id,
        'ActiveSession':
        properties.get(
            'ActiveSession',
            dbus.Struct(('c2', '/org/freedesktop/login1/session/c2'),
                        signature='so')),
        'CanMultiSession':
        properties.get('CanMultiSession', True),
        'CanTTY':
        properties.get('CanTTY', True),
        'CanGraphical':
        properties.get('CanGraphical', True),
        'Sessions':
        properties.get(
            'Sessions',
            dbus.Array([('c2', '/org/freedesktop/login1/session/c2')],
                       signature='(so)')),
        'IdleHint':
        properties.get('IdleHint', False),
        'IdleSinceHint':
        properties.get('IdleSinceHint', dbus.UInt64(1489590854604069)),
        'IdleSinceHintMonotonic':
        properties.get('IdleSinceHintMonotonic', dbus.UInt64(18537117367)),
    }

    seat_methods = [
        ('Terminate', '', '', ""),
        ('ActivateSession', 's', '', ""),
        ('SwitchTo', 'u', '', ""),
        ('SwitchToNext', '', '', ""),
        ('SwitchToPrevious', '', '', ""),
    ]

    self.seats[id] = self.AddObject(path, SEAT_IFACE, seat_props, seat_methods)

    if is_self:
        self_path = dbus.ObjectPath(SEAT_PATH + 'self')
        try:
            self.RemoveObject(self_path)
        except dbus.exceptions.DBusException:
            pass
        self.AddObject(self_path, SEAT_IFACE, seat_props, seat_methods)

    return path
def AddEthernetDevice(self, device_name, iface_name, state):
    '''Add an ethernet device.

    You have to specify device_name, device interface name (e. g. eth0), and
    state. You can use the predefined DeviceState values (e. g.
    DeviceState.ACTIVATED) or supply a numeric value. For valid state values
    please visit
    http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE

    Please note that this does not set any global properties.

    Returns the new object path.
    '''
    path = '/org/freedesktop/NetworkManager/Devices/' + device_name
    wired_props = {
        'Carrier': False,
        'HwAddress': dbus.String('78:DD:08:D2:3D:43'),
        'PermHwAddress': dbus.String('78:DD:08:D2:3D:43'),
        'Speed': dbus.UInt32(0)
    }
    self.AddObject(path, 'org.freedesktop.NetworkManager.Device.Wired',
                   wired_props, [])

    props = {
        'DeviceType': dbus.UInt32(1),
        'State': dbus.UInt32(state),
        'Interface': iface_name,
        'ActiveConnection': dbus.ObjectPath('/'),
        'AvailableConnections': dbus.Array([], signature='o'),
        'Autoconnect':
        False,  # Network Manager captializes this differently than other properties
        'Managed': True,
        'Driver': 'dbusmock',
        'IpInterface': ''
    }

    obj = dbusmock.get_object(path)
    obj.disconnect = device_disconnect
    obj.AddMethods(DEVICE_IFACE,
                   [('Disconnect', '', '', "self.disconnect(self)")])
    obj.AddProperties(DEVICE_IFACE, props)
    obj.AddProperties(
        DEVICE_STATISTICS_IFACE, {
            'RefreshRateMs': dbus.UInt32(0),
            'TxBytes': dbus.UInt64(0),
            'RxBytes': dbus.UInt64(0),
        })

    devices = self.Get(MAIN_IFACE, 'Devices')
    devices.append(path)
    self.Set(MAIN_IFACE, 'Devices', devices)

    self.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o',
                    [path])

    return path
Esempio n. 18
0
    def test_create_with_format(self):
        disk = self.get_object('/block_devices/' +
                               os.path.basename(self.vdevs[0]))
        self.assertIsNotNone(disk)

        # create msdos partition table
        self._create_format(disk, 'dos')

        self.addCleanup(self._remove_format, disk)

        # create partition with xfs format
        path = disk.CreatePartitionAndFormat(dbus.UInt64(1024**2),
                                             dbus.UInt64(100 * 1024**2),
                                             '',
                                             '',
                                             self.no_options,
                                             'xfs',
                                             self.no_options,
                                             dbus_interface=self.iface_prefix +
                                             '.PartitionTable')

        part = self.bus.get_object(self.iface_prefix, path)
        self.assertIsNotNone(part)

        self.addCleanup(self._remove_partition, part)
        self.addCleanup(self._remove_format, part)

        # check dbus properties
        size = self.get_property(part, '.Partition', 'Size')
        size.assertEqual(100 * 1024**2)

        offset = self.get_property(part, '.Partition', 'Offset')
        offset.assertEqual(1024**2)

        usage = self.get_property(part, '.Block', 'IdUsage')
        usage.assertEqual('filesystem')

        fstype = self.get_property(part, '.Block', 'IdType')
        fstype.assertEqual('xfs')

        # check system values
        part_name = path.split('/')[-1]
        disk_name = os.path.basename(self.vdevs[0])
        part_syspath = '/sys/block/%s/%s' % (disk_name, part_name)
        self.assertTrue(os.path.isdir(part_syspath))

        sys_size = int(self.read_file('%s/size' % part_syspath))
        self.assertEqual(sys_size * BLOCK_SIZE, 100 * 1024**2)

        sys_start = int(self.read_file('%s/start' % part_syspath))
        self.assertEqual(sys_start * BLOCK_SIZE, 1024**2)

        _ret, sys_fstype = self.run_command('lsblk -d -no FSTYPE /dev/%s' %
                                            part_name)
        self.assertEqual(sys_fstype, 'xfs')
Esempio n. 19
0
    def message_received(self,message_id,uid,timestamp,title,text,attachments):
        self.Received(message_id,timestamp,self._handle.get_id(),telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,0,text)

        headers = dbus.Dictionary({
                   dbus.String('message-sent') : dbus.UInt64(timestamp),
                   dbus.String('message-received') : dbus.UInt64(time()),
                   dbus.String('pending-message-id') : dbus.UInt32(message_id),
                   dbus.String('message-token') : dbus.UInt32(message_id),
                   dbus.String('message-sender') : dbus.UInt32(self._handle.get_id()),
                   dbus.String('message-sender-id') : dbus.String(uid),
                   dbus.String('sender-nickname') : dbus.String(self._handle.contact.get('screen_name', uid)),
                   dbus.String('message-type') : dbus.UInt32(telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL)
                  }, signature='sv')
        body = [headers]

        plain_text = striphtml(text)
        html = u'<p>{}</p>'.format(text)

        if attachments:

            photo_fields = [name[:-5] for name,value in attachments.items() if name[-5:]=='_type' and value == 'photo' ]
            # photos = [value for name,value in attachments.items() if name in photo_fields]

            photos = [attachments.get(k) for k in photo_fields if attachments.get(k)]
            if photos:
                try:
                    photos = self._conn.Api.photos.getById(photos=photos,photo_sizes=1)

                    for photo in photos:
                        logger.info(repr(photo))
                        for size in photo.get('sizes',[]):
                            if size.get('type') == 'x':
                                photo['src'] = size.get('src')
                                break
                        else:
                            size = photo.get('sizes',[None])[-1]
                            if size:
                                photo['src'] =  size.get('src')

                        identifier = 'photo{owner_id}_{id}'.format(**photo)
                        body.append( dbus.Dictionary({
                            dbus.String('content-type'): dbus.String('image/jpeg'),
                            dbus.String('needs-retrieval'): True,
                            dbus.String('identifier'): dbus.String(identifier)
                           }, signature='sv')
                        )
                        plain_text += u'\n{src}'.format(**photo)
                        # plain_text += u'<img src="{src}" alt="photo{owner_id}_{id}"/>'.format(**photo)
                        html += u'<br/><img src="cid:photo{owner_id}_{id}" alt="photo{owner_id}_{id}"/>'.format(**photo)

                except vkcom.APIError,e:
                    # att = u'\nAttachment Error: {}'.format(e.message)
                    att = u'Есть вложения, смотри https://vk.com/im?sel={}'.format(uid)
                    plain_text += att
                    html += '<br/>' + att
Esempio n. 20
0
    def test_20_thin(self):
        '''Test thin volumes functionality'''

        vgname = 'udisks_test_thin_vg'

        # Use all the virtual devices
        devs = dbus.Array()
        for d in self.vdevs:
            dev_obj = self.get_object('/block_devices/' + os.path.basename(d))
            self.assertIsNotNone(dev_obj)
            devs.append(dev_obj)
        vg = self._create_vg(vgname, devs)
        self.addCleanup(self._remove_vg, vg)

        # Create thin pool on the VG
        vgsize = int(self.get_property_raw(vg, '.VolumeGroup', 'FreeSize'))
        tpname = 'udisks_test_tp'
        tp_path = vg.CreateThinPoolVolume(tpname,
                                          dbus.UInt64(vgsize),
                                          self.no_options,
                                          dbus_interface=self.iface_prefix +
                                          '.VolumeGroup')
        self.udev_settle()
        self.assertIsNotNone(tp_path)

        ret, _out = self.run_command('lvs %s' % os.path.join(vgname, tpname))
        self.assertEqual(ret, 0)

        tp = self.bus.get_object(self.iface_prefix, tp_path)
        tpsize = int(self.get_property_raw(tp, '.LogicalVolume', 'Size'))

        # Create thin volume in the pool with virtual size twice the backing pool
        tvname = 'udisks_test_tv'
        tv_path = vg.CreateThinVolume(tvname,
                                      dbus.UInt64(tpsize * 2),
                                      tp,
                                      self.no_options,
                                      dbus_interface=self.iface_prefix +
                                      '.VolumeGroup')
        self.udev_settle()
        tv = self.bus.get_object(self.iface_prefix, tv_path)
        self.assertIsNotNone(tv)

        ret, _out = self.run_command('lvs %s' % os.path.join(vgname, tvname))
        self.assertEqual(ret, 0)

        # Check the block device of the thin volume
        lv_block_path = tv.Activate(self.no_options,
                                    dbus_interface=self.iface_prefix +
                                    '.LogicalVolume')
        self.udev_settle()
        lv_block = self.bus.get_object(self.iface_prefix, lv_block_path)
        self.assertIsNotNone(lv_block)
        blocksize = self.get_property(lv_block, '.Block', 'Size')
        blocksize.assertGreater(vgsize)
Esempio n. 21
0
	def GetAll(self, interface_name):
		if interface_name == 'org.freedesktop.Secret.Collection':
			return {
				'Locked': self.get_locked(),
				'Label': self.label,
				'Created': dbus.UInt64(self.created),
				'Modified': dbus.UInt64(self.modified),
				'Items': dbus.Array([dbus.ObjectPath(i.path) for i in self.items.values()], signature='o', variant_level=1)
			}
		else:
			raise InvalidArgs('Unknown %s interface' % interface_name)
Esempio n. 22
0
	def GetAll(self, interface_name):
		if interface_name == 'org.freedesktop.Secret.Item':
			return {
				'Locked': self.get_locked(),
				'Attributes': dbus.Dictionary(self.attributes, signature='ss', variant_level=1),
				'Label': self.label,
				'Created': dbus.UInt64(self.created),
				'Modified': dbus.UInt64(self.modified),
				'Type': self.type
			}
		else:
			raise InvalidArgs('Unknown %s interface' % interface_name)
Esempio n. 23
0
    def update(self, driver, app, xml):
        """
        Handler called when an update is received from the Turk server through XMPP.
        """
        print 'new update received:'
        print xml
        try:
            tree = parseString(xml)

            command = tree.getElementsByTagName('command')[0]
            ctype = command.getAttribute('type')

            if ctype == 'time':
                # Parse time value
                timestamp = int(command.childNodes[0].nodeValue)
                time = datetime.fromtimestamp(timestamp)

                # Set the time
                self.set_time(time)

            elif ctype == 'timezone':
                # Parse time value
                self.timezone = int(command.childNodes[0].nodeValue)

            elif ctype == 'text':
                # Send 4-character string
                text = command.childNodes[0].nodeValue[:4]
                self.set_text(text)

            elif ctype in ['on', 'off']:
                command = {'on': SET_ON_COMMAND, 'off': SET_OFF_COMMAND}[ctype]
                print 'sending %s command' % (ctype)
                self.xbee.SendData(dbus.ByteArray(command),
                                   dbus.UInt64(self.device_addr), 2)

            elif ctype == 'color':
                # Parse hex color into RGB values
                color = command.childNodes[0].nodeValue.lstrip('# \n\r')
                red, green, blue = [
                    int(color[i:i + 2], 16) for i in range(0, 6, 2)
                ]

                msg = SET_COLOR_COMMAND % (chr(red), chr(green), chr(blue))

                print 'setting color to #%02X%02X%02X' % (red, green, blue)
                self.xbee.SendData(dbus.ByteArray(msg),
                                   dbus.UInt64(self.device_addr), 1)

        except Exception, e:
            # emit an error signal for bridge
            self.Error(e.message)
            print e
Esempio n. 24
0
def enhancedPositionPositionUpdateHandler(arg):
    # get the position
    enhancedPosition = enhancedPositionInterface.GetPositionInfo(arg)
    if (arg & Genivi.ENHANCEDPOSITIONSERVICE_LATITUDE
        ) == Genivi.ENHANCEDPOSITIONSERVICE_LATITUDE:
        latitude = float(enhancedPosition[1][dbus.UInt64(
            Genivi.ENHANCEDPOSITIONSERVICE_LATITUDE)])
        displayLatitude("{:.3f}".format(latitude))
    if (arg & Genivi.ENHANCEDPOSITIONSERVICE_LONGITUDE
        ) == Genivi.ENHANCEDPOSITIONSERVICE_LONGITUDE:
        longitude = float(enhancedPosition[1][dbus.UInt64(
            Genivi.ENHANCEDPOSITIONSERVICE_LONGITUDE)])
        displayLongitude("{:.3f}".format(longitude))
Esempio n. 25
0
	def _create_raid5_thin_pool(self, vg=None):

		meta_name = "meta_r5"
		data_name = "data_r5"

		if not vg:
			pv_paths = []
			for pp in self.objs[PV_INT]:
				pv_paths.append(pp.object_path)

			vg = self._vg_create(pv_paths).Vg

		lv_meta_path = self.handle_return(
			vg.LvCreateRaid(
				dbus.String(meta_name),
				dbus.String("raid5"),
				dbus.UInt64(mib(4)),
				dbus.UInt32(0),
				dbus.UInt32(0),
				dbus.Int32(g_tmo),
				EOD)
		)
		self._validate_lookup("%s/%s" % (vg.Name, meta_name), lv_meta_path)

		lv_data_path = self.handle_return(
			vg.LvCreateRaid(
				dbus.String(data_name),
				dbus.String("raid5"),
				dbus.UInt64(mib(16)),
				dbus.UInt32(0),
				dbus.UInt32(0),
				dbus.Int32(g_tmo),
				EOD)
		)

		self._validate_lookup("%s/%s" % (vg.Name, data_name), lv_data_path)

		thin_pool_path = self.handle_return(
			vg.CreateThinPool(
				dbus.ObjectPath(lv_meta_path),
				dbus.ObjectPath(lv_data_path),
				dbus.Int32(g_tmo), EOD)
		)

		# Get thin pool client proxy
		thin_pool = ClientProxy(self.bus, thin_pool_path,
								interfaces=(LV_COMMON_INT,
											LV_INT,
											THINPOOL_INT))

		return vg, thin_pool
Esempio n. 26
0
    def test_20_thin(self):
        '''Test thin volumes functionality'''

        vgname = 'udisks_test_thin_vg'

        # Use all the virtual devices
        devs = dbus.Array()
        for d in self.vdevs:
            dev_obj = self.get_object('/block_devices/' + os.path.basename(d))
            self.assertIsNotNone(dev_obj)
            devs.append(dev_obj)
        vg = self._create_vg(vgname, devs)
        self.addCleanup(self._remove_vg, vg)

        # Create thin pool on the VG
        vgsize = int(self.get_property_raw(vg, '.VolumeGroup', 'FreeSize'))
        tpname = 'udisks_test_tp'
        tp_path = vg.CreateThinPoolVolume(tpname, dbus.UInt64(vgsize), self.no_options,
                                          dbus_interface=self.iface_prefix + '.VolumeGroup')
        self.assertIsNotNone(tp_path)

        ret, _out = self.run_command('lvs %s' % os.path.join(vgname, tpname))
        self.assertEqual(ret, 0)

        tp = self.bus.get_object(self.iface_prefix, tp_path)
        tpsize = self.get_property(tp, '.LogicalVolume', 'Size')

        # check that we report same size as lvs (udisks includes metadata so we need to add it too)
        _ret, dsize = self.run_command('lvs -olv_size --noheadings --units=b --nosuffix %s' % os.path.join(vgname, tpname))
        _ret, msize = self.run_command('lvs -olv_metadata_size --noheadings --units=b --nosuffix %s' % os.path.join(vgname, tpname))
        tpsize.assertEqual(int(dsize.strip()) + int(msize.strip()))

        dbus_type = self.get_property(tp, '.LogicalVolume', 'Type')
        dbus_type.assertEqual("pool")

        # Create thin volume in the pool with virtual size twice the backing pool
        tvname = 'udisks_test_tv'
        tv_path = vg.CreateThinVolume(tvname, dbus.UInt64(int(tpsize.value) * 2), tp, self.no_options,
                                      dbus_interface=self.iface_prefix + '.VolumeGroup')
        tv = self.bus.get_object(self.iface_prefix, tv_path)
        self.assertIsNotNone(tv)

        ret, _out = self.run_command('lvs %s' % os.path.join(vgname, tvname))
        self.assertEqual(ret, 0)

        # Check the block device of the thin volume
        lv_block_path = tv.Activate(self.no_options, dbus_interface=self.iface_prefix + '.LogicalVolume')
        lv_block = self.bus.get_object(self.iface_prefix, lv_block_path)
        self.assertIsNotNone(lv_block)
        blocksize = self.get_property(lv_block, '.Block', 'Size')
        blocksize.assertGreater(vgsize)
Esempio n. 27
0
    def test_resize(self):
        passwd = 'test'

        device = self.get_device(self.vdevs[0])
        self._create_luks(device, passwd)
        self.addCleanup(self._remove_luks, device)
        self.udev_settle()

        _ret, clear_dev = self.run_command('ls /sys/block/%s/holders/' %
                                           os.path.basename(self.vdevs[0]))
        self.assertEqual(_ret, 0)
        clear_size = self.get_block_size(clear_dev)

        # kernel keyring support and no passphrase for LUKS 2 given = fail
        if self._get_key_location('/dev/' + clear_dev) == 'keyring':
            msg = 'org.freedesktop.UDisks2.Error.Failed: Error resizing encrypted device /dev/dm-[0-9]+: Insufficient persmissions to resize device. *'
            with six.assertRaisesRegex(self, dbus.exceptions.DBusException,
                                       msg):
                device.Resize(dbus.UInt64(100 * 1024 * 1024),
                              self.no_options,
                              dbus_interface=self.iface_prefix + '.Encrypted')

        # wrong passphrase
        d = dbus.Dictionary(signature='sv')
        d['passphrase'] = 'wrongpassphrase'
        msg = 'org.freedesktop.UDisks2.Error.Failed: Error resizing encrypted device /dev/dm-[0-9]+: '\
              'Failed to activate device: (Operation not permitted|Incorrect passphrase)'
        with six.assertRaisesRegex(self, dbus.exceptions.DBusException, msg):
            device.Resize(dbus.UInt64(100 * 1024 * 1024),
                          d,
                          dbus_interface=self.iface_prefix + '.Encrypted')

        # right passphrase
        d = dbus.Dictionary(signature='sv')
        d['passphrase'] = passwd
        device.Resize(dbus.UInt64(100 * 1024 * 1024),
                      d,
                      dbus_interface=self.iface_prefix + '.Encrypted')

        clear_size2 = self.get_block_size(clear_dev)
        self.assertEqual(clear_size2, 100 * 1024 * 1024)

        # resize back to the original size (using binary passphrase)
        d = dbus.Dictionary(signature='sv')
        d['keyfile_contents'] = self.str_to_ay(passwd, False)
        device.Resize(dbus.UInt64(clear_size),
                      d,
                      dbus_interface=self.iface_prefix + '.Encrypted')

        clear_size3 = self.get_block_size(clear_dev)
        self.assertEqual(clear_size3, clear_size)
Esempio n. 28
0
    def _pv_devices(uuid):
        rc = []
        for pv in sorted(cfg.db.lv_contained_pv(uuid)):
            (pv_uuid, pv_name, pv_segs) = pv
            pv_obj = cfg.om.get_object_path_by_uuid_lvm_id(pv_uuid, pv_name)

            segs_decorate = []
            for i in pv_segs:
                segs_decorate.append(
                    (dbus.UInt64(i[0]), dbus.UInt64(i[1]), dbus.String(i[2])))

            rc.append((dbus.ObjectPath(pv_obj), segs_decorate))

        return dbus.Array(rc, signature="(oa(tts))")
Esempio n. 29
0
def load(mock, parameters):
    mock.AddMethods(MAIN_IFACE, [
        ('PowerOff', 'b', '', ''),
        ('Reboot', 'b', '', ''),
        ('Suspend', 'b', '', ''),
        ('Hibernate', 'b', '', ''),
        ('HybridSleep', 'b', '', ''),
        ('SuspendThenHibernate', 'b', '', ''),
        ('CanPowerOff', '', 's', 'ret = "%s"' % parameters.get('CanPowerOff', 'yes')),
        ('CanReboot', '', 's', 'ret = "%s"' % parameters.get('CanReboot', 'yes')),
        ('CanSuspend', '', 's', 'ret = "%s"' % parameters.get('CanSuspend', 'yes')),
        ('CanHibernate', '', 's', 'ret = "%s"' % parameters.get('CanHibernate', 'yes')),
        ('CanHybridSleep', '', 's', 'ret = "%s"' % parameters.get('CanHybridSleep', 'yes')),
        ('CanSuspendThenHibernate', '', 's', 'ret = "%s"' % parameters.get('CanSuspendThenHibernate', 'yes')),

        ('GetSession', 's', 'o', 'ret = "/org/freedesktop/login1/session/" + args[0]'),
        ('ActivateSession', 's', '', ''),
        ('ActivateSessionOnSeat', 'ss', '', ''),
        ('KillSession', 'sss', '', ''),
        ('LockSession', 's', '', ''),
        ('LockSessions', '', '', ''),
        ('ReleaseSession', 's', '', ''),
        ('TerminateSession', 's', '', ''),
        ('UnlockSession', 's', '', ''),
        ('UnlockSessions', '', '', ''),

        ('GetSeat', 's', 'o', 'ret = "/org/freedesktop/login1/seat/" + args[0]'),
        ('ListSeats', '', 'a(so)', 'ret = [(k.split("/")[-1], k) for k in objects.keys() if "/seat/" in k]'),
        ('TerminateSeat', 's', '', ''),

        ('GetUser', 'u', 'o', 'ret = "/org/freedesktop/login1/user/%u" % args[0]'),
        ('KillUser', 'us', '', ''),
        ('TerminateUser', 'u', '', ''),

        ('Inhibit', 'ssss', 'h', 'ret = %i' % parameters.get('Inhibit_fd', 3)),
        ('ListInhibitors', '', 'a(ssssuu)', 'ret = []'),
    ])

    mock.AddProperties(MAIN_IFACE,
                       dbus.Dictionary({
                           'IdleHint': parameters.get('IdleHint', False),
                           'IdleAction': parameters.get('IdleAction', 'ignore'),
                           'IdleSinceHint': dbus.UInt64(parameters.get('IdleSinceHint', 0)),
                           'IdleSinceHintMonotonic': dbus.UInt64(parameters.get('IdleSinceHintMonotonic', 0)),
                           'IdleActionUSec': dbus.UInt64(parameters.get('IdleActionUSec', 1)),
                           'PreparingForShutdown': parameters.get('PreparingForShutdown', False),
                           'PreparingForSleep': parameters.get('PreparingForSleep', False),
                       }, signature='sv'))
Esempio n. 30
0
	def test_lv_resize(self):

		pv_paths = []
		for pp in self.objs[PV_INT]:
			pv_paths.append(pp.object_path)

		vg = self._vg_create(pv_paths).Vg
		lv = self._create_lv(vg=vg, size=mib(16))

		for size in \
			[
			lv.LvCommon.SizeBytes + 4194304,
			lv.LvCommon.SizeBytes - 4194304,
			lv.LvCommon.SizeBytes + 2048,
			lv.LvCommon.SizeBytes - 2048]:

			pv_in_use = [i[0] for i in lv.LvCommon.Devices]
			# Select a PV in the VG that isn't in use
			pv_empty = [p for p in vg.Pvs if p not in pv_in_use]

			prev = lv.LvCommon.SizeBytes

			if len(pv_empty):
				p = ClientProxy(self.bus, pv_empty[0], interfaces=(PV_INT,))

				rc = self.handle_return(
					lv.Lv.Resize(
						dbus.UInt64(size),
						dbus.Array(
							[[p.object_path, 0, p.Pv.PeCount - 1]], '(oii)'),
						dbus.Int32(g_tmo), EOD))
			else:
				rc = self.handle_return(
					lv.Lv.Resize(
						dbus.UInt64(size),
						dbus.Array([], '(oii)'),
						dbus.Int32(g_tmo), EOD))

			self.assertEqual(rc, '/')
			self._check_consistency()

			lv.update()

			if prev < size:
				self.assertTrue(lv.LvCommon.SizeBytes > prev)
			else:
				# We are testing re-sizing to same size too...
				self.assertTrue(lv.LvCommon.SizeBytes <= prev)