blob: 61269b95af24cedc23daffa97c79d30befe88bae [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
mbligh7a603672009-02-07 01:52:08 +0000219 except (PackageFetchError, error.AutoservRunError):
showard9d02fb52008-08-08 18:20:37 +0000220 # The package could not be found in this repo, continue looking
mbligh7a603672009-02-07 01:52:08 +0000221 print '%s could not be fetched from %s' % (pkg_name, location)
showard9d02fb52008-08-08 18:20:37 +0000222
223 # if we got here then that means the package is not found
224 # in any of the repositories.
mbligh76d19f72008-10-15 16:24:43 +0000225 raise PackageFetchError("%s could not be fetched from any of"
226 " the repos %s : %s " % (pkg_name,
227 repo_url_list,
showard9d02fb52008-08-08 18:20:37 +0000228 error_msgs))
229
230
mbligh76d19f72008-10-15 16:24:43 +0000231 def fetch_pkg_file(self, filename, dest_path, source_url):
showard9d02fb52008-08-08 18:20:37 +0000232 """
233 Fetch the file from source_url into dest_path. The package repository
234 url is parsed and the appropriate retrieval method is determined.
235
236 """
237 if source_url.startswith('http://'):
mbligh76d19f72008-10-15 16:24:43 +0000238 self.fetch_file_http(filename, dest_path, source_url)
showard9d02fb52008-08-08 18:20:37 +0000239 else:
mbligh76d19f72008-10-15 16:24:43 +0000240 raise PackageFetchError("Invalid location %s" % source_url)
showard9d02fb52008-08-08 18:20:37 +0000241
242
mbligh76d19f72008-10-15 16:24:43 +0000243 def fetch_file_http(self, filename, dest_path, source_url):
showard9d02fb52008-08-08 18:20:37 +0000244 """
245 Fetch the package using http protocol. Raises a PackageFetchError.
246 """
mbligh76d19f72008-10-15 16:24:43 +0000247 print "Fetching %s from %s to %s" % (filename, source_url, dest_path)
showard9d02fb52008-08-08 18:20:37 +0000248 # check to see if the source_url is reachable or not
249 self.run_http_test(source_url, os.path.dirname(dest_path))
250
mbligh76d19f72008-10-15 16:24:43 +0000251 pkg_path = os.path.join(source_url, filename)
showard9d02fb52008-08-08 18:20:37 +0000252 try:
mblighdc1e7aa2008-10-10 21:12:15 +0000253 self._run_command('wget -nv %s -O %s' % (pkg_path, dest_path))
mbligh7a603672009-02-07 01:52:08 +0000254 print "Successfully fetched %s from %s" % (filename, source_url)
255 except error.CmdError:
256 raise PackageFetchError("%s not found in %s" % (filename,
257 source_url))
showard9d02fb52008-08-08 18:20:37 +0000258
259
260 def run_http_test(self, source_url, dest_dir):
261 '''
262 Run a simple 30 sec wget on source_url
263 just to see if it can be reachable or not. This avoids the need
264 for waiting for a 10min timeout.
265 '''
266 dest_file_path = os.path.join(dest_dir, 'http_test_file')
267
268 BPM = BasePackageManager
269 error_msg = "HTTP test failed. Failed to contact"
270 # We should never get here unless the source_url starts with http://
271 assert(source_url.startswith('http://'))
272
273 # Get the http server name from the URL
274 server_name = urlparse.urlparse(source_url)[1]
mbligh76d19f72008-10-15 16:24:43 +0000275 http_cmd = 'wget -nv %s -O %s' % (server_name, dest_file_path)
mblighabe330e2008-12-09 23:37:52 +0000276
277 # Following repo_exception optimization is disabled for now.
278 # Checksum files are optional. The attempted download of a
279 # missing checksum file erroneously causes the repos to be marked
280 # dead, causing download of its custom kernels to fail.
281 # It also stays dead until Autotest is restarted.
282 if server_name in BPM._repo_exception and False: # <--- TEMP
showard9d02fb52008-08-08 18:20:37 +0000283 if BPM._repo_exception[server_name] == BPM.REPO_OK:
284 # This repository is fine. Simply return
285 return
286 else:
287 raise PackageFetchError("%s - %s : %s "
288 % (error_msg, server_name,
289 BPM._repo_exception[server_name]))
290 try:
291 try:
292 self._run_command(http_cmd,
293 _run_command_dargs={'timeout':30})
294 BPM._repo_exception[server_name] = BPM.REPO_OK
295 finally:
296 self._run_command('rm -f %s' % dest_file_path)
mbligh76d19f72008-10-15 16:24:43 +0000297 except Exception, e:
showard9d02fb52008-08-08 18:20:37 +0000298 BPM._repo_exception[server_name] = e
mbligh76d19f72008-10-15 16:24:43 +0000299 raise PackageFetchError("%s - %s: %s " % (error_msg, server_name,
300 e))
showard9d02fb52008-08-08 18:20:37 +0000301
302
303 # TODO(aganti): Fix the bug with the current checksum logic where
304 # packages' checksums that are not present consistently in all the
305 # repositories are not handled properly. This is a corner case though
306 # but the ideal solution is to make the checksum file repository specific
307 # and then maintain it.
308 def upload_pkg(self, pkg_path, upload_path=None, update_checksum=False):
309 '''
310 Uploads to a specified upload_path or to all the repos.
311 Also uploads the checksum file to all the repos.
312 pkg_path : The complete path to the package file
313 upload_path : the absolute path where the files are copied to.
314 if set to 'None' assumes 'all' repos
315 update_checksum : If set to False, the checksum file is not
316 going to be updated which happens by default.
317 This is necessary for custom
318 packages (like custom kernels and custom tests)
319 that get uploaded which do not need to be part of
320 the checksum file and bloat it.
321 '''
322 if update_checksum:
323 # get the packages' checksum file and update it with the current
324 # package's checksum
325 checksum_path = self._get_checksum_file_path()
326 self.update_checksum(pkg_path)
327
328 if upload_path:
329 upload_path_list = [upload_path]
330 elif len(self.upload_paths) > 0:
331 upload_path_list = self.upload_paths
332 else:
333 raise PackageUploadError("Invalid Upload Path specified")
334
335 # upload the package
336 for path in upload_path_list:
337 self.upload_pkg_file(pkg_path, path)
338 if update_checksum:
339 self.upload_pkg_file(checksum_path, path)
340
341
342 def upload_pkg_file(self, file_path, upload_path):
343 '''
344 Upload a single file. Depending on the upload path, the appropriate
345 method for that protocol is called. Currently this simply copies the
346 file to the target directory (but can be extended for other protocols)
347 This assumes that the web server is running on the same machine where
348 the method is being called from. The upload_path's files are
349 basically served by that web server.
350 '''
351 try:
mbligh93a9e292008-10-10 21:09:53 +0000352 if upload_path.startswith('ssh://'):
353 # parse ssh://user@host/usr/local/autotest/packages
354 hostline, remote_path = self._parse_ssh_path(upload_path)
mbligh1e3b0992008-10-14 16:29:54 +0000355 try:
356 utils.run('scp %s %s:%s' % (file_path, hostline,
357 remote_path))
358 r_path = os.path.join(remote_path,
359 os.path.basename(file_path))
360 utils.run("ssh %s 'chmod 644 %s'" % (hostline, r_path))
361 except error.CmdError:
362 print "Error uploading to repository " + upload_path
mbligh93a9e292008-10-10 21:09:53 +0000363 else:
364 shutil.copy(file_path, upload_path)
365 os.chmod(os.path.join(upload_path,
366 os.path.basename(file_path)), 0644)
showard9d02fb52008-08-08 18:20:37 +0000367 except (IOError, os.error), why:
mbligh7a603672009-02-07 01:52:08 +0000368 print "Upload of %s to %s failed: %s" % (file_path, upload_path,
369 why)
showard9d02fb52008-08-08 18:20:37 +0000370
371
mbligh9fc77972008-10-02 20:32:09 +0000372 def upload_pkg_dir(self, dir_path, upload_path):
373 '''
374 Upload a full directory. Depending on the upload path, the appropriate
375 method for that protocol is called. Currently this copies the whole
376 tmp package directory to the target directory.
377 This assumes that the web server is running on the same machine where
378 the method is being called from. The upload_path's files are
379 basically served by that web server.
380 '''
mbligh93a9e292008-10-10 21:09:53 +0000381 local_path = os.path.join(dir_path, "*")
mbligh9fc77972008-10-02 20:32:09 +0000382 try:
mbligh93a9e292008-10-10 21:09:53 +0000383 if upload_path.startswith('ssh://'):
384 hostline, remote_path = self._parse_ssh_path(upload_path)
mbligh1e3b0992008-10-14 16:29:54 +0000385 try:
386 utils.run('scp %s %s:%s' % (local_path, hostline,
387 remote_path))
388 ssh_path = os.path.join(remote_path, "*")
389 utils.run("ssh %s 'chmod 644 %s'" % (hostline, ssh_path))
390 except error.CmdError:
391 print "Error uploading to repository: " + upload_path
mbligh93a9e292008-10-10 21:09:53 +0000392 else:
393 utils.run("cp %s %s " % (local_path, upload_path))
394 up_path = os.path.join(upload_path, "*")
395 utils.run("chmod 644 %s" % up_path)
mbligh9fc77972008-10-02 20:32:09 +0000396 except (IOError, os.error), why:
397 raise PackageUploadError("Upload of %s to %s failed: %s"
398 % (dir_path, upload_path, why))
399
400
showard9d02fb52008-08-08 18:20:37 +0000401 def remove_pkg(self, pkg_name, remove_path=None, remove_checksum=False):
402 '''
403 Remove the package from the specified remove_path
404 pkg_name : name of the package (ex: test-sleeptest.tar.bz2,
405 dep-gcc.tar.bz2)
406 remove_path : the location to remove the package from.
407
408 '''
409 if remove_path:
410 remove_path_list = [remove_path]
411 elif len(self.upload_paths) > 0:
412 remove_path_list = self.upload_paths
413 else:
414 raise PackageRemoveError("Invalid path to remove the pkg from")
415
416 checksum_path = self._get_checksum_file_path()
417
418 if remove_checksum:
419 self.remove_checksum(pkg_name)
420
421 # remove the package and upload the checksum file to the repos
422 for path in remove_path_list:
423 self.remove_pkg_file(pkg_name, path)
424 self.upload_pkg_file(checksum_path, path)
425
426
mbligh76d19f72008-10-15 16:24:43 +0000427 def remove_pkg_file(self, filename, pkg_dir):
showard9d02fb52008-08-08 18:20:37 +0000428 '''
mbligh76d19f72008-10-15 16:24:43 +0000429 Remove the file named filename from pkg_dir
showard9d02fb52008-08-08 18:20:37 +0000430 '''
431 try:
432 # Remove the file
mbligh93a9e292008-10-10 21:09:53 +0000433 if pkg_dir.startswith('ssh://'):
434 hostline, remote_path = self._parse_ssh_path(pkg_dir)
mbligh76d19f72008-10-15 16:24:43 +0000435 path = os.path.join(remote_path, filename)
mbligh93a9e292008-10-10 21:09:53 +0000436 utils.run("ssh %s 'rm -rf %s/%s'" % (hostline, remote_path,
437 path))
438 else:
mbligh76d19f72008-10-15 16:24:43 +0000439 os.remove(os.path.join(pkg_dir, filename))
showard9d02fb52008-08-08 18:20:37 +0000440 except (IOError, os.error), why:
441 raise PackageRemoveError("Could not remove %s from %s: %s "
mbligh76d19f72008-10-15 16:24:43 +0000442 % (filename, pkg_dir, why))
showard9d02fb52008-08-08 18:20:37 +0000443
444
mbligh76d19f72008-10-15 16:24:43 +0000445 def get_mirror_list(self):
mbligh1e3b0992008-10-14 16:29:54 +0000446 '''
mbligh76d19f72008-10-15 16:24:43 +0000447 Stub function for site specific mirrors.
mbligh1e3b0992008-10-14 16:29:54 +0000448
449 Returns:
450 Priority ordered list
451 '''
452 return self.repo_urls
453
454
showard9d02fb52008-08-08 18:20:37 +0000455 def _get_checksum_file_path(self):
456 '''
457 Return the complete path of the checksum file (assumed to be stored
458 in self.pkgmgr_dir
459 '''
460 return os.path.join(self.pkgmgr_dir, CHECKSUM_FILE)
461
462
463 def _get_checksum_dict(self):
464 '''
465 Fetch the checksum file if not already fetched. If the checksum file
466 cannot be fetched from the repos then a new file is created with
467 the current package's (specified in pkg_path) checksum value in it.
468 Populate the local checksum dictionary with the values read from
469 the checksum file.
470 The checksum file is assumed to be present in self.pkgmgr_dir
471 '''
472 checksum_path = self._get_checksum_file_path()
473 if not self._checksum_dict:
474 # Fetch the checksum file
475 try:
476 try:
477 self._run_command("ls %s" % checksum_path)
478 except (error.CmdError, error.AutoservRunError):
479 # The packages checksum file does not exist locally.
480 # See if it is present in the repositories.
mbligh76d19f72008-10-15 16:24:43 +0000481 self.fetch_pkg(CHECKSUM_FILE, checksum_path)
showard9d02fb52008-08-08 18:20:37 +0000482 except PackageFetchError, e:
483 # This should not happen whilst fetching a package..if a
484 # package is present in the repository, the corresponding
485 # checksum file should also be automatically present. This
486 # case happens only when a package
487 # is being uploaded and if it is the first package to be
488 # uploaded to the repos (hence no checksum file created yet)
489 # Return an empty dictionary in that case
490 return {}
491
492 # Read the checksum file into memory
493 checksum_file_contents = self._run_command('cat '
494 + checksum_path).stdout
495
496 # Return {} if we have an empty checksum file present
497 if not checksum_file_contents.strip():
498 return {}
499
500 # Parse the checksum file contents into self._checksum_dict
501 for line in checksum_file_contents.splitlines():
502 checksum, package_name = line.split(None, 1)
503 self._checksum_dict[package_name] = checksum
504
505 return self._checksum_dict
506
507
508 def _save_checksum_dict(self, checksum_dict):
509 '''
510 Save the checksum dictionary onto the checksum file. Update the
511 local _checksum_dict variable with this new set of values.
512 checksum_dict : New checksum dictionary
513 checksum_dir : The directory in which to store the checksum file to.
514 '''
515 checksum_path = self._get_checksum_file_path()
516 self._checksum_dict = checksum_dict.copy()
517 checksum_contents = '\n'.join(checksum + ' ' + pkg_name
518 for pkg_name,checksum in
519 checksum_dict.iteritems())
520 # Write the checksum file back to disk
521 self._run_command('echo "%s" > %s' % (checksum_contents,
522 checksum_path))
523
mbligh93a9e292008-10-10 21:09:53 +0000524 def _parse_ssh_path(self, pkg_path):
525 '''
526 Parse ssh://xx@xx/path/to/ and return a tuple with host_line and
527 remote path
528 '''
529
530 match = re.search('^ssh://(.*?)(/.*)$', pkg_path)
531 if match:
532 return match.groups()
533 else:
534 raise PackageUploadError("Incorrect SSH path in global_config: %s"
535 % upload_path)
536
showard9d02fb52008-08-08 18:20:37 +0000537
538 def compute_checksum(self, pkg_path):
539 '''
540 Compute the MD5 checksum for the package file and return it.
541 pkg_path : The complete path for the package file
542 '''
543 md5sum_output = self._run_command("md5sum %s " % pkg_path).stdout
544 return md5sum_output.split()[0]
545
546
547 def update_checksum(self, pkg_path):
548 '''
549 Update the checksum of the package in the packages' checksum
550 file. This method is called whenever a package is fetched just
551 to be sure that the checksums in the local file are the latest.
552 pkg_path : The complete path to the package file.
553 '''
554 # Compute the new checksum
555 new_checksum = self.compute_checksum(pkg_path)
556 checksum_dict = self._get_checksum_dict()
557 checksum_dict[os.path.basename(pkg_path)] = new_checksum
558 self._save_checksum_dict(checksum_dict)
559
560
561 def remove_checksum(self, pkg_name):
562 '''
563 Remove the checksum of the package from the packages checksum file.
564 This method is called whenever a package is removed from the
565 repositories in order clean its corresponding checksum.
566 pkg_name : The name of the package to be removed
567 '''
568 checksum_dict = self._get_checksum_dict()
569 if pkg_name in checksum_dict:
570 del checksum_dict[pkg_name]
571 self._save_checksum_dict(checksum_dict)
572
573
574 def compare_checksum(self, pkg_path, repo_url):
575 '''
576 Calculate the checksum of the file specified in pkg_path and
577 compare it with the checksum in the checksum file
578 Return True if both match else return False.
579 pkg_path : The full path to the package file for which the
580 checksum is being compared
581 repo_url : The URL to fetch the checksum from
582 '''
583 checksum_dict = self._get_checksum_dict()
584 package_name = os.path.basename(pkg_path)
585 if not checksum_dict or package_name not in checksum_dict:
586 return False
587
588 repository_checksum = checksum_dict[package_name]
589 local_checksum = self.compute_checksum(pkg_path)
590 return (local_checksum == repository_checksum)
591
592
mblighdbfc4e32008-08-22 18:08:07 +0000593 def tar_package(self, pkg_name, src_dir, dest_dir, exclude_string=None):
showard9d02fb52008-08-08 18:20:37 +0000594 '''
595 Create a tar.bz2 file with the name 'pkg_name' say test-blah.tar.bz2.
mbligh9fc77972008-10-02 20:32:09 +0000596 Excludes the directories specified in exclude_string while tarring
showard9d02fb52008-08-08 18:20:37 +0000597 the source. Returns the tarball path.
598 '''
showard9d02fb52008-08-08 18:20:37 +0000599 tarball_path = os.path.join(dest_dir, pkg_name)
mbligh9fc77972008-10-02 20:32:09 +0000600 cmd = "tar -cvjf %s -C %s %s " % (tarball_path, src_dir, exclude_string)
showard9d02fb52008-08-08 18:20:37 +0000601
mbligh9fc77972008-10-02 20:32:09 +0000602 utils.system(cmd)
showard9d02fb52008-08-08 18:20:37 +0000603 return tarball_path
604
605
606 def untar_required(self, tarball_path, dest_dir):
607 '''
608 Compare the checksum of the tarball_path with the .checksum file
609 in the dest_dir and return False if it matches. The untar
610 of the package happens only if the checksums do not match.
611 '''
612 checksum_path = os.path.join(dest_dir, '.checksum')
613 try:
614 existing_checksum = self._run_command('cat ' + checksum_path).stdout
615 except (error.CmdError, error.AutoservRunError):
616 # If the .checksum file is not present (generally, this should
617 # not be the case) then return True so that the untar happens
618 return True
619
620 new_checksum = self.compute_checksum(tarball_path)
621 return (new_checksum.strip() != existing_checksum.strip())
622
623
624 def untar_pkg(self, tarball_path, dest_dir):
625 '''
626 Untar the package present in the tarball_path and put a
627 ".checksum" file in the dest_dir containing the checksum
628 of the tarball. This method
629 assumes that the package to be untarred is of the form
630 <name>.tar.bz2
631 '''
mbligh96ad8512008-10-03 03:45:26 +0000632 self._run_command('tar xjf %s -C %s' % (tarball_path, dest_dir))
showard9d02fb52008-08-08 18:20:37 +0000633 # Put the .checksum file in the install_dir to note
634 # where the package came from
635 pkg_checksum = self.compute_checksum(tarball_path)
636 pkg_checksum_path = os.path.join(dest_dir,
637 '.checksum')
638 self._run_command('echo "%s" > %s '
639 % (pkg_checksum, pkg_checksum_path))
640
641
642 def get_tarball_name(self, name, pkg_type):
643 return "%s-%s.tar.bz2" % (pkg_type, name)
644
645
646 def is_url(self, url):
647 """Return true if path looks like a URL"""
648 return url.startswith('http://')
649
650
651 def get_package_name(self, url, pkg_type):
652 '''
653 Extract the group and test name for the url. This method is currently
654 used only for tests.
655 '''
656 if pkg_type == 'test':
mblighecbaec32008-10-25 13:37:42 +0000657 regex = '[^:]+://(.*)/([^/]*)$'
showard9d02fb52008-08-08 18:20:37 +0000658 return self._get_package_name(url, regex)
659 else:
660 return ('', url)
661
662
663 def _get_package_name(self, url, regex):
664 if not self.is_url(url):
665 if url.endswith('.tar.bz2'):
666 testname = url.replace('.tar.bz2', '')
667 testname = re.sub(r'(\d*)\.', '', testname)
668 return (testname, testname)
669 else:
670 return ('', url)
671
672 match = re.match(regex, url)
673 if not match:
674 return ('', url)
675 group, filename = match.groups()
676 # Generate the group prefix.
677 group = re.sub(r'\W', '_', group)
678 # Drop the extension to get the raw test name.
679 testname = re.sub(r'\.tar\.bz2', '', filename)
680 # Drop any random numbers at the end of the test name if any
681 testname = re.sub(r'\.(\d*)', '', testname)
682 return (group, testname)
683
684
mbligha7007722009-01-13 00:37:11 +0000685SitePackageManager = utils.import_site_class(
686 __file__, "autotest_lib.client.common_lib.site_packages",
687 "SitePackageManager", BasePackageManager)
showard9d02fb52008-08-08 18:20:37 +0000688
689class PackageManager(SitePackageManager):
690 pass