Merge lp:~eday/nova/pep8-fixes-api into lp:~hudson-openstack/nova/trunk

Proposed by Eric Day
Status: Merged
Approved by: Eric Day
Approved revision: 377
Merged at revision: 377
Proposed branch: lp:~eday/nova/pep8-fixes-api
Merge into: lp:~hudson-openstack/nova/trunk
Prerequisite: lp:~eday/nova/pep8-fixes
Diff against target: 933 lines (+135/-133)
16 files modified
nova/api/__init__.py (+7/-8)
nova/api/ec2/__init__.py (+8/-5)
nova/api/ec2/admin.py (+6/-5)
nova/api/ec2/apirequest.py (+5/-3)
nova/api/ec2/cloud.py (+46/-61)
nova/api/ec2/images.py (+5/-1)
nova/api/ec2/metadatarequesthandler.py (+4/-3)
nova/api/openstack/__init__.py (+17/-14)
nova/api/openstack/auth.py (+5/-4)
nova/api/openstack/backup_schedules.py (+1/-0)
nova/api/openstack/faults.py (+1/-1)
nova/api/openstack/flavors.py (+2/-4)
nova/api/openstack/images.py (+4/-6)
nova/api/openstack/ratelimiting/__init__.py (+6/-3)
nova/api/openstack/servers.py (+15/-14)
nova/api/openstack/sharedipgroups.py (+3/-1)
To merge this branch: bzr merge lp:~eday/nova/pep8-fixes-api
Reviewer Review Type Date Requested Status
Jay Pipes (community) Approve
Vish Ishaya (community) Approve
Review via email: mp+39107@code.launchpad.net

Description of the change

Another pep8 cleanup branch for nova/api, should be merged after lp:~eday/nova/pep8-fixes.

To post a comment you must log in.
Revision history for this message
Vish Ishaya (vishvananda) wrote :

lgtm

review: Approve
Revision history for this message
Jay Pipes (jaypipes) wrote :

yup, lgtm.

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'nova/api/__init__.py'
2--- nova/api/__init__.py 2010-10-11 15:43:58 +0000
3+++ nova/api/__init__.py 2010-10-21 22:29:46 +0000
4@@ -31,12 +31,13 @@
5 from nova.api.ec2 import metadatarequesthandler
6
7
8-flags.DEFINE_string('osapi_subdomain', 'api',
9+flags.DEFINE_string('osapi_subdomain', 'api',
10 'subdomain running the OpenStack API')
11-flags.DEFINE_string('ec2api_subdomain', 'ec2',
12+flags.DEFINE_string('ec2api_subdomain', 'ec2',
13 'subdomain running the EC2 API')
14-flags.DEFINE_string('FAKE_subdomain', None,
15- 'set to api or ec2 to fake the subdomain of the host for testing')
16+flags.DEFINE_string('FAKE_subdomain', None,
17+ 'set to api or ec2 to fake the subdomain of the host '
18+ 'for testing')
19 FLAGS = flags.FLAGS
20
21
22@@ -44,7 +45,7 @@
23 """Routes top-level requests to the appropriate controller."""
24
25 def __init__(self):
26- osapidomain = {'sub_domain': [FLAGS.osapi_subdomain]}
27+ osapidomain = {'sub_domain': [FLAGS.osapi_subdomain]}
28 ec2domain = {'sub_domain': [FLAGS.ec2api_subdomain]}
29 # If someone wants to pretend they're hitting the OSAPI subdomain
30 # on their local box, they can set FAKE_subdomain to 'api', which
31@@ -55,7 +56,7 @@
32 ec2domain = {}
33 mapper = routes.Mapper()
34 mapper.sub_domains = True
35- mapper.connect("/", controller=self.osapi_versions,
36+ mapper.connect("/", controller=self.osapi_versions,
37 conditions=osapidomain)
38 mapper.connect("/v1.0/{path_info:.*}", controller=openstack.API(),
39 conditions=osapidomain)
40@@ -107,5 +108,3 @@
41 '2009-04-04',
42 ]
43 return ''.join('%s\n' % v for v in versions)
44-
45-
46
47=== modified file 'nova/api/ec2/__init__.py'
48--- nova/api/ec2/__init__.py 2010-10-14 04:42:10 +0000
49+++ nova/api/ec2/__init__.py 2010-10-21 22:29:46 +0000
50@@ -62,7 +62,8 @@
51
52 # Make a copy of args for authentication and signature verification.
53 auth_params = dict(req.params)
54- auth_params.pop('Signature') # not part of authentication args
55+ # Not part of authentication args
56+ auth_params.pop('Signature')
57
58 # Authenticate the request.
59 try:
60@@ -109,9 +110,11 @@
61 'SignatureVersion', 'Version', 'Timestamp']
62 args = dict(req.params)
63 try:
64- action = req.params['Action'] # raise KeyError if omitted
65+ # Raise KeyError if omitted
66+ action = req.params['Action']
67 for non_arg in non_args:
68- args.pop(non_arg) # remove, but raise KeyError if omitted
69+ # Remove, but raise KeyError if omitted
70+ args.pop(non_arg)
71 except:
72 raise webob.exc.HTTPBadRequest()
73
74@@ -184,7 +187,8 @@
75 context = req.environ['ec2.context']
76 controller_name = req.environ['ec2.controller'].__class__.__name__
77 action = req.environ['ec2.action']
78- allowed_roles = self.action_roles[controller_name].get(action, ['none'])
79+ allowed_roles = self.action_roles[controller_name].get(action,
80+ ['none'])
81 if self._matches_any_role(context, allowed_roles):
82 return self.application
83 else:
84@@ -242,4 +246,3 @@
85 '<Message>%s</Message></Error></Errors>'
86 '<RequestID>?</RequestID></Response>') % (code, message)
87 return resp
88-
89
90=== modified file 'nova/api/ec2/admin.py'
91--- nova/api/ec2/admin.py 2010-09-16 15:33:42 +0000
92+++ nova/api/ec2/admin.py 2010-10-21 22:29:46 +0000
93@@ -73,7 +73,7 @@
94 def describe_users(self, _context, **_kwargs):
95 """Returns all users - should be changed to deal with a list."""
96 return {'userSet':
97- [user_dict(u) for u in manager.AuthManager().get_users()] }
98+ [user_dict(u) for u in manager.AuthManager().get_users()]}
99
100 def register_user(self, _context, name, **_kwargs):
101 """Creates a new user, and returns generated credentials."""
102@@ -91,7 +91,7 @@
103 def describe_roles(self, context, project_roles=True, **kwargs):
104 """Returns a list of allowed roles."""
105 roles = manager.AuthManager().get_roles(project_roles)
106- return { 'roles': [{'role': r} for r in roles]}
107+ return {'roles': [{'role': r} for r in roles]}
108
109 def describe_user_roles(self, context, user, project=None, **kwargs):
110 """Returns a list of roles for the given user.
111@@ -99,7 +99,7 @@
112 Specifying project will return only project specific roles.
113 """
114 roles = manager.AuthManager().get_user_roles(user, project=project)
115- return { 'roles': [{'role': r} for r in roles]}
116+ return {'roles': [{'role': r} for r in roles]}
117
118 def modify_user_role(self, context, user, role, project=None,
119 operation='add', **kwargs):
120@@ -155,9 +155,10 @@
121 'members': [{'member': m} for m in project.member_ids]}
122 return result
123
124- def modify_project_member(self, context, user, project, operation, **kwargs):
125+ def modify_project_member(self, context, user, project, operation,
126+ **kwargs):
127 """Add or remove a user from a project."""
128- if operation =='add':
129+ if operation == 'add':
130 manager.AuthManager().add_to_project(user, project)
131 elif operation == 'remove':
132 manager.AuthManager().remove_from_project(user, project)
133
134=== modified file 'nova/api/ec2/apirequest.py'
135--- nova/api/ec2/apirequest.py 2010-10-14 08:11:18 +0000
136+++ nova/api/ec2/apirequest.py 2010-10-21 22:29:46 +0000
137@@ -44,6 +44,7 @@
138 res = _underscore_to_camelcase(str)
139 return res[:1].lower() + res[1:]
140
141+
142 def _try_convert(value):
143 """Return a non-string if possible"""
144 if value == 'None':
145@@ -59,12 +60,12 @@
146 return value
147 if valueneg[0] == '0':
148 if valueneg[1] in 'xX':
149- return int(value,16)
150+ return int(value, 16)
151 elif valueneg[1] in 'bB':
152- return int(value,2)
153+ return int(value, 2)
154 else:
155 try:
156- return int(value,8)
157+ return int(value, 8)
158 except ValueError:
159 pass
160 try:
161@@ -80,6 +81,7 @@
162 except ValueError:
163 return value
164
165+
166 class APIRequest(object):
167 def __init__(self, controller, action):
168 self.controller = controller
169
170=== modified file 'nova/api/ec2/cloud.py'
171--- nova/api/ec2/cloud.py 2010-10-14 06:26:58 +0000
172+++ nova/api/ec2/cloud.py 2010-10-21 22:29:46 +0000
173@@ -48,6 +48,7 @@
174
175 InvalidInputException = exception.InvalidInputException
176
177+
178 class QuotaError(exception.ApiError):
179 """Quota Exceeeded"""
180 pass
181@@ -137,8 +138,8 @@
182 for node in nodes:
183 rpc.cast(context,
184 '%s.%s' % (FLAGS.compute_topic, node),
185- { "method": "refresh_security_group",
186- "args": {"security_group_id": security_group.id}})
187+ {"method": "refresh_security_group",
188+ "args": {"security_group_id": security_group.id}})
189
190 def get_metadata(self, address):
191 ctxt = context.get_admin_context()
192@@ -147,48 +148,42 @@
193 return None
194 mpi = self._get_mpi_data(ctxt, instance_ref['project_id'])
195 if instance_ref['key_name']:
196- keys = {
197- '0': {
198- '_name': instance_ref['key_name'],
199- 'openssh-key': instance_ref['key_data']
200- }
201- }
202+ keys = {'0': {'_name': instance_ref['key_name'],
203+ 'openssh-key': instance_ref['key_data']}}
204 else:
205 keys = ''
206 hostname = instance_ref['hostname']
207 floating_ip = db.instance_get_floating_address(ctxt,
208 instance_ref['id'])
209+ ec2_id = internal_id_to_ec2_id(instance_ref['internal_id'])
210 data = {
211 'user-data': base64.b64decode(instance_ref['user_data']),
212 'meta-data': {
213 'ami-id': instance_ref['image_id'],
214 'ami-launch-index': instance_ref['launch_index'],
215 'ami-manifest-path': 'FIXME',
216- 'block-device-mapping': { # TODO(vish): replace with real data
217+ 'block-device-mapping': {
218+ # TODO(vish): replace with real data
219 'ami': 'sda1',
220 'ephemeral0': 'sda2',
221 'root': '/dev/sda1',
222- 'swap': 'sda3'
223- },
224+ 'swap': 'sda3'},
225 'hostname': hostname,
226 'instance-action': 'none',
227- 'instance-id': internal_id_to_ec2_id(instance_ref['internal_id']),
228+ 'instance-id': ec2_id,
229 'instance-type': instance_ref['instance_type'],
230 'local-hostname': hostname,
231 'local-ipv4': address,
232 'kernel-id': instance_ref['kernel_id'],
233- 'placement': {
234- 'availability-zone': 'nova' # TODO(vish): real zone
235- },
236+ # TODO(vish): real zone
237+ 'placement': {'availability-zone': 'nova'},
238 'public-hostname': hostname,
239 'public-ipv4': floating_ip or '',
240 'public-keys': keys,
241 'ramdisk-id': instance_ref['ramdisk_id'],
242 'reservation-id': instance_ref['reservation_id'],
243 'security-groups': '',
244- 'mpi': mpi
245- }
246- }
247+ 'mpi': mpi}}
248 if False: # TODO(vish): store ancestor ids
249 data['ancestor-ami-ids'] = []
250 if False: # TODO(vish): store product codes
251@@ -211,7 +206,7 @@
252 'regionEndpoint': FLAGS.ec2_url}]
253 if region_name:
254 regions = [r for r in regions if r['regionName'] in region_name]
255- return {'regionInfo': regions }
256+ return {'regionInfo': regions}
257
258 def describe_snapshots(self,
259 context,
260@@ -237,7 +232,8 @@
261 for key_pair in key_pairs:
262 # filter out the vpn keys
263 suffix = FLAGS.vpn_key_suffix
264- if context.user.is_admin() or not key_pair['name'].endswith(suffix):
265+ if context.user.is_admin() or \
266+ not key_pair['name'].endswith(suffix):
267 result.append({
268 'keyName': key_pair['name'],
269 'keyFingerprint': key_pair['fingerprint'],
270@@ -271,7 +267,7 @@
271 if not group_name is None:
272 groups = [g for g in groups if g.name in group_name]
273
274- return {'securityGroupInfo': groups }
275+ return {'securityGroupInfo': groups}
276
277 def _format_security_group(self, context, group):
278 g = {}
279@@ -295,13 +291,10 @@
280 g['ipPermissions'] += [r]
281 return g
282
283-
284- def _authorize_revoke_rule_args_to_dict(self, context,
285- to_port=None, from_port=None,
286- ip_protocol=None, cidr_ip=None,
287- user_id=None,
288- source_security_group_name=None,
289- source_security_group_owner_id=None):
290+ def _revoke_rule_args_to_dict(self, context, to_port=None, from_port=None,
291+ ip_protocol=None, cidr_ip=None, user_id=None,
292+ source_security_group_name=None,
293+ source_security_group_owner_id=None):
294
295 values = {}
296
297@@ -322,16 +315,16 @@
298 values['cidr'] = '0.0.0.0/0'
299
300 if ip_protocol and from_port and to_port:
301- from_port = int(from_port)
302- to_port = int(to_port)
303+ from_port = int(from_port)
304+ to_port = int(to_port)
305 ip_protocol = str(ip_protocol)
306
307- if ip_protocol.upper() not in ['TCP','UDP','ICMP']:
308- raise InvalidInputException('%s is not a valid ipProtocol' %
309- (ip_protocol,))
310+ if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']:
311+ raise InvalidInputException('%s is not a valid ipProtocol' %
312+ (ip_protocol,))
313 if ((min(from_port, to_port) < -1) or
314 (max(from_port, to_port) > 65535)):
315- raise InvalidInputException('Invalid port range')
316+ raise InvalidInputException('Invalid port range')
317
318 values['protocol'] = ip_protocol
319 values['from_port'] = from_port
320@@ -343,7 +336,6 @@
321
322 return values
323
324-
325 def _security_group_rule_exists(self, security_group, values):
326 """Indicates whether the specified rule values are already
327 defined in the given security group.
328@@ -362,20 +354,19 @@
329 return True
330 return False
331
332-
333 def revoke_security_group_ingress(self, context, group_name, **kwargs):
334 self._ensure_default_security_group(context)
335 security_group = db.security_group_get_by_name(context,
336 context.project_id,
337 group_name)
338
339- criteria = self._authorize_revoke_rule_args_to_dict(context, **kwargs)
340+ criteria = self._revoke_rule_args_to_dict(context, **kwargs)
341 if criteria == None:
342 raise exception.ApiError("No rule for the specified parameters.")
343
344 for rule in security_group.rules:
345 match = True
346- for (k,v) in criteria.iteritems():
347+ for (k, v) in criteria.iteritems():
348 if getattr(rule, k, False) != v:
349 match = False
350 if match:
351@@ -394,7 +385,7 @@
352 context.project_id,
353 group_name)
354
355- values = self._authorize_revoke_rule_args_to_dict(context, **kwargs)
356+ values = self._revoke_rule_args_to_dict(context, **kwargs)
357 values['parent_group_id'] = security_group.id
358
359 if self._security_group_rule_exists(security_group, values):
360@@ -407,7 +398,6 @@
361
362 return True
363
364-
365 def _get_source_project_id(self, context, source_security_group_owner_id):
366 if source_security_group_owner_id:
367 # Parse user:project for source group.
368@@ -425,13 +415,12 @@
369
370 return source_project_id
371
372-
373 def create_security_group(self, context, group_name, group_description):
374 self._ensure_default_security_group(context)
375 if db.security_group_exists(context, context.project_id, group_name):
376 raise exception.ApiError('group %s already exists' % group_name)
377
378- group = {'user_id' : context.user.id,
379+ group = {'user_id': context.user.id,
380 'project_id': context.project_id,
381 'name': group_name,
382 'description': group_description}
383@@ -440,7 +429,6 @@
384 return {'securityGroupSet': [self._format_security_group(context,
385 group_ref)]}
386
387-
388 def delete_security_group(self, context, group_name, **kwargs):
389 security_group = db.security_group_get_by_name(context,
390 context.project_id,
391@@ -448,7 +436,6 @@
392 db.security_group_destroy(context, security_group.id)
393 return True
394
395-
396 def get_console_output(self, context, instance_id, **kwargs):
397 # instance_id is passed in as a list of instances
398 ec2_id = instance_id[0]
399@@ -457,13 +444,13 @@
400 output = rpc.call(context,
401 '%s.%s' % (FLAGS.compute_topic,
402 instance_ref['host']),
403- {"method" : "get_console_output",
404- "args" : {"instance_id": instance_ref['id']}})
405+ {"method": "get_console_output",
406+ "args": {"instance_id": instance_ref['id']}})
407
408 now = datetime.datetime.utcnow()
409- return { "InstanceId" : ec2_id,
410- "Timestamp" : now,
411- "output" : base64.b64encode(output) }
412+ return {"InstanceId": ec2_id,
413+ "Timestamp": now,
414+ "output": base64.b64encode(output)}
415
416 def describe_volumes(self, context, **kwargs):
417 if context.user.is_admin():
418@@ -530,7 +517,6 @@
419
420 return {'volumeSet': [self._format_volume(context, volume_ref)]}
421
422-
423 def attach_volume(self, context, volume_id, instance_id, device, **kwargs):
424 volume_ref = db.volume_get_by_ec2_id(context, volume_id)
425 # TODO(vish): abstract status checking?
426@@ -633,8 +619,7 @@
427 i['imageId'] = instance['image_id']
428 i['instanceState'] = {
429 'code': instance['state'],
430- 'name': instance['state_description']
431- }
432+ 'name': instance['state_description']}
433 fixed_addr = None
434 floating_addr = None
435 if instance['fixed_ip']:
436@@ -656,7 +641,7 @@
437 i['amiLaunchIndex'] = instance['launch_index']
438 i['displayName'] = instance['display_name']
439 i['displayDescription'] = instance['display_description']
440- if not reservations.has_key(instance['reservation_id']):
441+ if instance['reservation_id'] not in reservations:
442 r = {}
443 r['reservationId'] = instance['reservation_id']
444 r['ownerId'] = instance['project_id']
445@@ -757,10 +742,10 @@
446 context.project_id,
447 'default')
448 except exception.NotFound:
449- values = { 'name' : 'default',
450- 'description' : 'default',
451- 'user_id' : context.user.id,
452- 'project_id' : context.project_id }
453+ values = {'name': 'default',
454+ 'description': 'default',
455+ 'user_id': context.user.id,
456+ 'project_id': context.project_id}
457 group = db.security_group_create(context, values)
458
459 def run_instances(self, context, **kwargs):
460@@ -804,7 +789,7 @@
461 logging.debug("Going to run %s instances...", num_instances)
462 launch_time = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
463 key_data = None
464- if kwargs.has_key('key_name'):
465+ if 'key_name' in kwargs:
466 key_pair_ref = db.key_pair_get(context,
467 context.user.id,
468 kwargs['key_name'])
469@@ -883,7 +868,6 @@
470 (context.project.name, context.user.name, inst_id))
471 return self._format_run_instances(context, reservation_id)
472
473-
474 def terminate_instances(self, context, instance_id, **kwargs):
475 """Terminate each instance in instance_id, which is a list of ec2 ids.
476
477@@ -991,7 +975,7 @@
478
479 def register_image(self, context, image_location=None, **kwargs):
480 # FIXME: should the objectstore be doing these authorization checks?
481- if image_location is None and kwargs.has_key('name'):
482+ if image_location is None and 'name' in kwargs:
483 image_location = kwargs['name']
484 image_id = images.register(context, image_location)
485 logging.debug("Registered %s as %s" % (image_location, image_id))
486@@ -1009,7 +993,8 @@
487 result['launchPermission'].append({'group': 'all'})
488 return result
489
490- def modify_image_attribute(self, context, image_id, attribute, operation_type, **kwargs):
491+ def modify_image_attribute(self, context, image_id, attribute,
492+ operation_type, **kwargs):
493 # TODO(devcamcar): Support users and groups other than 'all'.
494 if attribute != 'launchPermission':
495 raise exception.ApiError('attribute not supported: %s' % attribute)
496
497=== modified file 'nova/api/ec2/images.py'
498--- nova/api/ec2/images.py 2010-10-12 20:52:10 +0000
499+++ nova/api/ec2/images.py 2010-10-21 22:29:46 +0000
500@@ -43,6 +43,7 @@
501
502 return True
503
504+
505 def update(context, image_id, attributes):
506 """update an image's attributes / info.json"""
507 attributes.update({"image_id": image_id})
508@@ -52,6 +53,7 @@
509 query_args=qs(attributes))
510 return True
511
512+
513 def register(context, image_location):
514 """ rpc call to register a new image based from a manifest """
515
516@@ -64,13 +66,14 @@
517
518 return image_id
519
520+
521 def list(context, filter_list=[]):
522 """ return a list of all images that a user can see
523
524 optionally filtered by a list of image_id """
525
526 if FLAGS.connection_type == 'fake':
527- return [{ 'imageId' : 'bar'}]
528+ return [{'imageId': 'bar'}]
529
530 # FIXME: send along the list of only_images to check for
531 response = conn(context).make_request(
532@@ -82,6 +85,7 @@
533 return [i for i in result if i['imageId'] in filter_list]
534 return result
535
536+
537 def get(context, image_id):
538 """return a image object if the context has permissions"""
539 result = list(context, [image_id])
540
541=== modified file 'nova/api/ec2/metadatarequesthandler.py'
542--- nova/api/ec2/metadatarequesthandler.py 2010-09-23 20:18:40 +0000
543+++ nova/api/ec2/metadatarequesthandler.py 2010-10-21 22:29:46 +0000
544@@ -27,7 +27,6 @@
545
546
547 class MetadataRequestHandler(object):
548-
549 """Serve metadata from the EC2 API."""
550
551 def print_data(self, data):
552@@ -43,7 +42,8 @@
553 else:
554 output += '/'
555 output += '\n'
556- return output[:-1] # cut off last \n
557+ # Cut off last \n
558+ return output[:-1]
559 elif isinstance(data, list):
560 return '\n'.join(data)
561 else:
562@@ -65,7 +65,8 @@
563 cc = cloud.CloudController()
564 meta_data = cc.get_metadata(req.remote_addr)
565 if meta_data is None:
566- logging.error('Failed to get metadata for ip: %s' % req.remote_addr)
567+ logging.error('Failed to get metadata for ip: %s' %
568+ req.remote_addr)
569 raise webob.exc.HTTPNotFound()
570 data = self.lookup(req.path_info, meta_data)
571 if data is None:
572
573=== modified file 'nova/api/openstack/__init__.py'
574--- nova/api/openstack/__init__.py 2010-10-15 01:17:56 +0000
575+++ nova/api/openstack/__init__.py 2010-10-21 22:29:46 +0000
576@@ -43,9 +43,10 @@
577
578 FLAGS = flags.FLAGS
579 flags.DEFINE_string('nova_api_auth',
580- 'nova.api.openstack.auth.BasicApiAuthManager',
581+ 'nova.api.openstack.auth.BasicApiAuthManager',
582 'The auth mechanism to use for the OpenStack API implemenation')
583
584+
585 class API(wsgi.Middleware):
586 """WSGI entry point for all OpenStack API requests."""
587
588@@ -53,6 +54,7 @@
589 app = AuthMiddleware(RateLimitingMiddleware(APIRouter()))
590 super(API, self).__init__(app)
591
592+
593 class AuthMiddleware(wsgi.Middleware):
594 """Authorize the openstack API request or return an HTTP Forbidden."""
595
596@@ -62,7 +64,7 @@
597
598 @webob.dec.wsgify
599 def __call__(self, req):
600- if not req.headers.has_key("X-Auth-Token"):
601+ if 'X-Auth-Token' not in req.headers:
602 return self.auth_driver.authenticate(req)
603
604 user = self.auth_driver.authorize_token(req.headers["X-Auth-Token"])
605@@ -70,11 +72,12 @@
606 if not user:
607 return faults.Fault(webob.exc.HTTPUnauthorized())
608
609- if not req.environ.has_key('nova.context'):
610+ if 'nova.context' not in req.environ:
611 req.environ['nova.context'] = {}
612 req.environ['nova.context']['user'] = user
613 return self.application
614
615+
616 class RateLimitingMiddleware(wsgi.Middleware):
617 """Rate limit incoming requests according to the OpenStack rate limits."""
618
619@@ -87,7 +90,7 @@
620 """
621 super(RateLimitingMiddleware, self).__init__(application)
622 if not service_host:
623- #TODO(gundlach): These limits were based on limitations of Cloud
624+ #TODO(gundlach): These limits were based on limitations of Cloud
625 #Servers. We should revisit them in Nova.
626 self.limiter = ratelimiting.Limiter(limits={
627 'DELETE': (100, ratelimiting.PER_MINUTE),
628@@ -102,13 +105,14 @@
629 @webob.dec.wsgify
630 def __call__(self, req):
631 """Rate limit the request.
632-
633- If the request should be rate limited, return a 413 status with a
634+
635+ If the request should be rate limited, return a 413 status with a
636 Retry-After header giving the time when the request would succeed.
637 """
638 user_id = req.environ['nova.context']['user']['id']
639 action_name = self.get_action_name(req)
640- if not action_name: # not rate limited
641+ if not action_name:
642+ # Not rate limited
643 return self.application
644 delay = self.get_delay(action_name, user_id)
645 if delay:
646@@ -152,13 +156,13 @@
647 def __init__(self):
648 mapper = routes.Mapper()
649 mapper.resource("server", "servers", controller=servers.Controller(),
650- collection={ 'detail': 'GET'},
651- member={'action':'POST'})
652+ collection={'detail': 'GET'},
653+ member={'action': 'POST'})
654
655- mapper.resource("backup_schedule", "backup_schedules",
656+ mapper.resource("backup_schedule", "backup_schedules",
657 controller=backup_schedules.Controller(),
658- parent_resource=dict(member_name='server',
659- collection_name = 'servers'))
660+ parent_resource=dict(member_name='server',
661+ collection_name='servers'))
662
663 mapper.resource("image", "images", controller=images.Controller(),
664 collection={'detail': 'GET'})
665@@ -172,7 +176,7 @@
666
667 def limited(items, req):
668 """Return a slice of items according to requested offset and limit.
669-
670+
671 items - a sliceable
672 req - wobob.Request possibly containing offset and limit GET variables.
673 offset is where to start in the list, and limit is the maximum number
674@@ -187,4 +191,3 @@
675 limit = min(1000, limit)
676 range_end = offset + limit
677 return items[offset:range_end]
678-
679
680=== modified file 'nova/api/openstack/auth.py'
681--- nova/api/openstack/auth.py 2010-10-13 20:36:05 +0000
682+++ nova/api/openstack/auth.py 2010-10-21 22:29:46 +0000
683@@ -15,9 +15,11 @@
684
685 FLAGS = flags.FLAGS
686
687+
688 class Context(object):
689 pass
690
691+
692 class BasicApiAuthManager(object):
693 """ Implements a somewhat rudimentary version of OpenStack Auth"""
694
695@@ -61,7 +63,7 @@
696
697 def authorize_token(self, token_hash):
698 """ retrieves user information from the datastore given a token
699-
700+
701 If the token has expired, returns None
702 If the token is not found, returns None
703 Otherwise returns dict(id=(the authorized user's id))
704@@ -69,7 +71,7 @@
705 This method will also remove the token if the timestamp is older than
706 2 days ago.
707 """
708- token = self.db.auth_get_token(self.context, token_hash)
709+ token = self.db.auth_get_token(self.context, token_hash)
710 if token:
711 delta = datetime.datetime.now() - token.created_at
712 if delta.days >= 2:
713@@ -94,8 +96,7 @@
714 token_dict['user_id'] = user.id
715 token = self.db.auth_create_token(self.context, token_dict)
716 return token, user
717- return None, None
718+ return None, None
719
720 def _get_server_mgmt_url(self):
721 return 'https://%s/v1.0/' % self.host
722-
723
724=== modified file 'nova/api/openstack/backup_schedules.py'
725--- nova/api/openstack/backup_schedules.py 2010-10-14 22:09:18 +0000
726+++ nova/api/openstack/backup_schedules.py 2010-10-21 22:29:46 +0000
727@@ -22,6 +22,7 @@
728 from nova.api.openstack import faults
729 import nova.image.service
730
731+
732 class Controller(wsgi.Controller):
733 def __init__(self):
734 pass
735
736=== modified file 'nova/api/openstack/faults.py'
737--- nova/api/openstack/faults.py 2010-09-29 19:09:39 +0000
738+++ nova/api/openstack/faults.py 2010-10-21 22:29:46 +0000
739@@ -55,7 +55,7 @@
740 if code == 413:
741 retry = self.wrapped_exc.headers['Retry-After']
742 fault_data[fault_name]['retryAfter'] = retry
743- # 'code' is an attribute on the fault tag itself
744+ # 'code' is an attribute on the fault tag itself
745 metadata = {'application/xml': {'attributes': {fault_name: 'code'}}}
746 serializer = wsgi.Serializer(req.environ, metadata)
747 self.wrapped_exc.body = serializer.to_content_type(fault_data)
748
749=== modified file 'nova/api/openstack/flavors.py'
750--- nova/api/openstack/flavors.py 2010-10-08 20:39:00 +0000
751+++ nova/api/openstack/flavors.py 2010-10-21 22:29:46 +0000
752@@ -22,16 +22,14 @@
753 from nova import wsgi
754 import nova.api.openstack
755
756+
757 class Controller(wsgi.Controller):
758 """Flavor controller for the OpenStack API."""
759
760 _serialization_metadata = {
761 'application/xml': {
762 "attributes": {
763- "flavor": [ "id", "name", "ram", "disk" ]
764- }
765- }
766- }
767+ "flavor": ["id", "name", "ram", "disk"]}}}
768
769 def index(self, req):
770 """Return all flavors in brief."""
771
772=== modified file 'nova/api/openstack/images.py'
773--- nova/api/openstack/images.py 2010-10-19 20:09:12 +0000
774+++ nova/api/openstack/images.py 2010-10-21 22:29:46 +0000
775@@ -27,16 +27,14 @@
776
777 FLAGS = flags.FLAGS
778
779+
780 class Controller(wsgi.Controller):
781
782 _serialization_metadata = {
783 'application/xml': {
784 "attributes": {
785- "image": [ "id", "name", "updated", "created", "status",
786- "serverId", "progress" ]
787- }
788- }
789- }
790+ "image": ["id", "name", "updated", "created", "status",
791+ "serverId", "progress"]}}}
792
793 def __init__(self):
794 self._service = utils.import_object(FLAGS.image_service)
795@@ -72,6 +70,6 @@
796 raise faults.Fault(exc.HTTPNotFound())
797
798 def update(self, req, id):
799- # Users may not modify public images, and that's all that
800+ # Users may not modify public images, and that's all that
801 # we support for now.
802 raise faults.Fault(exc.HTTPNotFound())
803
804=== modified file 'nova/api/openstack/ratelimiting/__init__.py'
805--- nova/api/openstack/ratelimiting/__init__.py 2010-09-15 17:54:38 +0000
806+++ nova/api/openstack/ratelimiting/__init__.py 2010-10-21 22:29:46 +0000
807@@ -13,6 +13,7 @@
808 PER_HOUR = 60 * 60
809 PER_DAY = 60 * 60 * 24
810
811+
812 class Limiter(object):
813
814 """Class providing rate limiting of arbitrary actions."""
815@@ -101,7 +102,8 @@
816 return webob.exc.HTTPForbidden(
817 headers={'X-Wait-Seconds': "%.2f" % delay})
818 else:
819- return '' # 200 OK
820+ # 200 OK
821+ return ''
822
823
824 class WSGIAppProxy(object):
825@@ -109,7 +111,7 @@
826 """Limiter lookalike that proxies to a ratelimiting.WSGIApp."""
827
828 def __init__(self, service_host):
829- """Creates a proxy pointing to a ratelimiting.WSGIApp at the given
830+ """Creates a proxy pointing to a ratelimiting.WSGIApp at the given
831 host."""
832 self.service_host = service_host
833
834@@ -118,5 +120,6 @@
835 conn.request('POST', '/limiter/%s/%s' % (username, action))
836 resp = conn.getresponse()
837 if resp.status == 200:
838- return None # no delay
839+ # No delay
840+ return None
841 return float(resp.getheader('X-Wait-Seconds'))
842
843=== modified file 'nova/api/openstack/servers.py'
844--- nova/api/openstack/servers.py 2010-10-14 20:40:56 +0000
845+++ nova/api/openstack/servers.py 2010-10-21 22:29:46 +0000
846@@ -34,30 +34,32 @@
847
848 FLAGS = flags.FLAGS
849
850+
851 def _filter_params(inst_dict):
852 """ Extracts all updatable parameters for a server update request """
853 keys = dict(name='name', admin_pass='adminPass')
854 new_attrs = {}
855 for k, v in keys.items():
856- if inst_dict.has_key(v):
857+ if v in inst_dict:
858 new_attrs[k] = inst_dict[v]
859 return new_attrs
860
861+
862 def _entity_list(entities):
863 """ Coerces a list of servers into proper dictionary format """
864 return dict(servers=entities)
865
866+
867 def _entity_detail(inst):
868 """ Maps everything to Rackspace-like attributes for return"""
869 power_mapping = {
870- power_state.NOSTATE: 'build',
871- power_state.RUNNING: 'active',
872- power_state.BLOCKED: 'active',
873- power_state.PAUSED: 'suspended',
874+ power_state.NOSTATE: 'build',
875+ power_state.RUNNING: 'active',
876+ power_state.BLOCKED: 'active',
877+ power_state.PAUSED: 'suspended',
878 power_state.SHUTDOWN: 'active',
879- power_state.SHUTOFF: 'active',
880- power_state.CRASHED: 'error'
881- }
882+ power_state.SHUTOFF: 'active',
883+ power_state.CRASHED: 'error'}
884 inst_dict = {}
885
886 mapped_keys = dict(status='state', imageId='image_id',
887@@ -73,21 +75,20 @@
888
889 return dict(server=inst_dict)
890
891+
892 def _entity_inst(inst):
893 """ Filters all model attributes save for id and name """
894 return dict(server=dict(id=inst['id'], name=inst['server_name']))
895
896+
897 class Controller(wsgi.Controller):
898 """ The Server API controller for the OpenStack API """
899
900 _serialization_metadata = {
901 'application/xml': {
902 "attributes": {
903- "server": [ "id", "imageId", "name", "flavorId", "hostId",
904- "status", "progress", "progress" ]
905- }
906- }
907- }
908+ "server": ["id", "imageId", "name", "flavorId", "hostId",
909+ "status", "progress", "progress"]}}}
910
911 def __init__(self, db_driver=None):
912 if not db_driver:
913@@ -209,7 +210,7 @@
914 image = img_service.show(image_id)
915
916 if not image:
917- raise Exception, "Image not found"
918+ raise Exception("Image not found")
919
920 inst['server_name'] = env['server']['name']
921 inst['image_id'] = image_id
922
923=== modified file 'nova/api/openstack/sharedipgroups.py'
924--- nova/api/openstack/sharedipgroups.py 2010-09-25 18:35:23 +0000
925+++ nova/api/openstack/sharedipgroups.py 2010-10-21 22:29:46 +0000
926@@ -17,4 +17,6 @@
927
928 from nova import wsgi
929
930-class Controller(wsgi.Controller): pass
931+
932+class Controller(wsgi.Controller):
933+ pass