blob: ae83a01cf237efbb2b4580a1929e0835f5591a24 [file] [log] [blame]
showard9d02fb52008-08-08 18:20:37 +00001#!/usr/bin/python
2
3"""
4This module defines the BasePackageManager Class which provides an
5implementation of the packaging system API providing methods to fetch,
6upload and remove packages. Site specific extensions to any of these methods
7should inherit this class.
8"""
9
10import re, os, sys, traceback, subprocess, shutil, time, traceback, urlparse
11import fcntl
12from autotest_lib.client.common_lib import error, utils
13
14
15class PackageUploadError(error.AutotestError):
16 'Raised when there is an error uploading the package'
17
18class PackageFetchError(error.AutotestError):
19 'Raised when there is an error fetching the package'
20
21class PackageRemoveError(error.AutotestError):
22 'Raised when there is an error removing the package'
23
24class PackageInstallError(error.AutotestError):
25 'Raised when there is an error installing the package'
26
27# the name of the checksum file that stores the packages' checksums
28CHECKSUM_FILE = "packages.checksum"
29
30class BasePackageManager(object):
31 _repo_exception = {}
32 REPO_OK = object()
33
mbligh76d19f72008-10-15 16:24:43 +000034 def __init__(self, pkgmgr_dir, hostname=None, repo_urls=None,
35 upload_paths=None, do_locking=True, run_function=utils.run,
36 run_function_args=[], run_function_dargs={}):
showard9d02fb52008-08-08 18:20:37 +000037 '''
38 repo_urls: The list of the repository urls which is consulted
39 whilst fetching the package
40 upload_paths: The list of the upload of repositories to which
41 the package is uploaded to
42 pkgmgr_dir : A directory that can be used by the package manager
43 to dump stuff (like checksum files of the repositories
44 etc.).
45 do_locking : Enable locking when the packages are installed.
46
47 run_function is used to execute the commands throughout this file.
48 It defaults to utils.run() but a custom method (if provided) should
49 be of the same schema as utils.run. It should return a CmdResult
50 object and throw a CmdError exception. The reason for using a separate
51 function to run the commands is that the same code can be run to fetch
52 a package on the local machine or on a remote machine (in which case
53 ssh_host's run function is passed in for run_function).
54 '''
55 # In memory dictionary that stores the checksum's of packages
56 self._checksum_dict = {}
57
58 self.pkgmgr_dir = pkgmgr_dir
59 self.do_locking = do_locking
mbligh76d19f72008-10-15 16:24:43 +000060 self.hostname = hostname
showard9d02fb52008-08-08 18:20:37 +000061
62 # Process the repository URLs and the upload paths if specified
63 if not repo_urls:
64 self.repo_urls = []
65 else:
mbligh76d19f72008-10-15 16:24:43 +000066 if hostname:
67 self.repo_urls = repo_urls
68 self.repo_urls = list(self.get_mirror_list())
69 else:
70 self.repo_urls = list(repo_urls)
showard9d02fb52008-08-08 18:20:37 +000071 if not upload_paths:
72 self.upload_paths = []
73 else:
74 self.upload_paths = list(upload_paths)
75
76 # Create an internal function that is a simple wrapper of
77 # run_function and takes in the args and dargs as arguments
78 def _run_command(command, _run_command_args=run_function_args,
79 _run_command_dargs={}):
80 '''
81 Special internal function that takes in a command as
82 argument and passes it on to run_function (if specified).
83 The _run_command_dargs are merged into run_function_dargs
84 with the former having more precedence than the latter.
85 '''
86 new_dargs = dict(run_function_dargs)
87 new_dargs.update(_run_command_dargs)
88
89 return run_function(command, *_run_command_args,
90 **new_dargs)
91
92 self._run_command = _run_command
93
94
95 def install_pkg(self, name, pkg_type, fetch_dir, install_dir,
96 preserve_install_dir=False, repo_url=None):
97 '''
98 Remove install_dir if it already exists and then recreate it unless
99 preserve_install_dir is specified as True.
100 Fetch the package into the pkg_dir. Untar the package into install_dir
101 The assumption is that packages are of the form :
102 <pkg_type>.<pkg_name>.tar.bz2
103 name : name of the package
104 type : type of the package
105 fetch_dir : The directory into which the package tarball will be
106 fetched to.
107 install_dir : the directory where the package files will be untarred to
108 repo_url : the url of the repository to fetch the package from.
109 '''
110
111 # do_locking flag is on by default unless you disable it (typically
112 # in the cases where packages are directly installed from the server
113 # onto the client in which case fcntl stuff wont work as the code
114 # will run on the server in that case..
115 if self.do_locking:
116 lockfile_name = '.%s-%s-lock' % (name, pkg_type)
117 lockfile = open(os.path.join(self.pkgmgr_dir, lockfile_name), 'w')
118
119 try:
120 if self.do_locking:
121 fcntl.flock(lockfile, fcntl.LOCK_EX)
122
123 self._run_command('mkdir -p %s' % fetch_dir)
124
125 pkg_name = self.get_tarball_name(name, pkg_type)
126 fetch_path = os.path.join(fetch_dir, pkg_name)
127 try:
128 # Fetch the package into fetch_dir
mbligh76d19f72008-10-15 16:24:43 +0000129 self.fetch_pkg(pkg_name, fetch_path, use_checksum=True)
showard9d02fb52008-08-08 18:20:37 +0000130
131 # check to see if the install_dir exists and if it does
132 # then check to see if the .checksum file is the latest
133 install_dir_exists = False
134 try:
135 self._run_command("ls %s" % install_dir)
136 install_dir_exists = True
137 except (error.CmdError, error.AutoservRunError):
138 pass
139
140 if (install_dir_exists and
141 not self.untar_required(fetch_path, install_dir)):
142 return
143
144 # untar the package into install_dir and
145 # update the checksum in that directory
146 if not preserve_install_dir:
147 # Make sure we clean up the install_dir
148 self._run_command('rm -rf %s' % install_dir)
149 self._run_command('mkdir -p %s' % install_dir)
150
151 self.untar_pkg(fetch_path, install_dir)
152
153 except PackageFetchError, why:
154 raise PackageInstallError('Installation of %s(type:%s) failed'
155 ' : %s' % (name, pkg_type, why))
156 finally:
157 if self.do_locking:
158 fcntl.flock(lockfile, fcntl.LOCK_UN)
159 lockfile.close()
160
161
mbligh76d19f72008-10-15 16:24:43 +0000162 def fetch_pkg(self, pkg_name, dest_path, repo_url=None, use_checksum=False):
showard9d02fb52008-08-08 18:20:37 +0000163 '''
164 Fetch the package into dest_dir from repo_url. By default repo_url
165 is None and the package is looked in all the repostories specified.
166 Otherwise it fetches it from the specific repo_url.
167 pkg_name : name of the package (ex: test-sleeptest.tar.bz2,
168 dep-gcc.tar.bz2, kernel.1-1.rpm)
169 repo_url : the URL of the repository where the package is located.
170 dest_path : complete path of where the package will be fetched to.
171 use_checksum : This is set to False to fetch the packages.checksum file
172 so that the checksum comparison is bypassed for the
173 checksum file itself. This is used internally by the
174 packaging system. It should be ignored by externals
175 callers of this method who use it fetch custom packages.
176 '''
177
178 try:
179 self._run_command("ls %s" % os.path.dirname(dest_path))
180 except (error.CmdError, error.AutoservRunError):
181 raise PackageFetchError("Please provide a valid "
182 "destination: %s " % dest_path)
183
184 # See if the package was already fetched earlier, if so
185 # the checksums need to be compared and the package is now
186 # fetched only if they differ.
187 pkg_exists = False
188 try:
189 self._run_command("ls %s" % dest_path)
190 pkg_exists = True
191 except (error.CmdError, error.AutoservRunError):
192 pass
193
194 # if a repository location is explicitly provided, fetch the package
195 # from there and return
196 if repo_url:
197 repo_url_list = [repo_url]
198 elif len(self.repo_urls) > 0:
199 repo_url_list = self.repo_urls
200 else:
201 raise PackageFetchError("There are no repository urls specified")
202
203 error_msgs = {}
204 for location in repo_url_list:
205 try:
206 # Fetch the checksum if it not there
207 if not use_checksum:
208 self.fetch_pkg_file(pkg_name, dest_path, location)
209
210 # Fetch the package if a) the pkg does not exist or
211 # b) if the checksum differs for the existing package
212 elif (not pkg_exists or
213 not self.compare_checksum(dest_path, location)):
214 self.fetch_pkg_file(pkg_name, dest_path, location)
215 # Update the checksum of the package in the packages'
216 # checksum file
217 self.update_checksum(dest_path)
218 return
219 except (PackageFetchError, error.AutoservRunError), e:
220 # The package could not be found in this repo, continue looking
221 error_msgs[location] = str(e)
mbligh76d19f72008-10-15 16:24:43 +0000222 print '%s could not be fetched from - %s : %s' % (pkg_name,
223 location, e)
showard9d02fb52008-08-08 18:20:37 +0000224
225 # if we got here then that means the package is not found
226 # in any of the repositories.
mbligh76d19f72008-10-15 16:24:43 +0000227 raise PackageFetchError("%s could not be fetched from any of"
228 " the repos %s : %s " % (pkg_name,
229 repo_url_list,
showard9d02fb52008-08-08 18:20:37 +0000230 error_msgs))
231
232
mbligh76d19f72008-10-15 16:24:43 +0000233 def fetch_pkg_file(self, filename, dest_path, source_url):
showard9d02fb52008-08-08 18:20:37 +0000234 """
235 Fetch the file from source_url into dest_path. The package repository
236 url is parsed and the appropriate retrieval method is determined.
237
238 """
239 if source_url.startswith('http://'):
mbligh76d19f72008-10-15 16:24:43 +0000240 self.fetch_file_http(filename, dest_path, source_url)
showard9d02fb52008-08-08 18:20:37 +0000241 else:
mbligh76d19f72008-10-15 16:24:43 +0000242 raise PackageFetchError("Invalid location %s" % source_url)
showard9d02fb52008-08-08 18:20:37 +0000243
244
mbligh76d19f72008-10-15 16:24:43 +0000245 def fetch_file_http(self, filename, dest_path, source_url):
showard9d02fb52008-08-08 18:20:37 +0000246 """
247 Fetch the package using http protocol. Raises a PackageFetchError.
248 """
mbligh76d19f72008-10-15 16:24:43 +0000249 print "Fetching %s from %s to %s" % (filename, source_url, dest_path)
showard9d02fb52008-08-08 18:20:37 +0000250 # check to see if the source_url is reachable or not
251 self.run_http_test(source_url, os.path.dirname(dest_path))
252
mbligh76d19f72008-10-15 16:24:43 +0000253 pkg_path = os.path.join(source_url, filename)
showard9d02fb52008-08-08 18:20:37 +0000254 try:
mblighdc1e7aa2008-10-10 21:12:15 +0000255 self._run_command('wget -nv %s -O %s' % (pkg_path, dest_path))
showard9d02fb52008-08-08 18:20:37 +0000256 except error.CmdError, e:
mbligh76d19f72008-10-15 16:24:43 +0000257 raise PackageFetchError("%s not found in %s: %s"
258 % (filename, source_url, e))
showard9d02fb52008-08-08 18:20:37 +0000259
260
261 def run_http_test(self, source_url, dest_dir):
262 '''
263 Run a simple 30 sec wget on source_url
264 just to see if it can be reachable or not. This avoids the need
265 for waiting for a 10min timeout.
266 '''
267 dest_file_path = os.path.join(dest_dir, 'http_test_file')
268
269 BPM = BasePackageManager
270 error_msg = "HTTP test failed. Failed to contact"
271 # We should never get here unless the source_url starts with http://
272 assert(source_url.startswith('http://'))
273
274 # Get the http server name from the URL
275 server_name = urlparse.urlparse(source_url)[1]
mbligh76d19f72008-10-15 16:24:43 +0000276 http_cmd = 'wget -nv %s -O %s' % (server_name, dest_file_path)
showard9d02fb52008-08-08 18:20:37 +0000277 if server_name in BPM._repo_exception:
278 if BPM._repo_exception[server_name] == BPM.REPO_OK:
279 # This repository is fine. Simply return
280 return
281 else:
282 raise PackageFetchError("%s - %s : %s "
283 % (error_msg, server_name,
284 BPM._repo_exception[server_name]))
285 try:
286 try:
287 self._run_command(http_cmd,
288 _run_command_dargs={'timeout':30})
289 BPM._repo_exception[server_name] = BPM.REPO_OK
290 finally:
291 self._run_command('rm -f %s' % dest_file_path)
mbligh76d19f72008-10-15 16:24:43 +0000292 except Exception, e:
showard9d02fb52008-08-08 18:20:37 +0000293 BPM._repo_exception[server_name] = e
mbligh76d19f72008-10-15 16:24:43 +0000294 raise PackageFetchError("%s - %s: %s " % (error_msg, server_name,
295 e))
showard9d02fb52008-08-08 18:20:37 +0000296
297
298 # TODO(aganti): Fix the bug with the current checksum logic where
299 # packages' checksums that are not present consistently in all the
300 # repositories are not handled properly. This is a corner case though
301 # but the ideal solution is to make the checksum file repository specific
302 # and then maintain it.
303 def upload_pkg(self, pkg_path, upload_path=None, update_checksum=False):
304 '''
305 Uploads to a specified upload_path or to all the repos.
306 Also uploads the checksum file to all the repos.
307 pkg_path : The complete path to the package file
308 upload_path : the absolute path where the files are copied to.
309 if set to 'None' assumes 'all' repos
310 update_checksum : If set to False, the checksum file is not
311 going to be updated which happens by default.
312 This is necessary for custom
313 packages (like custom kernels and custom tests)
314 that get uploaded which do not need to be part of
315 the checksum file and bloat it.
316 '''
317 if update_checksum:
318 # get the packages' checksum file and update it with the current
319 # package's checksum
320 checksum_path = self._get_checksum_file_path()
321 self.update_checksum(pkg_path)
322
323 if upload_path:
324 upload_path_list = [upload_path]
325 elif len(self.upload_paths) > 0:
326 upload_path_list = self.upload_paths
327 else:
328 raise PackageUploadError("Invalid Upload Path specified")
329
330 # upload the package
331 for path in upload_path_list:
332 self.upload_pkg_file(pkg_path, path)
333 if update_checksum:
334 self.upload_pkg_file(checksum_path, path)
335
336
337 def upload_pkg_file(self, file_path, upload_path):
338 '''
339 Upload a single file. Depending on the upload path, the appropriate
340 method for that protocol is called. Currently this simply copies the
341 file to the target directory (but can be extended for other protocols)
342 This assumes that the web server is running on the same machine where
343 the method is being called from. The upload_path's files are
344 basically served by that web server.
345 '''
346 try:
mbligh93a9e292008-10-10 21:09:53 +0000347 if upload_path.startswith('ssh://'):
348 # parse ssh://user@host/usr/local/autotest/packages
349 hostline, remote_path = self._parse_ssh_path(upload_path)
mbligh1e3b0992008-10-14 16:29:54 +0000350 try:
351 utils.run('scp %s %s:%s' % (file_path, hostline,
352 remote_path))
353 r_path = os.path.join(remote_path,
354 os.path.basename(file_path))
355 utils.run("ssh %s 'chmod 644 %s'" % (hostline, r_path))
356 except error.CmdError:
357 print "Error uploading to repository " + upload_path
358 pass
mbligh93a9e292008-10-10 21:09:53 +0000359 else:
360 shutil.copy(file_path, upload_path)
361 os.chmod(os.path.join(upload_path,
362 os.path.basename(file_path)), 0644)
showard9d02fb52008-08-08 18:20:37 +0000363 except (IOError, os.error), why:
364 raise PackageUploadError("Upload of %s to %s failed: %s"
365 % (file_path, upload_path, why))
366
367
mbligh9fc77972008-10-02 20:32:09 +0000368 def upload_pkg_dir(self, dir_path, upload_path):
369 '''
370 Upload a full directory. Depending on the upload path, the appropriate
371 method for that protocol is called. Currently this copies the whole
372 tmp package directory to the target directory.
373 This assumes that the web server is running on the same machine where
374 the method is being called from. The upload_path's files are
375 basically served by that web server.
376 '''
mbligh93a9e292008-10-10 21:09:53 +0000377 local_path = os.path.join(dir_path, "*")
mbligh9fc77972008-10-02 20:32:09 +0000378 try:
mbligh93a9e292008-10-10 21:09:53 +0000379 if upload_path.startswith('ssh://'):
380 hostline, remote_path = self._parse_ssh_path(upload_path)
mbligh1e3b0992008-10-14 16:29:54 +0000381 try:
382 utils.run('scp %s %s:%s' % (local_path, hostline,
383 remote_path))
384 ssh_path = os.path.join(remote_path, "*")
385 utils.run("ssh %s 'chmod 644 %s'" % (hostline, ssh_path))
386 except error.CmdError:
387 print "Error uploading to repository: " + upload_path
388 pass
mbligh93a9e292008-10-10 21:09:53 +0000389 else:
390 utils.run("cp %s %s " % (local_path, upload_path))
391 up_path = os.path.join(upload_path, "*")
392 utils.run("chmod 644 %s" % up_path)
mbligh9fc77972008-10-02 20:32:09 +0000393 except (IOError, os.error), why:
394 raise PackageUploadError("Upload of %s to %s failed: %s"
395 % (dir_path, upload_path, why))
396
397
showard9d02fb52008-08-08 18:20:37 +0000398 def remove_pkg(self, pkg_name, remove_path=None, remove_checksum=False):
399 '''
400 Remove the package from the specified remove_path
401 pkg_name : name of the package (ex: test-sleeptest.tar.bz2,
402 dep-gcc.tar.bz2)
403 remove_path : the location to remove the package from.
404
405 '''
406 if remove_path:
407 remove_path_list = [remove_path]
408 elif len(self.upload_paths) > 0:
409 remove_path_list = self.upload_paths
410 else:
411 raise PackageRemoveError("Invalid path to remove the pkg from")
412
413 checksum_path = self._get_checksum_file_path()
414
415 if remove_checksum:
416 self.remove_checksum(pkg_name)
417
418 # remove the package and upload the checksum file to the repos
419 for path in remove_path_list:
420 self.remove_pkg_file(pkg_name, path)
421 self.upload_pkg_file(checksum_path, path)
422
423
mbligh76d19f72008-10-15 16:24:43 +0000424 def remove_pkg_file(self, filename, pkg_dir):
showard9d02fb52008-08-08 18:20:37 +0000425 '''
mbligh76d19f72008-10-15 16:24:43 +0000426 Remove the file named filename from pkg_dir
showard9d02fb52008-08-08 18:20:37 +0000427 '''
428 try:
429 # Remove the file
mbligh93a9e292008-10-10 21:09:53 +0000430 if pkg_dir.startswith('ssh://'):
431 hostline, remote_path = self._parse_ssh_path(pkg_dir)
mbligh76d19f72008-10-15 16:24:43 +0000432 path = os.path.join(remote_path, filename)
mbligh93a9e292008-10-10 21:09:53 +0000433 utils.run("ssh %s 'rm -rf %s/%s'" % (hostline, remote_path,
434 path))
435 else:
mbligh76d19f72008-10-15 16:24:43 +0000436 os.remove(os.path.join(pkg_dir, filename))
showard9d02fb52008-08-08 18:20:37 +0000437 except (IOError, os.error), why:
438 raise PackageRemoveError("Could not remove %s from %s: %s "
mbligh76d19f72008-10-15 16:24:43 +0000439 % (filename, pkg_dir, why))
showard9d02fb52008-08-08 18:20:37 +0000440
441
mbligh76d19f72008-10-15 16:24:43 +0000442 def get_mirror_list(self):
mbligh1e3b0992008-10-14 16:29:54 +0000443 '''
mbligh76d19f72008-10-15 16:24:43 +0000444 Stub function for site specific mirrors.
mbligh1e3b0992008-10-14 16:29:54 +0000445
446 Returns:
447 Priority ordered list
448 '''
449 return self.repo_urls
450
451
showard9d02fb52008-08-08 18:20:37 +0000452 def _get_checksum_file_path(self):
453 '''
454 Return the complete path of the checksum file (assumed to be stored
455 in self.pkgmgr_dir
456 '''
457 return os.path.join(self.pkgmgr_dir, CHECKSUM_FILE)
458
459
460 def _get_checksum_dict(self):
461 '''
462 Fetch the checksum file if not already fetched. If the checksum file
463 cannot be fetched from the repos then a new file is created with
464 the current package's (specified in pkg_path) checksum value in it.
465 Populate the local checksum dictionary with the values read from
466 the checksum file.
467 The checksum file is assumed to be present in self.pkgmgr_dir
468 '''
469 checksum_path = self._get_checksum_file_path()
470 if not self._checksum_dict:
471 # Fetch the checksum file
472 try:
473 try:
474 self._run_command("ls %s" % checksum_path)
475 except (error.CmdError, error.AutoservRunError):
476 # The packages checksum file does not exist locally.
477 # See if it is present in the repositories.
mbligh76d19f72008-10-15 16:24:43 +0000478 self.fetch_pkg(CHECKSUM_FILE, checksum_path)
showard9d02fb52008-08-08 18:20:37 +0000479 except PackageFetchError, e:
480 # This should not happen whilst fetching a package..if a
481 # package is present in the repository, the corresponding
482 # checksum file should also be automatically present. This
483 # case happens only when a package
484 # is being uploaded and if it is the first package to be
485 # uploaded to the repos (hence no checksum file created yet)
486 # Return an empty dictionary in that case
487 return {}
488
489 # Read the checksum file into memory
490 checksum_file_contents = self._run_command('cat '
491 + checksum_path).stdout
492
493 # Return {} if we have an empty checksum file present
494 if not checksum_file_contents.strip():
495 return {}
496
497 # Parse the checksum file contents into self._checksum_dict
498 for line in checksum_file_contents.splitlines():
499 checksum, package_name = line.split(None, 1)
500 self._checksum_dict[package_name] = checksum
501
502 return self._checksum_dict
503
504
505 def _save_checksum_dict(self, checksum_dict):
506 '''
507 Save the checksum dictionary onto the checksum file. Update the
508 local _checksum_dict variable with this new set of values.
509 checksum_dict : New checksum dictionary
510 checksum_dir : The directory in which to store the checksum file to.
511 '''
512 checksum_path = self._get_checksum_file_path()
513 self._checksum_dict = checksum_dict.copy()
514 checksum_contents = '\n'.join(checksum + ' ' + pkg_name
515 for pkg_name,checksum in
516 checksum_dict.iteritems())
517 # Write the checksum file back to disk
518 self._run_command('echo "%s" > %s' % (checksum_contents,
519 checksum_path))
520
mbligh93a9e292008-10-10 21:09:53 +0000521 def _parse_ssh_path(self, pkg_path):
522 '''
523 Parse ssh://xx@xx/path/to/ and return a tuple with host_line and
524 remote path
525 '''
526
527 match = re.search('^ssh://(.*?)(/.*)$', pkg_path)
528 if match:
529 return match.groups()
530 else:
531 raise PackageUploadError("Incorrect SSH path in global_config: %s"
532 % upload_path)
533
showard9d02fb52008-08-08 18:20:37 +0000534
535 def compute_checksum(self, pkg_path):
536 '''
537 Compute the MD5 checksum for the package file and return it.
538 pkg_path : The complete path for the package file
539 '''
540 md5sum_output = self._run_command("md5sum %s " % pkg_path).stdout
541 return md5sum_output.split()[0]
542
543
544 def update_checksum(self, pkg_path):
545 '''
546 Update the checksum of the package in the packages' checksum
547 file. This method is called whenever a package is fetched just
548 to be sure that the checksums in the local file are the latest.
549 pkg_path : The complete path to the package file.
550 '''
551 # Compute the new checksum
552 new_checksum = self.compute_checksum(pkg_path)
553 checksum_dict = self._get_checksum_dict()
554 checksum_dict[os.path.basename(pkg_path)] = new_checksum
555 self._save_checksum_dict(checksum_dict)
556
557
558 def remove_checksum(self, pkg_name):
559 '''
560 Remove the checksum of the package from the packages checksum file.
561 This method is called whenever a package is removed from the
562 repositories in order clean its corresponding checksum.
563 pkg_name : The name of the package to be removed
564 '''
565 checksum_dict = self._get_checksum_dict()
566 if pkg_name in checksum_dict:
567 del checksum_dict[pkg_name]
568 self._save_checksum_dict(checksum_dict)
569
570
571 def compare_checksum(self, pkg_path, repo_url):
572 '''
573 Calculate the checksum of the file specified in pkg_path and
574 compare it with the checksum in the checksum file
575 Return True if both match else return False.
576 pkg_path : The full path to the package file for which the
577 checksum is being compared
578 repo_url : The URL to fetch the checksum from
579 '''
580 checksum_dict = self._get_checksum_dict()
581 package_name = os.path.basename(pkg_path)
582 if not checksum_dict or package_name not in checksum_dict:
583 return False
584
585 repository_checksum = checksum_dict[package_name]
586 local_checksum = self.compute_checksum(pkg_path)
587 return (local_checksum == repository_checksum)
588
589
mblighdbfc4e32008-08-22 18:08:07 +0000590 def tar_package(self, pkg_name, src_dir, dest_dir, exclude_string=None):
showard9d02fb52008-08-08 18:20:37 +0000591 '''
592 Create a tar.bz2 file with the name 'pkg_name' say test-blah.tar.bz2.
mbligh9fc77972008-10-02 20:32:09 +0000593 Excludes the directories specified in exclude_string while tarring
showard9d02fb52008-08-08 18:20:37 +0000594 the source. Returns the tarball path.
595 '''
showard9d02fb52008-08-08 18:20:37 +0000596 tarball_path = os.path.join(dest_dir, pkg_name)
mbligh9fc77972008-10-02 20:32:09 +0000597 cmd = "tar -cvjf %s -C %s %s " % (tarball_path, src_dir, exclude_string)
showard9d02fb52008-08-08 18:20:37 +0000598
mbligh9fc77972008-10-02 20:32:09 +0000599 utils.system(cmd)
showard9d02fb52008-08-08 18:20:37 +0000600 return tarball_path
601
602
603 def untar_required(self, tarball_path, dest_dir):
604 '''
605 Compare the checksum of the tarball_path with the .checksum file
606 in the dest_dir and return False if it matches. The untar
607 of the package happens only if the checksums do not match.
608 '''
609 checksum_path = os.path.join(dest_dir, '.checksum')
610 try:
611 existing_checksum = self._run_command('cat ' + checksum_path).stdout
612 except (error.CmdError, error.AutoservRunError):
613 # If the .checksum file is not present (generally, this should
614 # not be the case) then return True so that the untar happens
615 return True
616
617 new_checksum = self.compute_checksum(tarball_path)
618 return (new_checksum.strip() != existing_checksum.strip())
619
620
621 def untar_pkg(self, tarball_path, dest_dir):
622 '''
623 Untar the package present in the tarball_path and put a
624 ".checksum" file in the dest_dir containing the checksum
625 of the tarball. This method
626 assumes that the package to be untarred is of the form
627 <name>.tar.bz2
628 '''
mbligh96ad8512008-10-03 03:45:26 +0000629 self._run_command('tar xjf %s -C %s' % (tarball_path, dest_dir))
showard9d02fb52008-08-08 18:20:37 +0000630 # Put the .checksum file in the install_dir to note
631 # where the package came from
632 pkg_checksum = self.compute_checksum(tarball_path)
633 pkg_checksum_path = os.path.join(dest_dir,
634 '.checksum')
635 self._run_command('echo "%s" > %s '
636 % (pkg_checksum, pkg_checksum_path))
637
638
639 def get_tarball_name(self, name, pkg_type):
640 return "%s-%s.tar.bz2" % (pkg_type, name)
641
642
643 def is_url(self, url):
644 """Return true if path looks like a URL"""
645 return url.startswith('http://')
646
647
648 def get_package_name(self, url, pkg_type):
649 '''
650 Extract the group and test name for the url. This method is currently
651 used only for tests.
652 '''
653 if pkg_type == 'test':
mblighecbaec32008-10-25 13:37:42 +0000654 regex = '[^:]+://(.*)/([^/]*)$'
showard9d02fb52008-08-08 18:20:37 +0000655 return self._get_package_name(url, regex)
656 else:
657 return ('', url)
658
659
660 def _get_package_name(self, url, regex):
661 if not self.is_url(url):
662 if url.endswith('.tar.bz2'):
663 testname = url.replace('.tar.bz2', '')
664 testname = re.sub(r'(\d*)\.', '', testname)
665 return (testname, testname)
666 else:
667 return ('', url)
668
669 match = re.match(regex, url)
670 if not match:
671 return ('', url)
672 group, filename = match.groups()
673 # Generate the group prefix.
674 group = re.sub(r'\W', '_', group)
675 # Drop the extension to get the raw test name.
676 testname = re.sub(r'\.tar\.bz2', '', filename)
677 # Drop any random numbers at the end of the test name if any
678 testname = re.sub(r'\.(\d*)', '', testname)
679 return (group, testname)
680
681
682# site_packages.py may be non-existant or empty, make sure that an appropriate
683# SitePackage class is created nevertheless
684try:
685 from site_packages import SitePackageManager
686except ImportError:
687 class SitePackageManager(BasePackageManager):
688 pass
689
690class PackageManager(SitePackageManager):
691 pass