summaryrefslogtreecommitdiffstats
path: root/cobbler/action_buildiso.py
blob: 20364dfd0c017dc1fc6d372fb560fa8a8ee20ba2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
"""
Builds non-live bootable CD's that have PXE-equivalent behavior
for all cobbler profiles currently in memory.

Copyright 2006-2008, Red Hat, Inc
Michael DeHaan <mdehaan@redhat.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301  USA
"""

import os
import os.path
import shutil
import sub_process
import sys
import traceback
import shutil
import sub_process

import utils
from cexceptions import *
from utils import _

# FIXME: lots of overlap with pxegen.py, should consolidate
# FIXME: disable timeouts and remove local boot for this?
HEADER = """

DEFAULT menu
PROMPT 0
MENU TITLE Cobbler | http://cobbler.et.redhat.com
TIMEOUT 200
TOTALTIMEOUT 6000
ONTIMEOUT local

LABEL local
        MENU LABEL (local)
        MENU DEFAULT
        KERNEL chain.c32
        APPEND hd0 0

"""

class BuildIso:
    """
    Handles conversion of internal state to the tftpboot tree layout
    """

    def __init__(self,config,verbose=False):
        """
        Constructor
        """
        self.verbose     = verbose
        self.config      = config
        self.api         = config.api
        self.distros     = config.distros()
        self.profiles    = config.profiles()
        self.systems     = config.systems()
        self.distmap     = {}
        self.distctr     = 0

    def make_shorter(self,distname):
        if self.distmap.has_key(distname):
            return self.distmap[distname]
        else:
            self.distctr = self.distctr + 1
            self.distmap[distname] = str(self.distctr)
            return str(self.distctr)

    def run(self,iso=None,tempdir=None,profiles=None,systems=None):

        # if iso is none, create it in . as "kickstart.iso"
        if iso is None:
            iso = "kickstart.iso"

        if tempdir is None:
            tempdir = os.path.join(os.getcwd(), "buildiso")
        print _("- using/creating tempdir: %s") % tempdir 
        if not os.path.exists(tempdir):
            os.makedirs(tempdir)
        else:
            shutil.rmtree(tempdir)
            os.makedirs(tempdir)

        # if base of tempdir does not exist, fail
        # create all profiles unless filtered by "profiles"

        imagesdir = os.path.join(tempdir, "images")
        isolinuxdir = os.path.join(tempdir, "isolinux")       

        print _("- building tree for isolinux")
        if not os.path.exists(imagesdir):
            os.makedirs(imagesdir)
        if not os.path.exists(isolinuxdir):
            os.makedirs(isolinuxdir)

        print _("- copying miscellaneous files")
        isolinuxbin = "/usr/lib/syslinux/isolinux.bin"
        menu = "/var/lib/cobbler/menu.c32"
        chain = "/usr/lib/syslinux/chain.c32"
        files = [ isolinuxbin, menu, chain ]
        for f in files:
            if not os.path.exists(f):
               raise CX(_("Required file not found: %s") % f)
            else:
               utils.copyfile(f, os.path.join(isolinuxdir, os.path.basename(f)), self.api)
 
        print _("- copying kernels and initrds - for profiles")
        # copy all images in included profiles to images dir
        for profile in self.api.profiles():
           use_this = True
           if profiles is not None:
              which_profiles = profiles.split(",")
              if not profile.name in which_profiles:
                 use_this = False

           if use_this:
              dist = profile.get_conceptual_parent()
              if dist.name.lower().find("-xen") != -1:
                  print "skipping Xen distro: %s" % dist.name
                  continue
              distname = self.make_shorter(dist.name)
              # tempdir/isolinux/$distro/vmlinuz, initrd.img
              # FIXME: this will likely crash on non-Linux breeds
              f1 = os.path.join(isolinuxdir, "%s.krn" % distname)
              f2 = os.path.join(isolinuxdir, "%s.img" % distname)
              if not os.path.exists(dist.kernel):
                 raise CX("path does not exist: %s" % dist.kernel)
              if not os.path.exists(dist.initrd):
                 raise CX("path does not exist: %s" % dist.initrd)
              shutil.copyfile(dist.kernel, f1)
              shutil.copyfile(dist.initrd, f2)

        if systems is not None:
           print _("- copying kernels and initrds - for systems")
           # copy all images in included profiles to images dir
           for system in self.api.systems():
              if system.name in systems:
                 profile = system.get_conceptual_parent()
                 dist = profile.get_conceptual_parent()
                 if dist.name.find("-xen") != -1:
                    continue
                 distname = self.make_shorter(dist.name)
                 # tempdir/isolinux/$distro/vmlinuz, initrd.img
                 # FIXME: this will likely crash on non-Linux breeds
                 shutil.copyfile(dist.kernel, os.path.join(isolinuxdir, "%s.krn" % distname))
                 shutil.copyfile(dist.initrd, os.path.join(isolinuxdir, "%s.img" % distname))

        print _("- generating a isolinux.cfg")
        isolinuxcfg = os.path.join(isolinuxdir, "isolinux.cfg")
        cfg = open(isolinuxcfg, "w+")
        cfg.write(HEADER) # fixme, use template
        
        print _("- generating profile list...")
       #sort the profiles
        profile_list = [profile for profile in self.profiles]
        def sort_name(a,b):
            return cmp(a.name,b.name)
        profile_list.sort(sort_name)

        for profile in profile_list:
            use_this = True
            if profiles is not None:
                which_profiles = profiles.split(",")
                if not profile.name in which_profiles:
                    use_this = False

            if use_this:
                dist = profile.get_conceptual_parent()
                if dist.name.find("-xen") != -1:
                    continue
                data = utils.blender(self.api, True, profile)
                distname = self.make_shorter(dist.name)

                cfg.write("\n")
                cfg.write("LABEL %s\n" % profile.name)
                cfg.write("  MENU LABEL %s\n" % profile.name)
                cfg.write("  kernel %s.krn\n" % distname)

                if data["kickstart"].startswith("/"):
                    data["kickstart"] = "http://%s/cblr/svc/op/ks/profile/%s" % (
                        data["server"],
                        profile.name
                    )

                append_line = "  append initrd=%s.img" % distname
                append_line = append_line + " ks=%s " % data["kickstart"]
                append_line = append_line + " %s\n" % data["kernel_options"]

                length=len(append_line)
                if length>254:
                   print _("WARNING - append line length is greater than 254 chars: (%s chars)") % length 
                
                cfg.write(append_line)
 
        if systems is not None:
           print _("- generating system list...")

           cfg.write("\nMENU SEPARATOR\n")

          #sort the systems
           system_list = [system for system in self.systems]
           def sort_name(a,b):
               return cmp(a.name,b.name)
           system_list.sort(sort_name)

           for system in system_list:
               use_this = False
               if systems is not None:
                   which_systems = systems.split(",")
                   if system.name in which_systems:
                       use_this = True

               if use_this:
                   profile = system.get_conceptual_parent()
                   dist = profile.get_conceptual_parent()
                   if dist.name.find("-xen") != -1:
                       continue
                   data = utils.blender(self.api, True, system)
                   distname = self.make_shorter(dist.name)

                   cfg.write("\n")
                   cfg.write("LABEL %s\n" % system.name)
                   cfg.write("  MENU LABEL %s\n" % system.name)
                   cfg.write("  kernel %s.krn\n" % distname)

                   if data["kickstart"].startswith("/"):
                       data["kickstart"] = "http://%s/cblr/svc/op/ks/system/%s" % (
                           data["server"],
                           system.name
                       )

                   append_line = "  append initrd=%s.img" % distname
                   append_line = append_line + " ks=%s" % data["kickstart"]
                   append_line = append_line + " %s" % data["kernel_options"]

                   # add network info to avoid DHCP only if it is available

                   if data.has_key("bonding_master_eth0") and data["bonding_master_eth0"] != "":
                      primary_interface = data["bonding_master_eth0"]
                   else:
                      primary_interface = "eth0"

                   if data.has_key("ip_address_" + primary_interface) and data["ip_address_" + primary_interface] != "":
                       append_line = append_line + " ip=%s" % data["ip_address_" + primary_interface]

                   if data.has_key("subnet_" + primary_interface) and data["subnet_" + primary_interface] != "":
                       append_line = append_line + " netmask=%s" % data["subnet_" + primary_interface]

                   if data.has_key("gateway") and data["gateway"] != "":
                       append_line = append_line + " gateway=%s" % data["gateway"]

                   if data.has_key("name_servers") and data["name_servers"]:
                       append_line = append_line + " dns=%s\n" % ",".join(data["name_servers"])

                   length=len(append_line)
                   if length > 254:
                      print _("WARNING - append line length is greater than 254 chars: (%s chars)") % length 
                
                   cfg.write(append_line)

        print _("- done writing config")        
        cfg.write("\n")
        cfg.write("MENU END\n")
        cfg.close()
 
        cmd = "mkisofs -o %s -r -b isolinux/isolinux.bin -c isolinux/boot.cat" % iso
        cmd = cmd + "  -no-emul-boot -boot-load-size 4 "
        cmd = cmd + "  -boot-info-table -V Cobbler\ Install -R -J -T %s" % tempdir

        print _("- running: %s") % cmd
        rc = sub_process.call(cmd, shell=True, close_fds=True)
        if rc:
            raise CX(_("mkisofs failed"))
        
        print _("ISO build complete")
        print _("You may wish to delete: %s") % tempdir
        print _("The output file is: %s") % iso