summaryrefslogtreecommitdiffstats
path: root/rteval/modules/loads/kcompile.py
blob: 34a61cd96a1110032021abd975fc31ddfcb22b79 (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
#
#   Copyright 2009 - 2013   Clark Williams <williams@redhat.com>
#   Copyright 2012 - 2013   David Sommerseth <davids@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.
#
#   For the avoidance of doubt the "preferred form" of this code is one which
#   is in an open unpatent encumbered format. Where cryptographic key signing
#   forms part of the process of creating an executable the information
#   including keys needed to generate an equivalently functional executable
#   are deemed to be part of the source code.
#

import sys, os, glob, subprocess
from signal import SIGTERM
from rteval.modules import rtevalRuntimeError
from rteval.modules.loads import CommandLineLoad
from rteval.Log import Log

kernel_prefix="linux-2.6"

class Kcompile(CommandLineLoad):
    def __init__(self, config, logger):
        CommandLineLoad.__init__(self, "kcompile", config, logger)


    def _WorkloadSetup(self):
        # find our source tarball
        if self._cfg.has_key('tarball'):
            tarfile = os.path.join(self.srcdir, self._cfg.tarfile)
            if not os.path.exists(tarfile):
                raise rtevalRuntimeError(self, " tarfile %s does not exist!" % tarfile)
            self.source = tarfile
        else:
            tarfiles = glob.glob(os.path.join(self.srcdir, "%s*" % kernel_prefix))
            if len(tarfiles):
                self.source = tarfiles[0]
            else:
                raise rtevalRuntimeError(self, " no kernel tarballs found in %s" % self.srcdir)

        # check for existing directory
        kdir=None
        names=os.listdir(self.builddir)
        for d in names:
            if d.startswith(kernel_prefix):
                kdir=d
                break
        if kdir == None:
            self._log(Log.DEBUG, "unpacking kernel tarball")
            tarargs = ['tar', '-C', self.builddir, '-x']
            if self.source.endswith(".bz2"):
                tarargs.append("-j")
            elif self.source.endswith(".gz"):
                tarargs.append("-z")
            tarargs.append("-f")
            tarargs.append(self.source)
            try:
                subprocess.call(tarargs)
            except:
                self._log(Log.DEBUG, "untar'ing kernel self.source failed!")
                sys.exit(-1)
            names = os.listdir(self.builddir)
            for d in names:
                self._log(Log.DEBUG, "checking %s" % d)
                if d.startswith(kernel_prefix):
                    kdir=d
                    break
        if kdir == None:
            raise rtevalRuntimeError(self, "Can't find kernel directory!")
        self.jobs = 1 # We only run one instance of the kcompile job
        self.mydir = os.path.join(self.builddir, kdir)
        self._log(Log.DEBUG, "mydir = %s" % self.mydir)


    def _WorkloadBuild(self):
        self._log(Log.DEBUG, "setting up all module config file in %s" % self.mydir)
        null = os.open("/dev/null", os.O_RDWR)
        if self._logging:
            out = self.open_logfile("kcompile-build.stdout")
            err = self.open_logfile("kcompile-build.stderr")
        else:
            out = err = null

        # clean up from potential previous run
        try:
            ret = subprocess.call(["make", "-C", self.mydir, "mrproper", "allmodconfig"], 
                                  stdin=null, stdout=out, stderr=err)
            if ret:
                raise rtevalRuntimeError(self, "kcompile setup failed: %d" % ret)
        except KeyboardInterrupt, m:
            self._log(Log.DEBUG, "keyboard interrupt, aborting")
            return
        self._log(Log.DEBUG, "ready to run")
        os.close(null)
        if self._logging:
            os.close(out)
            os.close(err)
        self._setReady()


    def __calc_numjobs(self):
        mult = int(self._cfg.setdefault('jobspercore', 1))
        mem = self.memsize[0]
        if self.memsize[1] == 'KB':
            mem = mem / (1024.0 * 1024.0)
        elif self.memsize[1] == 'MB':
            mem = mem / 1024.0
        elif self.memsize[1] == 'TB':
            mem = mem * 1024
        ratio = float(mem) / float(self.num_cpus)
        if ratio > 1.0:
            njobs = self.num_cpus * mult
        else:
            self._log(Log.DEBUG, "Low memory system (%f GB/core)! Dropping jobs to one per core" % ratio)
            njobs = self.num_cpus
        return njobs


    def _WorkloadPrepare(self):
        self.__nullfd = os.open("/dev/null", os.O_RDWR)
        if self._logging:
            self.__outfd = self.open_logfile("kcompile.stdout")
            self.__errfd = self.open_logfile("kcompile.stderr")
        else:
            self.__outfd = self.__errfd = self.__nullfd

        self.jobs = self.__calc_numjobs()
        self._log(Log.DEBUG, "starting loop (jobs: %d)" % self.jobs)
        self.args = ["make", "-C", self.mydir,
                     "-j%d" % self.jobs ]
        self.__kcompileproc = None


    def _WorkloadTask(self):
        if not self.__kcompileproc or self.__kcompileproc.poll() is not None:
            # If kcompile has not been kicked off yet, or have completed,
            # restart it
            self._log(Log.DEBUG, "Kicking off kcompile: %s" % " ".join(self.args))
            self.__kcompileproc = subprocess.Popen(self.args,
                                                   stdin=self.__nullfd,
                                                   stdout=self.__outfd,
                                                   stderr=self.__errfd)


    def WorkloadAlive(self):
        # Let _WorkloadTask() kick off new runs, if it stops - thus
        # kcompile will always be alive
        return True


    def _WorkloadCleanup(self):
        self._log(Log.DEBUG, "out of stopevent loop")
        if self.__kcompileproc.poll() == None:
            self._log(Log.DEBUG, "killing compile job with SIGTERM")
            os.kill(self.__kcompileproc.pid, SIGTERM)
        self.__kcompileproc.wait()
        os.close(self.__nullfd)
        del self.__nullfd
        if self._logging:
            os.close(self.__outfd)
            del self.__outfd
            os.close(self.__errfd)
            del self.__errfd
        del self.__kcompileproc
        self._setFinished()



def ModuleParameters():
    return {"source":   {"descr": "Source tar ball",
                         "default": "linux-2.6.21.tar.bz2",
                         "metavar": "TARBALL"},
            "jobspercore": {"descr": "Number of working threads per core",
                            "default": 2,
                            "metavar": "NUM"}
            }



def create(config, logger):
    return Kcompile(config, logger)