Revision 091c0335

b/image_creator/os_type/__init__.py
128 128
        self.image = image
129 129

  
130 130
        self.root = image.root
131
        self.g = image.g
132 131
        self.out = image.out
133 132

  
134 133
        self.needed_sysprep_params = {}
......
141 140
        # Many guestfs compilations don't support scrub
142 141
        self._scrub_support = True
143 142
        try:
144
            self.g.available(['scrub'])
143
            self.image.g.available(['scrub'])
145 144
        except RuntimeError:
146 145
            self._scrub_support = False
147 146

  
......
288 287
        """Umount all mounted filesystems."""
289 288

  
290 289
        self.out.output("Umounting the media ...", False)
291
        self.g.umount_all()
290
        self.image.g.umount_all()
292 291
        self.mounted = False
293 292
        self.out.success('done')
294 293

  
......
299 298
    @add_prefix
300 299
    def _ls(self, directory):
301 300
        """List the name of all files under a directory"""
302
        return self.g.ls(directory)
301
        return self.image.g.ls(directory)
303 302

  
304 303
    @add_prefix
305 304
    def _find(self, directory):
306 305
        """List the name of all files recursively under a directory"""
307
        return self.g.find(directory)
306
        return self.image.g.find(directory)
308 307

  
309 308
    def _foreach_file(self, directory, action, **kargs):
310 309
        """Perform an action recursively on all files under a directory.
......
333 332
        ftype = None if 'ftype' not in kargs else kargs['ftype']
334 333
        has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
335 334

  
336
        for f in self.g.readdir(directory):
335
        for f in self.image.g.readdir(directory):
337 336
            if f['name'] in ('.', '..'):
338 337
                continue
339 338

  
......
350 349

  
351 350
    def _do_collect_metadata(self):
352 351
        """helper method for collect_metadata"""
353
        self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
354
        self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
355
        self.meta['OS'] = self.g.inspect_get_distro(self.root)
352
        self.meta['ROOT_PARTITION'] = \
353
            "%d" % self.image.g.part_to_partnum(self.root)
354
        self.meta['OSFAMILY'] = self.image.g.inspect_get_type(self.root)
355
        self.meta['OS'] = self.image.g.inspect_get_distro(self.root)
356 356
        if self.meta['OS'] == "unknown":
357 357
            self.meta['OS'] = self.meta['OSFAMILY']
358
        self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
358
        self.meta['DESCRIPTION'] = self.image.g.inspect_get_product_name(self.root)
359 359

  
360 360
    def _do_mount(self, readonly):
361 361
        """helper method for mount"""
362 362
        try:
363
            self.g.mount_options('ro' if readonly else 'rw', self.root, '/')
363
            self.image.g.mount_options(
364
                'ro' if readonly else 'rw', self.root, '/')
364 365
        except RuntimeError as msg:
365 366
            self.out.warn("unable to mount the root partition: %s" % msg)
366 367
            return False
b/image_creator/os_type/freebsd.py
49 49

  
50 50
        master_passwd = []
51 51

  
52
        for line in self.g.cat('/etc/master.passwd').splitlines():
52
        for line in self.image.g.cat('/etc/master.passwd').splitlines():
53 53

  
54 54
            # Check for empty or comment lines
55 55
            if len(line.split('#')[0]) == 0:
......
62 62

  
63 63
            master_passwd.append(":".join(fields))
64 64

  
65
        self.g.write('/etc/master.passwd', "\n".join(master_passwd) + '\n')
65
        self.image.g.write(
66
            '/etc/master.passwd', "\n".join(master_passwd) + '\n')
66 67

  
67 68
        # Make sure no one can login on the system
68
        self.g.rm_rf('/etc/spwd.db')
69
        self.image.g.rm_rf('/etc/spwd.db')
69 70

  
70 71
    def _do_collect_metadata(self):
71 72
        """Collect metadata about the OS"""
......
88 89
            '^([^:]+):((?:![^:]+)|(?:[^!*][^:]+)|):(?:[^:]*:){7}(?:[^:]*)'
89 90
        )
90 91

  
91
        for line in self.g.cat('/etc/master.passwd').splitlines():
92
        for line in self.image.g.cat('/etc/master.passwd').splitlines():
92 93
            line = line.split('#')[0]
93 94
            match = regexp.match(line)
94 95
            if not match:
......
120 121
                group3 = int(match.group(3))
121 122
                dev = '/dev/sd%c%d' % (chr(ord('a') + group2), group3)
122 123
            try:
123
                self.g.mount_vfs(mopts, 'ufs', dev, mp)
124
                self.image.g.mount_vfs(mopts, 'ufs', dev, mp)
124 125
            except RuntimeError as msg:
125 126
                if mp in critical_mpoints:
126 127
                    self.out.warn('unable to mount %s. Reason: %s' % (mp, msg))
b/image_creator/os_type/linux.py
59 59
        passwd = []
60 60
        removed_users = {}
61 61
        metadata_users = self.meta['USERS'].split()
62
        for line in self.g.cat('/etc/passwd').splitlines():
62
        for line in self.image.g.cat('/etc/passwd').splitlines():
63 63
            fields = line.split(':')
64 64
            if int(fields[2]) > 1000:
65 65
                removed_users[fields[0]] = fields
......
75 75
        if not len(self.meta['USERS']):
76 76
            del self.meta['USERS']
77 77

  
78
        self.g.write('/etc/passwd', '\n'.join(passwd) + '\n')
78
        self.image.g.write('/etc/passwd', '\n'.join(passwd) + '\n')
79 79

  
80 80
        # Remove the corresponding /etc/shadow entries
81 81
        shadow = []
82
        for line in self.g.cat('/etc/shadow').splitlines():
82
        for line in self.image.g.cat('/etc/shadow').splitlines():
83 83
            fields = line.split(':')
84 84
            if fields[0] not in removed_users:
85 85
                shadow.append(':'.join(fields))
86 86

  
87
        self.g.write('/etc/shadow', "\n".join(shadow) + '\n')
87
        self.image.g.write('/etc/shadow', "\n".join(shadow) + '\n')
88 88

  
89 89
        # Remove the corresponding /etc/group entries
90 90
        group = []
91
        for line in self.g.cat('/etc/group').splitlines():
91
        for line in self.image.g.cat('/etc/group').splitlines():
92 92
            fields = line.split(':')
93 93
            # Remove groups tha have the same name as the removed users
94 94
            if fields[0] not in removed_users:
95 95
                group.append(':'.join(fields))
96 96

  
97
        self.g.write('/etc/group', '\n'.join(group) + '\n')
97
        self.image.g.write('/etc/group', '\n'.join(group) + '\n')
98 98

  
99 99
        # Remove home directories
100 100
        for home in [field[5] for field in removed_users.values()]:
101
            if self.g.is_dir(home) and home.startswith('/home/'):
102
                self.g.rm_rf(home)
101
            if self.image.g.is_dir(home) and home.startswith('/home/'):
102
                self.image.g.rm_rf(home)
103 103

  
104 104
    @sysprep('Cleaning up password & locking all user accounts')
105 105
    def cleanup_passwords(self):
......
107 107

  
108 108
        shadow = []
109 109

  
110
        for line in self.g.cat('/etc/shadow').splitlines():
110
        for line in self.image.g.cat('/etc/shadow').splitlines():
111 111
            fields = line.split(':')
112 112
            if fields[1] not in ('*', '!'):
113 113
                fields[1] = '!'
114 114

  
115 115
            shadow.append(":".join(fields))
116 116

  
117
        self.g.write('/etc/shadow', "\n".join(shadow) + '\n')
117
        self.image.g.write('/etc/shadow', "\n".join(shadow) + '\n')
118 118

  
119 119
    @sysprep('Fixing acpid powerdown action')
120 120
    def fix_acpid(self):
......
126 126
                          'shutdown -h now "Power button pressed"\n'
127 127

  
128 128
        events_dir = '/etc/acpi/events'
129
        if not self.g.is_dir(events_dir):
129
        if not self.image.g.is_dir(events_dir):
130 130
            self.out.warn("No acpid event directory found")
131 131
            return
132 132

  
133 133
        event_exp = re.compile('event=(.+)', re.I)
134 134
        action_exp = re.compile('action=(.+)', re.I)
135
        for events_file in self.g.readdir(events_dir):
135
        for events_file in self.image.g.readdir(events_dir):
136 136
            if events_file['ftyp'] != 'r':
137 137
                continue
138 138

  
139 139
            fullpath = "%s/%s" % (events_dir, events_file['name'])
140 140
            event = ""
141 141
            action = ""
142
            for line in self.g.cat(fullpath).splitlines():
142
            for line in self.image.g.cat(fullpath).splitlines():
143 143
                match = event_exp.match(line)
144 144
                if match:
145 145
                    event = match.group(1)
......
151 151

  
152 152
            if event.strip() in ("button[ /]power", "button/power.*"):
153 153
                if action:
154
                    if not self.g.is_file(action):
154
                    if not self.image.g.is_file(action):
155 155
                        self.out.warn("Acpid action file: %s does not exist" %
156 156
                                      action)
157 157
                        return
158
                    self.g.copy_file_to_file(action,
158
                    self.image.g.copy_file_to_file(action,
159 159
                                             "%s.orig.snf-image-creator-%d" %
160 160
                                             (action, time.time()))
161
                    self.g.write(action, powerbtn_action)
161
                    self.image.g.write(action, powerbtn_action)
162 162
                    return
163 163
                else:
164 164
                    self.out.warn("Acpid event file %s does not contain and "
......
182 182
        """
183 183

  
184 184
        rule_file = '/etc/udev/rules.d/70-persistent-net.rules'
185
        if self.g.is_file(rule_file):
186
            self.g.rm(rule_file)
185
        if self.image.g.is_file(rule_file):
186
            self.image.g.rm(rule_file)
187 187

  
188 188
    @sysprep('Removing swap entry from fstab')
189 189
    def remove_swap_entry(self):
......
194 194
        """
195 195

  
196 196
        new_fstab = ""
197
        fstab = self.g.cat('/etc/fstab')
197
        fstab = self.image.g.cat('/etc/fstab')
198 198
        for line in fstab.splitlines():
199 199

  
200 200
            entry = line.split('#')[0].strip().split()
......
203 203

  
204 204
            new_fstab += "%s\n" % line
205 205

  
206
        self.g.write('/etc/fstab', new_fstab)
206
        self.image.g.write('/etc/fstab', new_fstab)
207 207

  
208 208
    @sysprep('Replacing fstab & grub non-persistent device references')
209 209
    def use_persistent_block_device_names(self):
......
221 221
        """Replaces non-persistent device name occurencies with persistent
222 222
        ones in GRUB1 configuration files.
223 223
        """
224
        if self.g.is_file('/boot/grub/menu.lst'):
224
        if self.image.g.is_file('/boot/grub/menu.lst'):
225 225
            grub1 = '/boot/grub/menu.lst'
226
        elif self.g.is_file('/etc/grub.conf'):
226
        elif self.image.g.is_file('/etc/grub.conf'):
227 227
            grub1 = '/etc/grub.conf'
228 228
        else:
229 229
            return
230 230

  
231
        self.g.aug_init('/', 0)
231
        self.image.g.aug_init('/', 0)
232 232
        try:
233
            roots = self.g.aug_match('/files%s/title[*]/kernel/root' % grub1)
233
            roots = self.image.g.aug_match(
234
                '/files%s/title[*]/kernel/root' % grub1)
234 235
            for root in roots:
235
                dev = self.g.aug_get(root)
236
                dev = self.image.g.aug_get(root)
236 237
                if not self._is_persistent(dev):
237 238
                    # This is not always correct. Grub may contain root entries
238 239
                    # for other systems, but we only support 1 OS per hard
239 240
                    # disk, so this shouldn't harm.
240
                    self.g.aug_set(root, new_root)
241
                    self.image.g.aug_set(root, new_root)
241 242
        finally:
242
            self.g.aug_save()
243
            self.g.aug_close()
243
            self.image.g.aug_save()
244
            self.image.g.aug_close()
244 245

  
245 246
    def _persistent_fstab(self):
246 247
        """Replaces non-persistent device name occurencies in /etc/fstab with
247 248
        persistent ones.
248 249
        """
249
        mpoints = self.g.mountpoints()
250
        mpoints = self.image.g.mountpoints()
250 251
        if len(mpoints) == 0:
251 252
            pass  # TODO: error handling
252 253

  
......
254 255

  
255 256
        root_dev = None
256 257
        new_fstab = ""
257
        fstab = self.g.cat('/etc/fstab')
258
        fstab = self.image.g.cat('/etc/fstab')
258 259
        for line in fstab.splitlines():
259 260

  
260 261
            line, dev, mpoint = self._convert_fstab_line(line, device_dict)
......
263 264
            if mpoint == '/':
264 265
                root_dev = dev
265 266

  
266
        self.g.write('/etc/fstab', new_fstab)
267
        self.image.g.write('/etc/fstab', new_fstab)
267 268
        if root_dev is None:
268 269
            pass  # TODO: error handling
269 270

  
......
312 313
        users = []
313 314
        regexp = re.compile(r'(\S+):((?:!\S+)|(?:[^!*]\S+)|):(?:\S*:){6}')
314 315

  
315
        for line in self.g.cat('/etc/shadow').splitlines():
316
        for line in self.image.g.cat('/etc/shadow').splitlines():
316 317
            match = regexp.match(line)
317 318
            if not match:
318 319
                continue
......
334 335
        if dev in self._uuid:
335 336
            return self._uuid[dev]
336 337

  
337
        uuid = self.g.vfs_uuid(dev)
338
        uuid = self.image.g.vfs_uuid(dev)
338 339
        assert len(uuid)
339 340
        self._uuid[dev] = uuid
340 341
        return uuid
b/image_creator/os_type/slackware.py
47 47
        # In slackware the metadata about installed packages are
48 48
        # stored in /var/log/packages. Clearing all /var/log files
49 49
        # will destroy the package management system.
50
        self._foreach_file('/var/log', self.g.truncate, ftype='r',
50
        self._foreach_file('/var/log', self.image.g.truncate, ftype='r',
51 51
                           exclude='/var/log/packages')
52 52

  
53 53
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :
b/image_creator/os_type/ubuntu.py
45 45
        """Collect metadata about the OS"""
46 46

  
47 47
        super(Ubuntu, self)._do_collect_metadata()
48
        apps = self.g.inspect_list_applications(self.root)
48
        apps = self.image.g.inspect_list_applications(self.root)
49 49
        for app in apps:
50 50
            if app['app_name'] == 'kubuntu-desktop':
51 51
                self.meta['OS'] = 'kubuntu'
b/image_creator/os_type/unix.py
53 53
        """Return mountpoints in the correct order.
54 54
        / should be mounted before /boot or /usr, /usr befor /usr/bin ...
55 55
        """
56
        mps = self.g.inspect_get_mountpoints(self.root)
56
        mps = self.image.g.inspect_get_mountpoints(self.root)
57 57

  
58 58
        def compare(a, b):
59 59
            if len(a[0]) > len(b[0]):
......
75 75
        mopts = 'ro' if readonly else 'rw'
76 76
        for mp, dev in self._mountpoints():
77 77
            try:
78
                self.g.mount_options(mopts, dev, mp)
78
                self.image.g.mount_options(mopts, dev, mp)
79 79
            except RuntimeError as msg:
80 80
                if mp in critical_mpoints:
81 81
                    self.out.warn('unable to mount %s. Reason: %s' % (mp, msg))
......
89 89
    def cleanup_cache(self):
90 90
        """Remove all regular files under /var/cache"""
91 91

  
92
        self._foreach_file('/var/cache', self.g.rm, ftype='r')
92
        self._foreach_file('/var/cache', self.image.g.rm, ftype='r')
93 93

  
94 94
    @sysprep('Removing files under /tmp and /var/tmp')
95 95
    def cleanup_tmp(self):
96 96
        """Remove all files under /tmp and /var/tmp"""
97 97

  
98
        self._foreach_file('/tmp', self.g.rm_rf, maxdepth=1)
99
        self._foreach_file('/var/tmp', self.g.rm_rf, maxdepth=1)
98
        self._foreach_file('/tmp', self.image.g.rm_rf, maxdepth=1)
99
        self._foreach_file('/var/tmp', self.image.g.rm_rf, maxdepth=1)
100 100

  
101 101
    @sysprep('Emptying all files under /var/log')
102 102
    def cleanup_log(self):
103 103
        """Empty all files under /var/log"""
104 104

  
105
        self._foreach_file('/var/log', self.g.truncate, ftype='r')
105
        self._foreach_file('/var/log', self.image.g.truncate, ftype='r')
106 106

  
107 107
    @sysprep('Removing files under /var/mail & /var/spool/mail', enabled=False)
108 108
    def cleanup_mail(self):
109 109
        """Remove all files under /var/mail and /var/spool/mail"""
110 110

  
111
        if self.g.is_dir('/var/spool/mail'):
112
            self._foreach_file('/var/spool/mail', self.g.rm_rf, maxdepth=1)
111
        if self.image.g.is_dir('/var/spool/mail'):
112
            self._foreach_file('/var/spool/mail', self.image.g.rm_rf,
113
                               maxdepth=1)
113 114

  
114
        self._foreach_file('/var/mail', self.g.rm_rf, maxdepth=1)
115
        self._foreach_file('/var/mail', self.image.g.rm_rf, maxdepth=1)
115 116

  
116 117
    @sysprep('Removing sensitive user data')
117 118
    def cleanup_userdata(self):
118 119
        """Delete sensitive userdata"""
119 120

  
120 121
        homedirs = ['/root']
121
        if self.g.is_dir('/home/'):
122
        if self.image.g.is_dir('/home/'):
122 123
            homedirs += self._ls('/home/')
123 124

  
124
        action = self.g.rm_rf
125
        action = self.image.g.rm_rf
125 126
        if self._scrub_support:
126
            action = self.g.scrub_file
127
            action = self.image.g.scrub_file
127 128
        else:
128 129
            self.out.warn("Sensitive data won't be scrubbed (not supported)")
129 130

  
130 131
        for homedir in homedirs:
131 132
            for data in self.sensitive_userdata:
132 133
                fname = "%s/%s" % (homedir, data)
133
                if self.g.is_file(fname):
134
                if self.image.g.is_file(fname):
134 135
                    action(fname)
135
                elif self.g.is_dir(fname):
136
                elif self.image.g.is_dir(fname):
136 137
                    self._foreach_file(fname, action, ftype='r')
137 138

  
138 139
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :
b/image_creator/os_type/windows.py
116 116
    def __init__(self, image, **kargs):
117 117
        super(Windows, self).__init__(image, **kargs)
118 118

  
119
        device = self.g.part_to_dev(self.root)
119
        device = self.image.g.part_to_dev(self.root)
120 120

  
121
        self.last_part_num = self.g.part_list(device)[-1]['part_num']
121
        self.last_part_num = self.image.g.part_list(device)[-1]['part_num']
122 122
        self.last_drive = None
123 123
        self.system_drive = None
124 124

  
125
        for drive, partition in self.g.inspect_get_drive_mappings(self.root):
125
        for drive, partition in self.image.g.inspect_get_drive_mappings(self.root):
126 126
            if partition == "%s%d" % (device, self.last_part_num):
127 127
                self.last_drive = drive
128 128
            if partition == self.root:
......
130 130

  
131 131
        assert self.system_drive
132 132

  
133
        self.product_name = self.g.inspect_get_product_name(self.root)
133
        self.product_name = self.image.g.inspect_get_product_name(self.root)
134 134
        self.syspreped = False
135 135

  
136 136
    @sysprep('Disabling IPv6 privacy extensions')
......
291 291
            firewall_states = self._update_firewalls(0, 0, 0)
292 292

  
293 293
            # Delete the pagefile. It will be recreated when the system boots
294
            systemroot = self.g.inspect_get_windows_systemroot(self.root)
294
            systemroot = self.image.g.inspect_get_windows_systemroot(self.root)
295 295
            try:
296 296
                pagefile = "%s/pagefile.sys" % systemroot
297
                self.g.rm_rf(self.g.case_sensitive_path(pagefile))
297
                self.image.g.rm_rf(self.image.g.case_sensitive_path(pagefile))
298 298
            except RuntimeError:
299 299
                pass
300 300

  
......
302 302
            self.umount()
303 303

  
304 304
        self.out.output("Shutting down helper VM ...", False)
305
        self.g.sync()
305
        self.image.g.sync()
306 306
        # guestfs_shutdown which is the prefered way to shutdown the backend
307 307
        # process was introduced in version 1.19.16
308 308
        if check_guestfs_version(self.g, 1, 19, 16) >= 0:
309
            self.g.shutdown()
309
            self.image.g.shutdown()
310 310
        else:
311
            self.g.kill_subprocess()
311
            self.image.g.kill_subprocess()
312 312

  
313 313
        self.out.success('done')
314 314

  
......
383 383
            finally:
384 384
                self.out.output("Relaunching helper VM (may take a while) ...",
385 385
                                False)
386
                self.g.launch()
386
                self.image.g.launch()
387 387
                self.out.success('done')
388 388

  
389 389
                self.mount(readonly=False)
......
426 426
    def _registry_file_path(self, regfile):
427 427
        """Retrieves the case sensitive path to a registry file"""
428 428

  
429
        systemroot = self.g.inspect_get_windows_systemroot(self.root)
429
        systemroot = self.image.g.inspect_get_windows_systemroot(self.root)
430 430
        path = "%s/system32/config/%s" % (systemroot, regfile)
431 431
        try:
432
            path = self.g.case_sensitive_path(path)
432
            path = self.image.g.case_sensitive_path(path)
433 433
        except RuntimeError as error:
434 434
            raise FatalError("Unable to retrieve registry file: %s. Reason: %s"
435 435
                             % (regfile, str(error)))
......
446 446
        softwarefd, software = tempfile.mkstemp()
447 447
        try:
448 448
            os.close(softwarefd)
449
            self.g.download(path, software)
449
            self.image.g.download(path, software)
450 450

  
451 451
            h = hivex.Hivex(software, write=True)
452 452

  
......
511 511

  
512 512
            h.commit(None)
513 513

  
514
            self.g.upload(software, path)
514
            self.image.g.upload(software, path)
515 515
        finally:
516 516
            os.unlink(software)
517 517

  
......
537 537
        systemfd, system = tempfile.mkstemp()
538 538
        try:
539 539
            os.close(systemfd)
540
            self.g.download(path, system)
540
            self.image.g.download(path, system)
541 541

  
542 542
            h = hivex.Hivex(system, write=True)
543 543

  
......
569 569
                           'value': struct.pack("<I", new_values.pop(0))})
570 570

  
571 571
            h.commit(None)
572
            self.g.upload(system, path)
572
            self.image.g.upload(system, path)
573 573

  
574 574
        finally:
575 575
            os.unlink(system)
......
598 598
        softwarefd, software = tempfile.mkstemp()
599 599
        try:
600 600
            os.close(softwarefd)
601
            self.g.download(path, software)
601
            self.image.g.download(path, software)
602 602

  
603 603
            h = hivex.Hivex(software, write=True)
604 604

  
......
625 625
            h.node_set_value(key, new_value)
626 626
            h.commit(None)
627 627

  
628
            self.g.upload(software, path)
628
            self.image.g.upload(software, path)
629 629

  
630 630
        finally:
631 631
            os.unlink(software)
......
642 642
        samfd, sam = tempfile.mkstemp()
643 643
        try:
644 644
            os.close(samfd)
645
            self.g.download(self._registry_file_path('SAM'), sam)
645
            self.image.g.download(self._registry_file_path('SAM'), sam)
646 646

  
647 647
            h = hivex.Hivex(sam)
648 648

  

Also available in: Unified diff