Pass the Image instance to the os_type classes
[snf-image-creator] / image_creator / os_type / freebsd.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright 2012 GRNET S.A. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
7 # conditions are met:
8 #
9 #   1. Redistributions of source code must retain the above
10 #      copyright notice, this list of conditions and the following
11 #      disclaimer.
12 #
13 #   2. Redistributions in binary form must reproduce the above
14 #      copyright notice, this list of conditions and the following
15 #      disclaimer in the documentation and/or other materials
16 #      provided with the distribution.
17 #
18 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 # POSSIBILITY OF SUCH DAMAGE.
30 #
31 # The views and conclusions contained in the software and
32 # documentation are those of the authors and should not be
33 # interpreted as representing official policies, either expressed
34 # or implied, of GRNET S.A.
35
36 """This module hosts OS-specific code for FreeBSD."""
37
38 from image_creator.os_type.unix import Unix, sysprep
39
40 import re
41
42
43 class Freebsd(Unix):
44     """OS class for FreeBSD Unix-like os"""
45
46     @sysprep()
47     def cleanup_password(self, print_header=True):
48         """Remove all passwords and lock all user accounts"""
49
50         if print_header:
51             self.out.output("Cleaning up passwords & locking all user "
52                             "accounts")
53
54         master_passwd = []
55
56         for line in self.g.cat('/etc/master.passwd').splitlines():
57
58             # Check for empty or comment lines
59             if len(line.split('#')[0]) == 0:
60                 master_passwd.append(line)
61                 continue
62
63             fields = line.split(':')
64             if fields[1] not in ('*', '!'):
65                 fields[1] = '!'
66
67             master_passwd.append(":".join(fields))
68
69         self.g.write('/etc/master.passwd', "\n".join(master_passwd) + '\n')
70
71         # Make sure no one can login on the system
72         self.g.rm_rf('/etc/spwd.db')
73
74     def _do_collect_metadata(self):
75         """Collect metadata about the OS"""
76         super(Freebsd, self)._do_collect_metadata()
77         self.meta["USERS"] = " ".join(self._get_passworded_users())
78
79         #The original product name key is long and ugly
80         self.meta['DESCRIPTION'] = \
81             self.meta['DESCRIPTION'].split('#')[0].strip()
82
83         # Delete the USERS metadata if empty
84         if not len(self.meta['USERS']):
85             self.out.warn("No passworded users found!")
86             del self.meta['USERS']
87
88     def _get_passworded_users(self):
89         """Returns a list of non-locked user accounts"""
90         users = []
91         regexp = re.compile(
92             '^([^:]+):((?:![^:]+)|(?:[^!*][^:]+)|):(?:[^:]*:){7}(?:[^:]*)'
93         )
94
95         for line in self.g.cat('/etc/master.passwd').splitlines():
96             line = line.split('#')[0]
97             match = regexp.match(line)
98             if not match:
99                 continue
100
101             user, passwd = match.groups()
102             if len(passwd) > 0 and passwd[0] == '!':
103                 self.out.warn("Ignoring locked %s account." % user)
104             else:
105                 users.append(user)
106
107         return users
108
109     def _do_mount(self, readonly):
110         """Mount partitions in the correct order"""
111
112         critical_mpoints = ('/', '/etc', '/root', '/home', '/var')
113
114         # libguestfs can't handle correct freebsd partitions on a GUID
115         # Partition Table. We have to do the translation to linux device names
116         # ourselves
117         guid_device = re.compile('^/dev/((?:ada)|(?:vtbd))(\d+)p(\d+)$')
118
119         mopts = "ufstype=ufs2,%s" % ('ro' if readonly else 'rw')
120         for mp, dev in self._mountpoints():
121             match = guid_device.match(dev)
122             if match:
123                 group2 = int(match.group(2))
124                 group3 = int(match.group(3))
125                 dev = '/dev/sd%c%d' % (chr(ord('a') + group2), group3)
126             try:
127                 self.g.mount_vfs(mopts, 'ufs', dev, mp)
128             except RuntimeError as msg:
129                 if mp in critical_mpoints:
130                     self.out.warn('unable to mount %s. Reason: %s' % (mp, msg))
131                     return False
132                 else:
133                     self.out.warn('%s (ignored)' % msg)
134
135         return True
136
137 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :