Package pulp :: Package client :: Module utils
[hide private]
[frames] | no frames]

Source Code for Module pulp.client.utils

  1  #!/usr/bin/python 
  2  # 
  3  # Copyright (c) 2010 Red Hat, Inc. 
  4  # 
  5  # This software is licensed to you under the GNU General Public License, 
  6  # version 2 (GPLv2). There is NO WARRANTY for this software, express or 
  7  # implied, including the implied warranties of MERCHANTABILITY or FITNESS 
  8  # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 
  9  # along with this software; if not, see 
 10  # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. 
 11  # 
 12  # Red Hat trademarks are not licensed under GPLv2. No permission is 
 13  # granted to use or replicate Red Hat trademarks that are incorporated 
 14  # in this software or its documentation. 
 15  # 
 16  import os 
 17  import rpm 
 18  import socket 
 19  import hashlib 
 20  import base64 
 21  import yum.packages as yumPackages 
 22   
 23  PGPHASHALGO = { 
 24    1: 'md5', 
 25    2: 'sha1', 
 26    3: 'ripemd160', 
 27    5: 'md2', 
 28    6: 'tiger192', 
 29    7: 'haval-5-160', 
 30    8: 'sha256', 
 31    9: 'sha384', 
 32   10: 'sha512', 
 33  } 
 34  # need this for rpm-pyhon < 4.6 (e.g. on RHEL5) 
 35  rpm.RPMTAG_FILEDIGESTALGO = 5011 
 36   
 37   
38 -def findSysvArgs(args):
39 """ 40 Find the arguments passed in from the CLI, skipping any --option=value and 41 any -o value options. We don't want to treat the 'value' in '-o value' as 42 an argument and must skip these 43 """ 44 # Find the actual arguments to the command, skipping options 45 foundargs = [] 46 skipArg = False 47 for arg in args: 48 # Only add it if the arg doesnt start with a - or the previous 49 # argument didnt start with -. need to track previous arg for 50 # cases where users use -u username -p password somecommand 51 # if (not arg.startswith("-") and not prevarg.startswith("-")): 52 if (skipArg): 53 skipArg = False 54 continue 55 if (arg.startswith("-") and not arg.startswith("--")): 56 skipArg = True 57 elif (not arg.startswith("--")): 58 foundargs.append(arg) 59 60 return foundargs
61 62
63 -def getVersionRelease():
64 ts = rpm.TransactionSet() 65 for h in ts.dbMatch('Providename', "redhat-release"): 66 version = h['version'] 67 versionRelease = (h['name'], version, h['release']) 68 return versionRelease
69
70 -def getArch():
71 arch = os.uname()[4] 72 replace = {"i686": "i386"} 73 if replace.has_key(arch): 74 arch = replace[arch] 75 return arch
76
77 -def getHostname():
78 return socket.gethostname()
79
80 -def getFQDN():
81 return socket.getfqdn()
82
83 -def writeToFile(filename, message, overwrite=True):
84 dir_name = os.path.dirname(filename) 85 if not os.access(dir_name, os.W_OK): 86 os.mkdir(dir_name) 87 if os.access(filename, os.F_OK) and not overwrite: 88 # already have file there; let's back it up 89 try: 90 os.rename(filename, filename + '.save') 91 except: 92 return False 93 94 os.open(filename, os.O_WRONLY | os.O_CREAT, 0644) 95 msgFile = open(filename, 'w') 96 try: 97 msgFile.write(message) 98 finally: 99 msgFile.close() 100 101 return True
102
103 -def listdir(directory):
104 directory = os.path.abspath(os.path.normpath(directory)) 105 if not os.access(directory, os.R_OK | os.X_OK): 106 raise Exception("Cannot read from directory %s" % directory) 107 if not os.path.isdir(directory): 108 raise Exception("%s not a directory" % directory) 109 # Build the package list 110 packagesList = [] 111 for f in os.listdir(directory): 112 packagesList.append("%s/%s" % (directory, f)) 113 return packagesList
114
115 -def processDirectory(dirpath, ftype):
116 dirfiles = [] 117 for file in listdir(dirpath): 118 # only add packages 119 if file[-3:] in ftype: 120 dirfiles.append(file) 121 return dirfiles
122
123 -def getFileChecksum(hashtype, filename=None, fd=None, file=None, buffer_size=None):
124 """ Compute a file's checksum 125 """ 126 if hashtype in ['sha', 'SHA']: 127 hashtype = 'sha1' 128 129 if buffer_size is None: 130 buffer_size = 65536 131 132 if filename is None and fd is None and file is None: 133 raise ValueError("no file specified") 134 if file: 135 f = file 136 elif fd is not None: 137 f = os.fdopen(os.dup(fd), "r") 138 else: 139 f = open(filename, "r") 140 # Rewind it 141 f.seek(0, 0) 142 m = hashlib.new(hashtype) 143 while 1: 144 buffer = f.read(buffer_size) 145 if not buffer: 146 break 147 m.update(buffer) 148 149 # cleanup time 150 if file is not None: 151 file.seek(0, 0) 152 else: 153 f.close() 154 return m.hexdigest()
155 156
157 -class FileError(Exception):
158 pass
159
160 -def processRPM(filename, relativeDir=None, source=None):
161 # Is this a file? 162 if not os.access(filename, os.R_OK): 163 raise FileError("Could not stat the file %s" % filename) 164 if not os.path.isfile(filename): 165 raise FileError("%s is not a file" % filename) 166 167 # Size 168 size = os.path.getsize(filename) 169 hash = {'size' : size} 170 if relativeDir: 171 # Append the relative dir too 172 hash["relativePath"] = "%s/%s" % (relativeDir, 173 os.path.basename(filename)) 174 175 # Read the header 176 try: 177 ts = rpm.TransactionSet() 178 ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES) 179 h = readRpmHeader(ts, filename) 180 except: 181 return hash 182 183 # Get the name, version, release, epoch, arch 184 lh = [] 185 for k in ['name', 'version', 'release', 'epoch']: 186 lh.append(h[k]) 187 # Fix the epoch 188 if lh[3] is None: 189 lh[3] = "" 190 else: 191 lh[3] = str(lh[3]) 192 193 if source: 194 lh.append('src') 195 else: 196 lh.append(h['arch']) 197 198 hash['nvrea'] = tuple(lh) 199 hash['hashtype'] = getChecksumType(h) 200 hash['checksum'] = getFileChecksum(hash['hashtype'], filename=filename) 201 hash['pkgname'] = os.path.basename(filename) 202 return hash
203
204 -def getChecksumType(header):
205 if header[rpm.RPMTAG_FILEDIGESTALGO] \ 206 and PGPHASHALGO.has_key(header[rpm.RPMTAG_FILEDIGESTALGO]): 207 checksum_type = PGPHASHALGO[header[rpm.RPMTAG_FILEDIGESTALGO]] 208 else: 209 checksum_type = 'md5' 210 return checksum_type
211
212 -def readRpmHeader(ts, rpmname):
213 fd = os.open(rpmname, os.O_RDONLY) 214 h = ts.hdrFromFdno(fd) 215 os.close(fd) 216 return h
217
218 -def generatePkgMetadata(pkgFile):
219 ts = rpm.TransactionSet() 220 yumPkg = yumPackages.YumLocalPackage(ts, filename=pkgFile) 221 primary_xml = yumPkg.xml_dump_primary_metadata() 222 return base64.b64encode(primary_xml)
223
224 -def generatePakageProfile(rpmHeaderList):
225 """ Accumulates list of installed rpm info """ 226 227 pkgList = [] 228 for h in rpmHeaderList: 229 if h['name'] == "gpg-pubkey": 230 #dbMatch includes imported gpg keys as well 231 # skip these for now as there isnt compelling 232 # reason for server to know this info 233 continue 234 info = { 235 'name' : h['name'], 236 'version' : h['version'], 237 'release' : h['release'], 238 'epoch' : h['epoch'] or 0, 239 'arch' : h['arch'], 240 'vendor' : h['vendor'] or None, 241 } 242 pkgList.append(info) 243 return pkgList
244
245 -def getRpmName(pkg):
246 return pkg["name"] + "-" + pkg["version"] + "-" + \ 247 pkg["release"] + "." + pkg["arch"]
248
249 -def readFile(filepath):
250 # Is this a file? 251 if not os.access(filepath, os.R_OK): 252 raise FileError("Could not stat the file %s" % filepath) 253 if not os.path.isfile(filepath): 254 raise FileError("%s is not a file" % filepath) 255 256 try: 257 f = open(filepath) 258 return f.read() 259 except: 260 return None
261