/[gli]/trunk/src/GLIUtility.py
Gentoo

Contents of /trunk/src/GLIUtility.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 357 - (show annotations) (download) (as text)
Mon Mar 7 08:52:10 2005 UTC (13 years, 9 months ago) by agaffney
File MIME type: text/x-python
File size: 8749 byte(s)
switch spawn() over to using commands.getstatusoutput instead of fork/waitpid

1 """
2 Gentoo Linux Installer
3
4 Copyright 2004 Gentoo Technologies Inc.
5
6 The GLIUtility module contians all utility functions used throughout GLI.
7 """
8
9 import string, os, re, signal, time, shutil, sys, random, commands
10 from GLIException import *
11
12 def is_realstring(string_a):
13 "Check to see if a string is actually a string, and if it is not null. Returns bool."
14 # Make sure it is a string
15 if type(string_a) != str:
16 return False
17
18 # Make sure it isn't null
19 if type(string_a) == '':
20 return False
21
22 return True
23
24 def is_numeric(x):
25 try:
26 float(x)
27 except ValueError:
28 return False
29 else:
30 return True
31
32 def is_ip(ip):
33 "Check to see if a string is a valid ip. Returns bool."
34
35 # Make sure it is a string
36 if not is_realstring(ip):
37 return False
38
39 # Compile the regular expression that validates an IP. It will also check for valid ranges.
40 expr = re.compile('(([0-9]|[01]?[0-9]{2}|2([0-4][0-9]|5[0-5]))\.){3}([0-9]|[01]?[0-9]{2}|2([0-4][0-9]|5[0-5]))$')
41
42 # Run the test.
43 res = expr.match(ip)
44
45 # Return True only if there are results.
46 return(res != None)
47
48 def trim_ip(ip):
49 # Remove leading zero's on the first octet
50 ip = re.sub('^0{1,2}','',ip)
51
52 # Remove leading zero's from the other octets
53 res = re.sub('((?<=\.)(00|0)(?P<num>\d))','\g<num>',ip)
54
55 return(res)
56
57 def is_device(device):
58 "Check to see if the string passed is a valid device. Returns bool."
59
60 # Make sure it is a string
61 if not is_realstring(device):
62 return False
63
64 # Make sure the string starts with /dev/
65 if device[0:5] != '/dev/':
66 return False
67
68 # Check to make sure the device exists
69 return os.access(device, os.F_OK)
70
71 def is_hostname(hostname):
72 "Check to see if the string is a valid hostname. Returns bool."
73
74 # Make sure it is a string
75 if not is_realstring(hostname):
76 return False
77
78 expr = re.compile('^([a-zA-Z0-9-_\.])+\.[a-zA-Z]{2,4}$')
79 res = expr.match(hostname)
80
81 return(res != None)
82
83 def is_path(path):
84 "Check to see if the string is a valid path. Returns bool."
85
86 # Make sure it is a string
87 if not is_realstring(path):
88 return False
89
90 # Create a regular expression that matches all words and the symbols '-_./' _ is included in the \w
91 expr = re.compile('^[\w\.\-\/~]+$')
92
93 # Run the match
94 res = expr.match(path)
95
96 # Return True only if there are results
97 return(res != None)
98
99 def is_file(file):
100 "Check to see if the string is a valid file. Returns bool."
101
102 # Make sure it is a string
103 if not is_realstring(file):
104 return False
105
106 # Check to make sure the device exists
107 return os.access(file, os.F_OK)
108
109 def is_uri(uri):
110 "Check to see if the string is a valid URI. Returns bool."
111
112 # Make sure it is a string
113 if not is_realstring(uri):
114 return False
115
116 # Set the valid uri types
117 valid_uri_types = ( 'ftp:', 'rsync:', 'http:', 'file:', 'https:')
118
119 # Check colon and double slash location
120 colon_location = uri.find(':')
121 if not ( 6 > colon_location > 2):
122 return False
123 if uri[colon_location + 1:colon_location + 3] != "//":
124 return False
125
126 # Check for valid uri type
127 if not uri.split('/')[0] in valid_uri_types:
128 return False
129
130 # If we are dealing with a network uri...
131 if uri.split('/')[0] in ('ftp:', 'rsync:', 'http:', 'https:' ):
132
133 # Check for hostname or ip address
134 if (not is_hostname(uri.split('/')[2])) and (not is_ip(uri.split('/')[2])):
135 return False
136
137 # Check to make sure the rest is a propper path
138 if not is_path(string.join(uri.split('/')[3:], '/')):
139 return False
140
141 # If we are dealing with a local uri
142 else:
143 # Check for file validity
144 if not is_file(uri[colon_location + 3:]):
145 return False
146
147
148 return True
149
150 def strtobool(input):
151 if type(input) != str:
152 raise GLIException("InputError", 'fatal','strtobool',"The input must be a string!")
153
154 if string.lower(input) == 'true':
155 return True
156 else:
157 return False
158
159 def is_eth_device(device):
160 "Check to see if device is a valid ethernet device. Returns bool."
161
162 # Make sure it is a string
163 if not is_realstring(device):
164 return False
165
166 # Create a regular expression to test the specified device.
167 expr = re.compile('^(eth|wlan|ppp)([0-9]{1,2})(:[0-9]{1,2})?$')
168
169 # Run the match
170 res = expr.match(device)
171
172 # Return True only if there are results
173 return(res != None)
174
175 def is_nfs(device):
176 " Checks to see if device is a valid NFS device "
177
178 if not is_realstring(device):
179 return False
180
181 colon_location = device.find(':')
182
183 if colon_location == -1:
184 return False
185
186 host = device[:colon_location]
187 path = device[colon_location+1:]
188
189 return((is_ip(host) or is_hostname(host)) and is_path(path))
190
191 def set_ip(dev, ip, broadcast, netmask):
192 if not is_ip(ip) or not is_ip(netmask) or not is_ip(broadcast):
193 raise GLIException("IPAddressError", 'fatal','set_ip', "ip, netmask and broadcast must be a valid IP's!")
194
195 if not is_eth_device(dev):
196 raise GLIException("EthDeviceError", 'fatal','set_ip',"dev must be a valid ethernet device!")
197
198 options = "%s inet %s broadcast %s netmask %s" % (dev, ip, broadcast, netmask)
199
200 status = spawn("ifconfig " + options, quiet=True)
201
202 if not exitsuccess(status):
203 return False
204
205 return True
206
207 def set_default_route(route):
208 if not is_ip(route):
209 raise GLIException("IPAddressError", 'fatal', 'set_default_route', "The default route must be an IP address!")
210
211 status = spawn("route add default gw " + route, quiet=True)
212
213 if not exitsuccess(status):
214 return False
215
216 return True
217
218 def spawn(cmd, quiet=False, logfile=None, display_on_tty8=False, chroot=None, append_log=False, return_output=False):
219 # quiet and return_output really do the same thing. One of them need to be removed.
220 if chroot != None:
221 cmd = "chroot " + chroot + " " + cmd
222
223 if quiet and logfile != None:
224 cmd += " >> " + logfile + " 2>&1"
225 elif quiet and logfile == None:
226 cmd += " >/dev/null 2>&1"
227 elif logfile != None:
228 if append_log:
229 cmd += " | tee " + logfile
230 else:
231 cmd += " | tee -a " + logfile
232
233 if display_on_tty8:
234 if not is_file("/tmp/tty8_fifo"):
235 spawn("mkfifo /tmp/tty8_fifo")
236 cmd += " | tee /tmp/tty8_fifo"
237
238 ret, output = commands.getstatusoutput(cmd)
239 if return_output:
240 return ret, output
241 else:
242 return ret
243
244 def exitsuccess(status):
245 if os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0:
246 return True
247
248 return False
249
250 def spawn_bash():
251 os.putenv("PROMPT_COMMAND","echo \"Type 'exit' to return to the installer.\"")
252 return spawn("bash")
253
254 def get_uri(uri, path):
255 uri = uri.strip()
256 status = 1
257
258 if re.match('^(ftp|http(s)?)://',uri):
259 status = spawn("wget --quiet " + uri + " -O " + path)
260
261 elif re.match('^rsync://', uri):
262 status = spawn("rsync --quiet " + uri + " " + path)
263
264 elif re.match('^file://', uri):
265 file = uri[7:]
266 if os.path.isfile(file):
267 shutil.copy(file, path)
268 if os.path.isfile(path):
269 status = 0
270 else:
271 status = 1
272 else:
273 # Just in case a person forgets file://
274 if os.path.isfile(uri):
275 shutil.copy(uri, path)
276 if os.path.isfile(path):
277 status = 0
278 else:
279 status = 1
280 else:
281 print "I don't know how to download/copy that profile!"
282
283 if exitsuccess(status):
284 return True
285
286 return False
287
288 def test_network(host):
289 status = spawn("ping -c 3 " + host,quiet=True)
290
291 if not exitsuccess(status):
292 return False
293
294 return True
295
296 def fetch_and_unpack_tarball(tarball_uri, target_directory, temp_directory="/tmp", keep_permissions=False):
297 "Fetches a tarball from tarball_uri and extracts it into target_directory"
298
299 # Get tarball info
300 tarball_filename = tarball_uri.split("/")[-1]
301
302 # Get the tarball
303 get_uri(tarball_uri, temp_directory + "/" + tarball_filename)
304
305 # Reset tar options
306 tar_options = "xv"
307
308 # If the tarball is bzip'd
309 if tarball_filename.split(".")[-1] == "tbz" or tarball_filename.split(".")[-1] == "bz2":
310 tar_options = tar_options + "j"
311
312 # If the tarball is gzip'd
313 elif tarball_filename.split(".")[-1] == "tgz" or tarball_filename.split(".")[-1] == "gz":
314 tar_options = tar_options + "z"
315
316 # If we want to keep permissions
317 if keep_permissions:
318 tar_options = tar_options + "p"
319
320 # Unpack the tarball
321 exitstatus = spawn("tar -" + tar_options + " -f " + temp_directory + "/" + tarball_filename + " -C " + target_directory, display_on_tty8=True)
322
323 if not exitsuccess(exitstatus):
324 raise GLIException("UnpackTarballError", 'fatal', 'fetch_and_unpack_tarball',"Could not unpack tarball!")
325
326
327 def generate_random_password():
328 s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890$%^&*[]{}-=+_,|'\"<>:/"
329 s = list(s)
330
331 for i in range(0,len(s)/2):
332 x = random.randint(0,len(s)-1)
333 y = random.randint(0,len(s)-1)
334 tmp = s[x]
335 s[x] = s[y]
336 s[y] = tmp
337
338 passwd = ""
339 for i in range(0,random.randint(8,12)):
340 passwd += s[i]
341
342 return passwd
343
344 def get_value_from_config(filename, value):
345 return string.strip(commands.getoutput("source " + filename + " && echo $" + value))

Properties

Name Value
svn:eol-style native

  ViewVC Help
Powered by ViewVC 1.1.20