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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
|
import sys
import protocol
import socket
import pickle
from time import sleep
import os
import subprocess
from subprocess import CalledProcessError
import re
import string
from string import atoi
import portage
from traceback import print_exc, format_exc
from util import WritableObject, flatten_deps
from common.exceptions import ChrootPreparationException
import config
from logger import log, init_logging
class Tinderbox(object):
def __init__(self, hostname, port):
self.hostname = hostname
self.port = port
self.sock = None
self.settings = portage.config(clone=portage.settings)
self.trees = portage.create_trees()
self.settings["PORTAGE_VERBOSE"]="1"
self.settings.backup_changes("PORTAGE_VERBOSE")
def start_tinderbox(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# TODO load settings for contacting matchbox
self.sock.connect((self.hostname,self.port))
while 1:
# TODO error/exception checking
msg = protocol.GetNextPackage()
msg_pickled = pickle.dumps(msg)
self.sock.sendall(msg_pickled)
reply = self.sock.recv(1024)
reply_unpickled = pickle.loads(reply)
if type(reply_unpickled) is protocol.GetNextPackageReply:
gnp = reply_unpickled
print "going to compile: %s\nuse flags: %s" %\
(gnp.package_name,gnp.use_flags)
package = Package(gnp.package_name, gnp.version, gnp.use_flags)
sleep(5)
self.emerge_package(package)
pi = package.get_info()
pi.emerge_info = self.get_emerge_info()
msg = protocol.AddPackageInfo(pi)
self.sock.sendall(pickle.dumps(msg))
else:
print "Unknown reply: %s" % reply_unpickled
def emerge_package(self, package):
settings = self.settings
porttree = self.trees[portage.root]['porttree']
portdb = porttree.dbapi
if not package.version:
# we are compiling ALL versions of package
allversions = portdb.xmatch('match-all', package.name)
else:
# we were told exact version to compile
allversions = ["%s-%s" % (package.name, package.version)]
for pkg in allversions:
ebuild = portdb.findname(pkg)
deps = portdb.aux_get(pkg,["DEPEND"])
deps = portage.dep.paren_reduce(deps[0])
settings.setcpv(pkg, mydb=portdb)
use_enabled = set(settings["PORTAGE_USE"].split())
iuse = set(settings["IUSE"].split())
# only count deps enabled by USE flags
use_deps = portage.dep.use_reduce(deps, list(use_enabled & iuse))
use_deps = flatten_deps(use_deps)
dep_groups = self.create_dep_groups(use_deps)
# prepare chroot & fork & do work
try:
subprocess.check_call([config.MK_CHROOT_SCRIPT,"-s",config.STAGE_TARBALL,
config.BASE_CHROOT, config.WORK_CHROOT])
except CalledProcessError, cpe:
raise ChrootPreparationException("Chroot preparation for %s failed with error code: %d"
% (pkg, cpe.returncode))
except OSError, ose:
raise ChrootPreparationException("Chroot preparation for %s failed with error(%d): %s\n\
Check your settings"
% (pkg, ose.errno, ose.strerror))
self.child_pid = os.fork()
childpid = self.child_pid
if childpid == 0:
# we are the child!
try:
# setup logging!
os.chroot(config.WORK_CHROOT)
init_logging()
self._emerge_package_subprocess(pkg, ebuild, dep_groups, package)
sys.exit(0)
except Exception, e:
print_exc()
print "Something went really bad and we need logging, stat!"
log.error("Unrecoverable error in tinderbox slave, see backtrace for possible solutions:")
log.error(format_exc())
sys.exit(1)
(retpid, status) = os.waitpid(childpid, 0)
if status != 0:
# something went really wrong, grab all the info we can
print "Something went really bad and we need logging, stat!"
log.error("Emerge of package %s failed with error code: %d" % (pkg, status))
#TODO get contents && make binpkg && report back to matchbox && uninstall deps && uninstall pkg
def _emerge_package_subprocess(self, pkg, ebuild, dep_groups, package):
# We are chrooted inside WORK_CHROOT remember!
porttree = self.trees[portage.root]['porttree']
portdb = porttree.dbapi
vartree = self.trees[portage.root]["vartree"]
package_infos = []
settings = self.settings
for group in dep_groups:
dep_failed = False
deps_processed = []
for dep in group:
orig_args = sys.argv
try:
# this will need to change since it's only a quick hack so that
# we don't have to do dep resolution ourselves
import _emerge as emerge
dep_emergepid = os.fork()
# we need to run emerge_main() in child process since a lot of stuff in there
# likes to call sys.exit() and we don't want that do we?
if dep_emergepid == 0:
extra_use = dep[0]
os.environ["USE"]=" ".join(extra_use)
sys.argv = ["emerge","--verbose","=%s" % dep[1]]
sys.exit(emerge.emerge_main())
ret = os.waitpid(dep_emergepid, 0)
if ret[1] != 0:
raise Exception("emerge_main() failed with error code %d" % ret)
except Exception, e:
log.error(format_exc())
log.error("Unable to merge dependency %s for package %s" % (dep, pkg))
dep_failed = True
break
deps_processed.append(dep)
settings.setcpv(dep, mydb=portdb)
dep_use_enabled = set(settings["PORTAGE_USE"].split())
dep_iuse = set(settings["IUSE"].split())
dep_name, dep_ver, dep_rev = portage.pkgsplit(dep)
dep_pkg = Package(dep_name,"%s-%s" % (dep_ver, dep_rev), list(dep_use_enabled & dep_iuse))
package_infos.append(dep_pkg.get_info())
if dep_failed:
log.error("Unable to emerge package %s with deps %s" % (pkg, group))
# TODO unmerge succeeded deps
continue
ret = portage.doebuild(ebuild, "merge", portage.root, settings, debug = False, tree="porttree")
if ret != 0:
# error installing, grab logs
try:
logfile = open("%s/build.log" % settings["T"], "r")
except IOError, (errno, strerror):
print "Unable to read build logs: %d: %s" % (errno, strerror)
log.warning("Unable to read build logs %d: %s" % (errno, strerror))
else:
package.build_log = logfile.read()
logfile.close()
del logfile
try:
envfile = open("%s/environment" % settings["T"],"r")
except IOError, (errno, strerror):
print "Unable to read build environment: %d: %s" % (errno, strerror)
log.warning("Unable to read build environment %d: %s" % (errno, strerror))
else:
package.build_env = envfile.read()
envfile.close()
del envfile
package_infos.append(package.get_info())
for dep in group:
dep_cat, dep_pv = portage.catsplit(dep)
ret = portage.unmerge(dep_cat, dep_pv, portage.root, settings, True, vartree=vartree)
if ret != 0:
log.error("Unable to unmerge dep %s" % dep)
pkg_cat, pkg_pv = portage.catsplit(pkg)
ret = portage.unmerge(pkg_cat, pkg_pv, portage.root, settings, True, vartree=vartree)
if ret != 0:
log.error("Unable to unmerge dep %s" % dep)
def get_emerge_info(self):
"""
@rtype: string
@returns: emerge --info output
"""
infoout = WritableObject()
sys.stdout = infoout
# emerge.action_info(self.settings, self.trees, [], [])
# REDO withouth emerge.action_info
ret = sys.stdout.content
sys.stdout = sys.__stdout__
return string.join(infoout.content,sep='')
def create_dep_groups(self, deps):
"""
Create dependency groups from package dependencies
Every valid version of dep (according to input spec) has to be at least in
one output dependency group
@param deps: dependencies of package (atoms)
@type deps: List
@rtype: List of Lists
@returns: List of dependency groups (list of dependency versions) together with special use flags needed
Example:
Input: ['=dev-libs/glib-2*', '>=net-fs/samba-3.0.0', 'x11-libs/libX11','dev-util/subversion[-dso]']
Output:
[[(None,'net-fs/samba-3.2.11'),(None, 'dev-libs/glib-2.18.4-r1'),(None, 'x11-libs/libX11-1.1.2-r1'), (['-dso'],'dev-util/subversion-1.5.5'],
[(None,'net-fs/samba-3.0.32'),(None, 'dev-libs/glib-2.18.4-r1'),(None, 'x11-libs/libX11-1.1.3-r1'), (['-dso'],'dev-util/subversion-1.5.5'],
[(None,'net-fs/samba-3.0.32'),(None, 'dev-libs/glib-2.20.3'),(None, 'x11-libs/libX11-1.1.3'), (['-dso'],'dev-util/subversion-1.5.5'],
"""
result = None
porttree = self.trees[portage.root]['porttree']
portdb = porttree.dbapi
deps_expanded = []
max_dep_versions = 0
for dep in deps:
if dep[0].startswith('!'):
continue
dep_useflag = list(portage.dep.dep_getusedeps(dep))
if len(dep_useflag) == 0:
dep_useflag = None
depversions = portdb.xmatch('match-all',dep)
depversions = [(dep_useflag,x) for x in depversions]
deps_expanded.append(depversions)
if len(depversions) > max_dep_versions:
max_dep_versions = len(depversions)
for dep in deps_expanded:
while len(dep) < max_dep_versions:
print dep
dep.append(dep[0])
result = []
for i in range(max_dep_versions):
group = []
for dep in deps_expanded:
group.append(dep.pop())
result.append(group)
return result
class Package(object):
def __init__(self, name, version, use_flags):
"""
@param name: category/name of given package (excluding version/release)
@type name: string
@param version: version part of CPV e.g. 1.2.0-r4
@type version: string
@param use_flags: list of enabled use flags for given package
@type use_flags: list
"""
self.name = name
self.version = version
self.use_flags = use_flags
self.content = None
self.build_log = None
self.build_env = None
def get_info(self):
"""Returns protocol.PackageInfo with information about this package
@returns: PackageInfo for sending across network
@rtype: protocol.PackageInfo
"""
pi = protocol.PackageInfo()
pi.name = self.name
pi.version = self.version
pi.use_flags = self.use_flags
if self.content is None:
self.content = self.get_package_contents()
pi.content = self.content
pi.build_log = self.build_log
pi.build_env = self.build_env
return pi
def get_package_contents(self):
"""Returns package contents as dict with paths as keys
data values are tuples of information (such as hash and size)
@returns: package contents (or {} if it's not installed)
@rtype: dict
"""
vartree = portage.db[portage.root]["vartree"]
cpv = "%s-%s" % (self.name, self.version)
if not vartree.dbapi.cpv_exists(cpv):
# maybe raise exception? instead
return {}
cat, pkg = portage.catsplit(cpv)
dblink = portage.dblink(cat, pkg, portage.root, vartree.settings,
treetype="vartree", vartree=vartree)
return dblink.getcontents()
|