Fix license, copyright and pep8 infractions
[snf-image-creator] / image_creator / os_type / linux.py
1 # Copyright 2012 GRNET S.A. All rights reserved.
2 #
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
5 # conditions are met:
6 #
7 #   1. Redistributions of source code must retain the above
8 #      copyright notice, this list of conditions and the following
9 #      disclaimer.
10 #
11 #   2. Redistributions in binary form must reproduce the above
12 #      copyright notice, this list of conditions and the following
13 #      disclaimer in the documentation and/or other materials
14 #      provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 # POSSIBILITY OF SUCH DAMAGE.
28 #
29 # The views and conclusions contained in the software and
30 # documentation are those of the authors and should not be
31 # interpreted as representing official policies, either expressed
32 # or implied, of GRNET S.A.
33
34 from image_creator.os_type.unix import Unix
35 import re
36
37
38 class Linux(Unix):
39     def __init__(self, rootdev, ghandler):
40         super(Linux, self).__init__(rootdev, ghandler)
41         self._uuid = dict()
42         self._persistent = re.compile('/dev/[hsv]d[a-z][1-9]*')
43
44     def is_persistent(self, dev):
45         return not self._persistent.match(dev)
46
47     def get_uuid(self, dev):
48         if dev in self._uuid:
49             return self._uuid[dev]
50
51         for attr in self.g.blkid(dev):
52             if attr[0] == 'UUID':
53                 self._uuid[dev] = attr[1]
54                 return attr[1]
55
56     def sysprep(self):
57         """Prepere system for image creation."""
58         self.sysprep_acpid()
59         self.sysprep_persistent_net_rules()
60         self.sysprep_persistent_devs()
61
62     def sysprep_acpid(self):
63         """Replace acpid powerdown action scripts to automatically shutdown
64         the system without checking if a GUI is running.
65         """
66         action = '#!/bin/sh\n\nPATH=/sbin:/bin:/usr/bin\n shutdown -h now '
67         '\"Power button pressed\"'
68
69         if self.g.is_file('/etc/acpi/powerbtn.sh'):
70             self.g.write('/etc/acpi/powerbtn.sh', action)
71         elif self.g.is_file('/etc/acpi/actions/power.sh'):
72             self.g.write('/etc/acpi/actions/power.sh', action)
73         else:
74             print "Warning: No acpid action file found"
75
76     def sysprep_persistent_net_rules(self):
77         """Remove udev rules that will keep network interface names persistent
78         after hardware changes and reboots. Those rules will be created again
79         the next time the image runs.
80         """
81         rule_file = '/etc/udev/rules.d/70-persistent-net.rules'
82         if self.g.is_file(rule_file):
83             self.g.rm(rule_file)
84
85     def sysprep_persistent_devs(self):
86         """Scan fstab and grub configuration files and replace all
87         non-persistent device appearences with UUIDs.
88         """
89         # convert all devices in fstab to persistent
90         persistent_root = self._persistent_fstab()
91
92         # convert all devices in grub1 to persistent
93         self._persistent_grub1(persistent_root)
94
95     def _persistent_grub1(self, new_root):
96         if self.g.is_file('/boot/grub/menu.lst'):
97             grub1 = '/boot/grub/menu.lst'
98         elif self.g.is_file('/etc/grub.conf'):
99             grub1 = '/etc/grub.conf'
100         else:
101             return
102
103         self.g.aug_init('/', 0)
104         try:
105             roots = self.g.aug_match('/files%s/title[*]/kernel/root' % grub1)
106             for root in roots:
107                 dev = self.g.aug_get(root)
108                 if not self.is_persistent(dev):
109                     # This is not always correct. Grub may contain root entries
110                     # for other systems, but we only support 1 OS per hard
111                     # disk, so this shouldn't harm.
112                     self.g.aug_set(root, new_root)
113         finally:
114             self.g.aug_save()
115             self.g.aug_close()
116
117     def _persistent_fstab(self):
118         mpoints = self.g.mountpoints()
119         if len(mpoints) == 0:
120             pass  # TODO: error handling
121
122         device_dict = dict([[mpoint, dev] for dev, mpoint in mpoints])
123
124         root_dev = None
125         new_fstab = ""
126         fstab = self.g.cat('/etc/fstab')
127         for line in fstab.splitlines():
128
129             line, dev, mpoint = self._convert_fstab_line(line, device_dict)
130             new_fstab += "%s\n" % line
131
132             if mpoint == '/':
133                 root_dev = dev
134
135         self.g.write('/etc/fstab', new_fstab)
136         if root_dev is None:
137             pass  # TODO: error handling
138
139         return root_dev
140
141     def _convert_fstab_line(self, line, devices):
142         orig = line
143         line = line.split('#')[0].strip()
144         if len(line) == 0:
145             return orig, "", ""
146
147         entry = line.split()
148         if len(entry) != 6:
149             print "Warning: detected abnorman entry in fstab"
150             return orig, "", ""
151
152         dev = entry[0]
153         mpoint = entry[1]
154
155         if not self.is_persistent(dev):
156             if mpoint in devices:
157                 dev = "UUID=%s" % self.get_uuid(devices[mpoint])
158                 entry[0] = dev
159             else:
160                 # comment out the entry
161                 entry[0] = "#%s" % dev
162             return " ".join(entry), dev, mpoint
163
164         return orig, dev, mpoint
165
166 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :