summaryrefslogtreecommitdiff
path: root/kswriter/KSWriter.py
blob: 12ba8998f775f1ac7d7a59d2423b6f2bd828207f (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
#!/usr/bin/python
import copy
import time
import yaml
import os, re
import sys
import errno
from urlparse import urlparse

from kickstart import kickstart

class KSMetaError(Exception):
    """Exception to catch malformated meta YAML files """
    def __init__(self, msg):
        Exception.__init__(self)
        self.msg = msg

    def __str__(self):
        return self.msg

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST:
            pass
        else: raise

def yamlload_safe(fname):
    """ Safer wrapper for yaml.load() """
    try:
        with file(fname) as f:
            return yaml.load(f)

    except IOError:
        raise KSMetaError('cannot read meta file: %s' % fname)

    except:
        # should be YAML format issue
        raise KSMetaError('format error of meta file: %s' % fname)

class KSWriter():
    def __init__(self, configs=None, repos=None, outdir=".", config=None, packages=False, external=None, targetdefs=None, target=None):
        self.dist = None
        self.arch = None
        self.image_filename = os.path.abspath(os.path.expanduser(configs))
        self.outdir = outdir
        self.external = external
        self.packages = packages
        self.config = config
        self.image_meta = yamlload_safe(self.image_filename)
        self.extra = {}

        self.repos = self.parse_repos(repos)

        # parse and record target definitions
        self.target = target
        self.targetdefs = self.parse_targetdef(targetdefs)

    def parse_repos(self, repos):
        prepos = []
        for repo in repos:
            repo_meta = yamlload_safe(repo)
            prepos = prepos + repo_meta['Repositories']

        return prepos

    def parse_targetdef(self, targetdefs):
        """ Parse the targets defs in YAML to list of dict.
            Will join them if multiple files provided.
            Once one wrong file found, raise exception to abort
        """
        if not targetdefs:
            return []

        all_defs = []
        for tdef in targetdefs:
            tmeta = yamlload_safe(tdef)

            all_defs.extend(tmeta['Targets'])

        return all_defs

    def merge(*input):
        return list(reduce(set.union, input, set()))

    def dump(self):
        print yaml.dump(yamlload_safe(self.stream))

    def parse(self, img):
        conf = copy.copy(self.image_meta['Default'])
        plat = copy.copy(self.image_meta[img['Platform']])
        conf.update(plat)
        conf.update(img)
        lval = ['Repos', 'Groups', 'PostScripts', 'NoChrootScripts', 'RemovePackages', 'ExtraPackages']
        lvald = {}
        for l in lval:
            full = []
            if self.image_meta['Default'].has_key(l) and self.image_meta['Default'][l]:
                full = full + self.image_meta['Default'][l]
            if plat.has_key(l) and plat[l]:
                full = full + plat[l]
            if img.has_key(l) and img[l]:
                full = full + img[l]
            lvald[l] = sorted(set(full), key=full.index)
        conf.update(lvald)
        postscript = ""
        meta_root = os.path.dirname(self.image_filename)
        for scr in conf['PostScripts']:
            if os.path.exists('%s/scripts/%s.post' %(meta_root, scr)):
                f = open('%s/scripts/%s.post' %(meta_root, scr), 'r')
                postscript += f.read()
                postscript += "\n"
                f.close()
            else:
                print '%s/scripts/%s.post not found, skipping.' %(meta_root,scr )

        nochrootscript = ""
        for scr in conf['NoChrootScripts']:
            if os.path.exists('%s/scripts/%s.nochroot' %(meta_root,scr)):
                f = open('%s/scripts/%s.nochroot' %(meta_root, scr ), 'r')
                nochrootscript += f.read()
                nochrootscript += "\n"
                f.close()
            else:
                print '%s/scripts/%s.nochroot not found, skipping.' %(meta_root, scr )

        ptab = ""
        for g in [ plat, img ]:
            if g.has_key("Part"):
                f = open("%s/partitions/%s" %(meta_root, g['Part']) )
                ptab = f.read()
                f.close()

        conf['Part'] = ptab
        conf['Post'] = postscript
        conf['NoChroot'] = nochrootscript
        return conf

    def process_files(self,  meta,  repos):
        new_repos = []
        if ( meta.has_key("Architecture") and  meta['Architecture'] )  or ( meta.has_key("Distribution") and  meta['Distribution']):
            for repo in repos:
                r = {}
                r['Name'] = repo['Name']
                repourl = repo['Url']
                if repo.has_key('Options'):
                    r['Options'] = repo['Options']
                if meta.has_key("Architecture") or self.arch:
                    repourl = repourl.replace("@ARCH@", self.arch or meta['Architecture'])
                if meta.has_key("Distribution") or self.dist:
                    repourl = repourl.replace("@DIST@", self.dist or meta['Distribution'])

                url = repourl.replace("@RELEASE@", meta['Baseline'])
                o = urlparse(url)
                new_url = "%s://" % o[0]
                if repo.has_key('Username') and repo['Username']:
                    new_url = "%s%s" % (new_url, repo['Username'] )
                if repo.has_key('Password') and repo['Password']:
                    new_url = "%s:%s@" % (new_url, repo['Password'] )
                r['Url'] = "%s%s%s" % (new_url, o[1], o[2] )
                new_repos.append(r)
        else:
            new_repos = repos

        nameSpace = {'metadata': meta,  'repos': new_repos}
        t = kickstart(searchList=[nameSpace])
        a = str(t)
        if meta.has_key('FileName') and meta['FileName']:
            f = None
            if meta.has_key("Baseline"):
                mkdir_p("%s/%s" %(self.outdir, meta['Baseline']))
                f = open("%s/%s/%s.ks" %( self.outdir, meta['Baseline'],  meta['FileName'] ), 'w')
            else:
                f = open("%s/%s.ks" %( self.outdir, meta['FileName'] ), 'w')
            f.write(a)
            f.close()

    def _image_for_current_target(self, fname):
        """ To check whether this image is belong to current
            target, which is specifed by user
        """

        if not self.target or not self.targetdefs:
            # if user doesn't specify them, skip the checking
            return True

        for tdef in self.targetdefs:
            if self.target == tdef['Name'] and fname in tdef['Images']:
                # found
                return True

        return False

    def generate(self):
        out = {}
        if self.image_meta.has_key('Configurations'):
            for img in self.image_meta['Configurations']:
                conf = self.parse(img)
                if self.config:
                    if img.has_key('FileName') and self.config == img['FileName']:
                        print "Creating %s (%s.ks)" %(img['Name'], img['FileName'] )
                        self.process_files(conf, self.repos)
                        break
                else:
                    if conf.has_key('Active') and conf['Active'] :
                        print "Creating %s (%s.ks)" %(img['Name'], img['FileName'] )
                        self.process_files(conf, self.repos)
                    else:
                        print "%s is inactive, not generating %s at this time" %(img['Name'], img['FileName'] )

        external = []
        if self.external:
            external = external + self.external
        if self.image_meta.has_key('ExternalConfigs') and self.image_meta['ExternalConfigs']:
            external = external + self.image_meta['ExternalConfigs']

        for path in external:
            external_config_dir = os.path.join(os.path.dirname(self.image_filename), path)
            if not os.path.exists(external_config_dir):
                external_config_dir = os.path.abspath(os.path.expanduser(path))

            for f in os.listdir(external_config_dir):
                if f.endswith('.yaml'):

                    if not self._image_for_current_target(f):
                        # skip
                        continue

                    local = yamlload_safe('%s/%s' %(external_config_dir, f))
                    conf = self.parse(local)
                    if self.config:
                        if self.config == conf['FileName']:
                            if self.packages:
                                out['baseline'] = conf['Baseline']
                                out['groups'] = conf['Groups']
                                out['packages'] = conf['ExtraPackages']
                            else:
                                print "Creating %s (%s.ks)" %(conf['Name'], conf['FileName'] )
                                self.process_files(conf, self.repos)
                                break
                    else:
                        if conf.has_key('Active') and conf['Active']:
                            print "Creating %s (%s.ks)" %(conf['Name'], conf['FileName'] )
                            self.process_files(conf, self.repos)
                        else:
                            print "%s is inactive, not generate %s this time" %(conf['Name'], conf['FileName'] )
                else:
                    print "WARNING: File '%s' ignored." % (f)
        return out