You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@libcloud.apache.org by pq...@apache.org on 2010/05/05 02:10:25 UTC
svn commit: r941116 - in /incubator/libcloud/trunk/libcloud/drivers:
dummy.py ec2.py ecp.py gogrid.py ibm.py linode.py rackspace.py
rimuhosting.py slicehost.py softlayer.py vcloud.py vpsnet.py
Author: pquerna
Date: Wed May 5 00:10:25 2010
New Revision: 941116
URL: http://svn.apache.org/viewvc?rev=941116&view=rev
Log:
Style cleanups in all drivers; No functional changes.
Modified:
incubator/libcloud/trunk/libcloud/drivers/dummy.py
incubator/libcloud/trunk/libcloud/drivers/ec2.py
incubator/libcloud/trunk/libcloud/drivers/ecp.py
incubator/libcloud/trunk/libcloud/drivers/gogrid.py
incubator/libcloud/trunk/libcloud/drivers/ibm.py
incubator/libcloud/trunk/libcloud/drivers/linode.py
incubator/libcloud/trunk/libcloud/drivers/rackspace.py
incubator/libcloud/trunk/libcloud/drivers/rimuhosting.py
incubator/libcloud/trunk/libcloud/drivers/slicehost.py
incubator/libcloud/trunk/libcloud/drivers/softlayer.py
incubator/libcloud/trunk/libcloud/drivers/vcloud.py
incubator/libcloud/trunk/libcloud/drivers/vpsnet.py
Modified: incubator/libcloud/trunk/libcloud/drivers/dummy.py
URL: http://svn.apache.org/viewvc/incubator/libcloud/trunk/libcloud/drivers/dummy.py?rev=941116&r1=941115&r2=941116&view=diff
==============================================================================
--- incubator/libcloud/trunk/libcloud/drivers/dummy.py (original)
+++ incubator/libcloud/trunk/libcloud/drivers/dummy.py Wed May 5 00:10:25 2010
@@ -27,8 +27,8 @@ import uuid
class DummyConnection(ConnectionKey):
- def connect(self, host=None, port=None):
- pass
+ def connect(self, host=None, port=None):
+ pass
class DummyNodeDriver(NodeDriver):
Modified: incubator/libcloud/trunk/libcloud/drivers/ec2.py
URL: http://svn.apache.org/viewvc/incubator/libcloud/trunk/libcloud/drivers/ec2.py?rev=941116&r1=941115&r2=941116&view=diff
==============================================================================
--- incubator/libcloud/trunk/libcloud/drivers/ec2.py (original)
+++ incubator/libcloud/trunk/libcloud/drivers/ec2.py Wed May 5 00:10:25 2010
@@ -139,7 +139,7 @@ class EC2Response(Response):
# if you are using the wrong user/password.
msg = "Failure: 403 Forbidden"
if self.status == 403 and self.body[:len(msg)] == msg:
- raise InvalidCredsException(msg)
+ raise InvalidCredsException(msg)
for err in ET.XML(self.body).findall('Errors/Error'):
code, message = err.getchildren()
@@ -167,11 +167,11 @@ class EC2Connection(ConnectionUserAndKey
params['SignatureMethod'] = 'HmacSHA256'
params['AWSAccessKeyId'] = self.user_id
params['Version'] = API_VERSION
- params['Timestamp'] = time.strftime('%Y-%m-%dT%H:%M:%SZ',
+ params['Timestamp'] = time.strftime('%Y-%m-%dT%H:%M:%SZ',
time.gmtime())
params['Signature'] = self._get_aws_auth_param(params, self.key, self.action)
return params
-
+
def _get_aws_auth_param(self, params, secret_key, path='/'):
"""
Creates the signature required for AWS, per
@@ -191,7 +191,7 @@ class EC2Connection(ConnectionUserAndKey
qs = '&'.join(pairs)
string_to_sign = '\n'.join(('GET', self.host, path, qs))
-
+
b64_hmac = base64.b64encode(
hmac.new(secret_key, string_to_sign, digestmod=sha256).digest()
)
@@ -253,7 +253,7 @@ class EC2NodeDriver(NodeDriver):
def _to_nodes(self, object, xpath, groups=None):
return [ self._to_node(el, groups=groups)
for el in object.findall(self._fixxpath(xpath)) ]
-
+
def _to_node(self, element, groups=None):
try:
state = self.NODE_STATE_MAP[
@@ -315,9 +315,9 @@ class EC2NodeDriver(NodeDriver):
return nodes
def list_sizes(self, location=None):
- return [ NodeSize(driver=self.connection.driver, **i)
+ return [ NodeSize(driver=self.connection.driver, **i)
for i in self._instance_types.values() ]
-
+
def list_images(self, location=None):
params = {'Action': 'DescribeImages'}
images = self._to_images(
@@ -419,9 +419,9 @@ class EC2NodeDriver(NodeDriver):
if 'ex_securitygroup' in kwargs:
if not isinstance(kwargs['ex_securitygroup'], list):
- kwargs['ex_securitygroup'] = [kwargs['ex_securitygroup']]
+ kwargs['ex_securitygroup'] = [kwargs['ex_securitygroup']]
for sig in range(len(kwargs['ex_securitygroup'])):
- params['SecurityGroup.%d' % (sig+1,)] = kwargs['ex_securitygroup'][sig]
+ params['SecurityGroup.%d' % (sig+1,)] = kwargs['ex_securitygroup'][sig]
if 'ex_keyname' in kwargs:
params['KeyName'] = kwargs['ex_keyname']
@@ -528,10 +528,10 @@ class EucNodeDriver(EC2NodeDriver):
_instance_types = EC2_US_WEST_INSTANCE_TYPES
def __init__(self, key, secret=None, secure=True, host=None, path=None, port=None):
- super(EucNodeDriver, self).__init__(key, secret, secure, host, port)
- if path is None:
- path = "/services/Eucalyptus"
- self.path = path
+ super(EucNodeDriver, self).__init__(key, secret, secure, host, port)
+ if path is None:
+ path = "/services/Eucalyptus"
+ self.path = path
def list_locations(self):
raise NotImplementedError, \
Modified: incubator/libcloud/trunk/libcloud/drivers/ecp.py
URL: http://svn.apache.org/viewvc/incubator/libcloud/trunk/libcloud/drivers/ecp.py?rev=941116&r1=941115&r2=941116&view=diff
==============================================================================
--- incubator/libcloud/trunk/libcloud/drivers/ecp.py (original)
+++ incubator/libcloud/trunk/libcloud/drivers/ecp.py Wed May 5 00:10:25 2010
@@ -65,16 +65,16 @@ class ECPResponse(Response):
#Interpret the json responses - no error checking required
def parse_body(self):
return json.loads(self.body)
-
+
def getheaders(self):
return self.headers
-
+
class ECPConnection(ConnectionUserAndKey):
responseCls = ECPResponse
host = API_HOST
port = API_PORT
-
+
def add_default_headers(self, headers):
#Authentication
username = self.user_id
@@ -83,9 +83,9 @@ class ECPConnection(ConnectionUserAndKey
'%s:%s' % (username, password))[:-1]
authheader = "Basic %s" % base64string
headers['Authorization']= authheader
-
+
return headers
-
+
def _encode_multipart_formdata(self, fields):
"""
Based on Wade Leftwich's function:
@@ -120,34 +120,34 @@ class ECPNodeDriver(NodeDriver):
"""
Returns a list of all running Nodes
"""
-
+
#Make the call
res = self.connection.request('/rest/hosting/vm/list').parse_body()
-
+
#Put together a list of node objects
nodes=[]
for vm in res['vms']:
node = self._to_node(vm)
if not node == None:
nodes.append(node)
-
+
#And return it
return nodes
-
+
def _to_node(self, vm):
"""
Turns a (json) dictionary into a Node object.
This returns only running VMs.
"""
-
+
#Check state
if not vm['state'] == "running":
return None
-
+
#IPs
iplist = [interface['ip'] for interface in vm['interfaces'] if interface['ip'] != '127.0.0.1']
-
+
public_ips = []
private_ips = []
for ip in iplist:
@@ -160,7 +160,7 @@ class ECPNodeDriver(NodeDriver):
private_ips.append(ip)
else:
public_ips.append(ip)
-
+
#Create the node object
n = Node(
id=vm['uuid'],
@@ -170,24 +170,24 @@ class ECPNodeDriver(NodeDriver):
private_ip=private_ips,
driver=self,
)
-
+
return n
def reboot_node(self, node):
"""
Shuts down a VM and then starts it again.
"""
-
+
#Turn the VM off
#Black magic to make the POST requests work
d = self.connection._encode_multipart_formdata({'action':'stop'})
self.connection.request(
- '/rest/hosting/vm/%s' % node.id,
- method='POST',
- headers=d[0],
+ '/rest/hosting/vm/%s' % node.id,
+ method='POST',
+ headers=d[0],
data=d[1]
).parse_body()
-
+
node.state = NodeState.REBOOTING
#Wait for it to turn off and then continue (to turn it on again)
while node.state == NodeState.REBOOTING:
@@ -199,18 +199,18 @@ class ECPNodeDriver(NodeDriver):
node.state = NodeState.TERMINATED
else:
time.sleep(5)
-
-
+
+
#Turn the VM back on.
#Black magic to make the POST requests work
d = self.connection._encode_multipart_formdata({'action':'start'})
self.connection.request(
'/rest/hosting/vm/%s' % node.id,
- method='POST',
- headers=d[0],
+ method='POST',
+ headers=d[0],
data=d[1]
).parse_body()
-
+
node.state = NodeState.RUNNING
return True
@@ -218,17 +218,17 @@ class ECPNodeDriver(NodeDriver):
"""
Shuts down and deletes a VM.
"""
-
+
#Shut down first
#Black magic to make the POST requests work
d = self.connection._encode_multipart_formdata({'action':'stop'})
self.connection.request(
'/rest/hosting/vm/%s' % node.id,
- method = 'POST',
- headers=d[0],
+ method = 'POST',
+ headers=d[0],
data=d[1]
).parse_body()
-
+
#Ensure there was no applicationl level error
node.state = NodeState.PENDING
#Wait for the VM to turn off before continuing
@@ -241,28 +241,28 @@ class ECPNodeDriver(NodeDriver):
node.state = NodeState.TERMINATED
else:
time.sleep(5)
-
+
#Delete the VM
#Black magic to make the POST requests work
d = self.connection._encode_multipart_formdata({'action':'delete'})
self.connection.request(
- '/rest/hosting/vm/%s' % (node.id),
- method='POST',
- headers=d[0],
+ '/rest/hosting/vm/%s' % (node.id),
+ method='POST',
+ headers=d[0],
data=d[1]
).parse_body()
-
+
return True
def list_images(self, location=None):
"""
Returns a list of all package templates aka appiances aka images
"""
-
+
#Make the call
response = self.connection.request(
'/rest/hosting/ptemplate/list').parse_body()
-
+
#Turn the response into an array of NodeImage objects
images = []
for ptemplate in response['packages']:
@@ -271,19 +271,19 @@ class ECPNodeDriver(NodeDriver):
name= '%s: %s' % (ptemplate['name'], ptemplate['description']),
driver = self,
))
-
+
return images
-
+
def list_sizes(self, location=None):
"""
Returns a list of all hardware templates
"""
-
+
#Make the call
response = self.connection.request(
'/rest/hosting/htemplate/list').parse_body()
-
+
#Turn the response into an array of NodeSize objects
sizes = []
for htemplate in response['templates']:
@@ -296,7 +296,7 @@ class ECPNodeDriver(NodeDriver):
price = 0, #The billing system is external
driver = self,
))
-
+
return sizes
def list_locations(self):
@@ -313,17 +313,17 @@ class ECPNodeDriver(NodeDriver):
def create_node(self, **kwargs):
"""
Creates a virtual machine.
-
+
Parameters: name (string), image (NodeImage), size (NodeSize)
"""
-
+
#Find out what network to put the VM on.
res = self.connection.request('/rest/hosting/network/list').parse_body()
-
- #Use the first / default network because there is no way to specific
+
+ #Use the first / default network because there is no way to specific
#which one
network = res['networks'][0]['uuid']
-
+
#Prepare to make the VM
data = {
'name' : str(kwargs['name']),
@@ -332,16 +332,16 @@ class ECPNodeDriver(NodeDriver):
'network_uuid' : str(network),
'disk' : ''
}
-
+
#Black magic to make the POST requests work
d = self.connection._encode_multipart_formdata(data)
response = self.connection.request(
- '/rest/hosting/vm/',
- method='PUT',
- headers = d[0],
+ '/rest/hosting/vm/',
+ method='PUT',
+ headers = d[0],
data=d[1]
).parse_body()
-
+
#Create a node object and return it.
n = Node(
id=response['machine_id'],
@@ -351,6 +351,5 @@ class ECPNodeDriver(NodeDriver):
private_ip=[],
driver=self,
)
-
- return n
+ return n
Modified: incubator/libcloud/trunk/libcloud/drivers/gogrid.py
URL: http://svn.apache.org/viewvc/incubator/libcloud/trunk/libcloud/drivers/gogrid.py?rev=941116&r1=941115&r2=941116&view=diff
==============================================================================
--- incubator/libcloud/trunk/libcloud/drivers/gogrid.py (original)
+++ incubator/libcloud/trunk/libcloud/drivers/gogrid.py Wed May 5 00:10:25 2010
@@ -75,7 +75,7 @@ GOGRID_INSTANCE_TYPES = {'512MB': {'id':
class GoGridResponse(Response):
def success(self):
if self.status == 403:
- raise InvalidCredsException()
+ raise InvalidCredsException()
if not self.body:
return None
return json.loads(self.body)['status'] == 'success'
@@ -102,7 +102,7 @@ class GoGridConnection(ConnectionUserAnd
params["sig"] = self.get_signature(self.user_id, self.key)
return params
-
+
def get_signature(self, key, secret):
""" create sig from md5 of key + secret + time """
m = hashlib.md5(key+secret+str(int(time.time())))
@@ -210,7 +210,7 @@ class GoGridNodeDriver(NodeDriver):
return object['list'][0]['ip']
def list_sizes(self, location=None):
- return [ NodeSize(driver=self.connection.driver, **i)
+ return [ NodeSize(driver=self.connection.driver, **i)
for i in self._instance_types.values() ]
def list_locations(self):
Modified: incubator/libcloud/trunk/libcloud/drivers/ibm.py
URL: http://svn.apache.org/viewvc/incubator/libcloud/trunk/libcloud/drivers/ibm.py?rev=941116&r1=941115&r2=941116&view=diff
==============================================================================
--- incubator/libcloud/trunk/libcloud/drivers/ibm.py (original)
+++ incubator/libcloud/trunk/libcloud/drivers/ibm.py Wed May 5 00:10:25 2010
@@ -28,12 +28,12 @@ REST_BASE = '/cloud/enterprise/beta/api/
class IBMResponse(Response):
def success(self):
return int(self.status) == 200
-
+
def parse_body(self):
if not self.body:
return None
return ET.XML(self.body)
-
+
def parse_error(self):
if int(self.status) == 401:
if not self.body:
@@ -48,25 +48,25 @@ class IBMConnection(ConnectionUserAndKey
"""
host = HOST
responseCls = IBMResponse
-
+
def add_default_headers(self, headers):
headers['Accept'] = 'text/xml'
headers['Authorization'] = ('Basic %s' % (base64.b64encode('%s:%s' % (self.user_id, self.key))))
if not 'Content-Type' in headers:
headers['Content-Type'] = 'text/xml'
return headers
-
+
def encode_data(self, data):
return urllib.urlencode(data)
-
-class IBMNodeDriver(NodeDriver):
+
+class IBMNodeDriver(NodeDriver):
"""
IBM Developer Cloud node driver.
"""
connectionCls = IBMConnection
type = Provider.IBM
name = "IBM Developer Cloud"
-
+
NODE_STATE_MAP = { 0: NodeState.PENDING,
1: NodeState.PENDING,
2: NodeState.TERMINATED,
@@ -79,11 +79,11 @@ class IBMNodeDriver(NodeDriver):
9: NodeState.PENDING,
10: NodeState.PENDING,
11: NodeState.TERMINATED }
-
+
def create_node(self, **kwargs):
"""
Creates a node in the IBM Developer Cloud.
-
+
See L{NodeDriver.create_node} for more keyword args.
@keyword ex_configurationData: Image-specific configuration parameters.
@@ -109,49 +109,49 @@ class IBMNodeDriver(NodeDriver):
configurationData = kwargs['ex_configurationData']
for key in configurationData.keys():
data.update({key: configurationData.get(key)})
-
+
# Send request!
resp = self.connection.request(action = REST_BASE + 'instances',
headers = {'Content-Type': 'application/x-www-form-urlencoded'},
method = 'POST',
data = data).object
return self._to_nodes(resp)[0]
-
+
def destroy_node(self, node):
url = REST_BASE + 'instances/%s' % (node.id)
status = int(self.connection.request(action = url, method='DELETE').status)
return status == 200
-
+
def reboot_node(self, node):
url = REST_BASE + 'instances/%s' % (node.id)
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {'state': 'restart'}
-
+
resp = self.connection.request(action = url,
method = 'PUT',
headers = headers,
data = data)
return int(resp.status) == 200
-
+
def list_nodes(self):
return self._to_nodes(self.connection.request(REST_BASE + 'instances').object)
-
+
def list_images(self, location = None):
return self._to_images(self.connection.request(REST_BASE + 'images').object)
-
+
def list_sizes(self, location = None):
# IBM Developer Cloud instances currently support SMALL, MEDIUM, and
# LARGE. Storage also supports SMALL, MEDIUM, and LARGE.
return [ NodeSize('SMALL', 'SMALL', None, None, None, None, self.connection.driver),
NodeSize('MEDIUM', 'MEDIUM', None, None, None, None, self.connection.driver),
NodeSize('LARGE', 'LARGE', None, None, None, None, self.connection.driver) ]
-
+
def list_locations(self):
return self._to_locations(self.connection.request(REST_BASE + 'locations').object)
-
+
def _to_nodes(self, object):
return [ self._to_node(instance) for instance in object.findall('Instance') ]
-
+
def _to_node(self, instance):
return Node(id = instance.findtext('ID'),
name = instance.findtext('Name'),
@@ -159,19 +159,19 @@ class IBMNodeDriver(NodeDriver):
public_ip = instance.findtext('IP'),
private_ip = None,
driver = self.connection.driver)
-
+
def _to_images(self, object):
return [ self._to_image(image) for image in object.findall('Image') ]
-
+
def _to_image(self, image):
return NodeImage(id = image.findtext('ID'),
name = image.findtext('Name'),
driver = self.connection.driver,
extra = {'parametersURL': image.findtext('Manifest')})
-
+
def _to_locations(self, object):
return [ self._to_location(location) for location in object.findall('Location') ]
-
+
def _to_location(self, location):
# NOTE: country currently hardcoded
return NodeLocation(id = location.findtext('ID'),
Modified: incubator/libcloud/trunk/libcloud/drivers/linode.py
URL: http://svn.apache.org/viewvc/incubator/libcloud/trunk/libcloud/drivers/linode.py?rev=941116&r1=941115&r2=941116&view=diff
==============================================================================
--- incubator/libcloud/trunk/libcloud/drivers/linode.py (original)
+++ incubator/libcloud/trunk/libcloud/drivers/linode.py Wed May 5 00:10:25 2010
@@ -53,7 +53,7 @@ LINODE_ROOT = "/"
class LinodeResponse(Response):
# Wraps a Linode API HTTP response.
-
+
def __init__(self, response):
# Given a response object, slurp the information from it.
self.body = response.read()
@@ -62,11 +62,11 @@ class LinodeResponse(Response):
self.error = response.reason
self.invalid = LinodeException(0xFF,
"Invalid JSON received from server")
-
+
# Move parse_body() to here; we can't be sure of failure until we've
# parsed the body into JSON.
self.action, self.object, self.errors = self.parse_body()
-
+
if self.error == "Moved Temporarily":
raise LinodeException(0xFA,
"Redirected to error page by API. Bug?")
@@ -74,7 +74,7 @@ class LinodeResponse(Response):
if not self.success():
# Raise the first error, as there will usually only be one
raise self.errors[0]
-
+
def parse_body(self):
# Parse the body of the response into JSON. Will return None if the
# JSON response chokes the parser. Returns a triple:
@@ -91,7 +91,7 @@ class LinodeResponse(Response):
except:
# Assume invalid JSON, and use an error code unused by Linode API.
return (None, None, [self.invalid])
-
+
def parse_error(self):
# Obtain the errors from the response. Will always return a list.
try:
@@ -101,20 +101,20 @@ class LinodeResponse(Response):
return [self._make_excp(e) for e in js["ERRORARRAY"]]
except:
return [self.invalid]
-
+
def success(self):
# Does the response indicate success? If ERRORARRAY has more than one
# entry, we'll say no.
return len(self.errors) == 0
-
+
def _make_excp(self, error):
# Make an exception from an entry in ERRORARRAY.
if "ERRORCODE" not in error or "ERRORMESSAGE" not in error:
return None
if error["ERRORCODE"] == 4:
- return InvalidCredsException(error["ERRORMESSAGE"])
+ return InvalidCredsException(error["ERRORMESSAGE"])
return LinodeException(error["ERRORCODE"], error["ERRORMESSAGE"])
-
+
class LinodeConnection(ConnectionKey):
# Wraps a Linode HTTPS connection, and passes along the connection key.
@@ -132,7 +132,7 @@ class LinodeNodeDriver(NodeDriver):
type = Provider.LINODE
name = "Linode"
connectionCls = LinodeConnection
-
+
def __init__(self, key):
self.datacenter = None
NodeDriver.__init__(self, key)
@@ -155,14 +155,14 @@ class LinodeNodeDriver(NodeDriver):
params = { "api_action": "linode.list" }
data = self.connection.request(LINODE_ROOT, params=params).object
return [self._to_node(n) for n in data]
-
+
def reboot_node(self, node):
# Reboot
# Execute a shutdown and boot job for the given Node.
params = { "api_action": "linode.reboot", "LinodeID": node.id }
self.connection.request(LINODE_ROOT, params=params)
return True
-
+
def destroy_node(self, node):
# Destroy
# Terminates a Node. With prejudice.
@@ -363,7 +363,7 @@ class LinodeNodeDriver(NodeDriver):
price=obj["PRICE"], driver=self.connection.driver)
sizes.append(n)
return sizes
-
+
def list_images(self, location=None):
# List Images
# Retrieve all available Linux distributions.
@@ -424,20 +424,20 @@ class LinodeNodeDriver(NodeDriver):
def _to_node(self, obj):
# Convert a returned Linode instance into a Node instance.
lid = obj["LINODEID"]
-
+
# Get the IP addresses for a Linode
- params = { "api_action": "linode.ip.list", "LinodeID": lid }
+ params = { "api_action": "linode.ip.list", "LinodeID": lid }
req = self.connection.request(LINODE_ROOT, params=params)
if not req.success() or len(req.object) == 0:
return None
-
+
public_ip = []
private_ip = []
for ip in req.object:
if ip["ISPUBLIC"]:
- public_ip.append(ip["IPADDRESS"])
+ public_ip.append(ip["IPADDRESS"])
else:
- private_ip.append(ip["IPADDRESS"])
+ private_ip.append(ip["IPADDRESS"])
n = Node(id=lid, name=obj["LABEL"],
state=self.LINODE_STATES[obj["STATUS"]], public_ip=public_ip,
Modified: incubator/libcloud/trunk/libcloud/drivers/rackspace.py
URL: http://svn.apache.org/viewvc/incubator/libcloud/trunk/libcloud/drivers/rackspace.py?rev=941116&r1=941115&r2=941116&view=diff
==============================================================================
--- incubator/libcloud/trunk/libcloud/drivers/rackspace.py (original)
+++ incubator/libcloud/trunk/libcloud/drivers/rackspace.py Wed May 5 00:10:25 2010
@@ -132,7 +132,7 @@ class RackspaceConnection(ConnectionUser
class RackspaceNodeDriver(NodeDriver):
"""
Rackspace node driver.
-
+
Extra node attributes:
- password: root password, available after create.
- hostId: represents the host your cloud server runs on
@@ -203,11 +203,11 @@ class RackspaceNodeDriver(NodeDriver):
if files_elm:
server_elm.append(files_elm)
- resp = self.connection.request("/servers",
- method='POST',
+ resp = self.connection.request("/servers",
+ method='POST',
data=ET.tostring(server_elm))
return self._to_node(resp.object)
-
+
def _metadata_to_xml(self, metadata):
if len(metadata) == 0:
return None
@@ -218,7 +218,7 @@ class RackspaceNodeDriver(NodeDriver):
meta_elm.text = str(v)
return metadata_elm
-
+
def _files_to_xml(self, files):
if len(files) == 0:
return None
@@ -265,19 +265,19 @@ class RackspaceNodeDriver(NodeDriver):
def _to_node(self, el):
def get_ips(el):
return [ip.get('addr') for ip in el]
-
+
def get_meta_dict(el):
d = {}
for meta in el:
d[meta.get('key')] = meta.text
return d
-
- public_ip = get_ips(self._findall(el,
+
+ public_ip = get_ips(self._findall(el,
'addresses/public/ip'))
- private_ip = get_ips(self._findall(el,
+ private_ip = get_ips(self._findall(el,
'addresses/private/ip'))
metadata = get_meta_dict(self._findall(el, 'metadata/meta'))
-
+
n = Node(id=el.get('id'),
name=el.get('name'),
state=self.NODE_STATE_MAP.get(el.get('status'), NodeState.UNKNOWN),
Modified: incubator/libcloud/trunk/libcloud/drivers/rimuhosting.py
URL: http://svn.apache.org/viewvc/incubator/libcloud/trunk/libcloud/drivers/rimuhosting.py?rev=941116&r1=941115&r2=941116&view=diff
==============================================================================
--- incubator/libcloud/trunk/libcloud/drivers/rimuhosting.py (original)
+++ incubator/libcloud/trunk/libcloud/drivers/rimuhosting.py Wed May 5 00:10:25 2010
@@ -47,11 +47,11 @@ class RimuHostingResponse(Response):
self.error = response.reason
if self.success():
- self.object = self.parse_body()
+ self.object = self.parse_body()
def success(self):
if self.status == 403:
- raise InvalidCredsException()
+ raise InvalidCredsException()
return True
def parse_body(self):
try:
@@ -67,14 +67,14 @@ class RimuHostingResponse(Response):
except KeyError:
raise RimuHostingException('Could not parse body: %s'
% (self.body))
-
+
class RimuHostingConnection(ConnectionKey):
-
+
api_context = API_CONTEXT
host = API_HOST
port = API_PORT
responseCls = RimuHostingResponse
-
+
def __init__(self, key, secure=True):
# override __init__ so that we can set secure of False for testing
ConnectionKey.__init__(self,key,secure)
@@ -85,7 +85,7 @@ class RimuHostingConnection(ConnectionKe
headers['Accept'] = 'application/json'
# Must encode all data as json, or override this header.
headers['Content-Type'] = 'application/json'
-
+
headers['Authorization'] = 'rimuhosting apikey=%s' % (self.key)
return headers;
@@ -102,7 +102,7 @@ class RimuHostingNodeDriver(NodeDriver):
type = Provider.RIMUHOSTING
name = 'RimuHosting'
connectionCls = RimuHostingConnection
-
+
def __init__(self, key, host=API_HOST, port=API_PORT,
api_context=API_CONTEXT, secure=API_SECURE):
# Pass in some extra vars so that
@@ -118,7 +118,7 @@ class RimuHostingNodeDriver(NodeDriver):
def _order_uri(self, node,resource):
# Returns the order uri with its resourse appended.
return "/orders/%s/%s" % (node.id,resource)
-
+
# TODO: Get the node state.
def _to_node(self, order):
n = Node(id=order['slug'],
@@ -143,12 +143,12 @@ class RimuHostingNodeDriver(NodeDriver):
price=plan['monthly_recurring_amt']['amt_usd'],
driver=self.connection.driver
)
-
+
def _to_image(self,image):
return NodeImage(id=image['distro_code'],
name=image['distro_description'],
driver=self.connection.driver)
-
+
def list_sizes(self, location=None):
# Returns a list of sizes (aka plans)
# Get plans. Note this is really just for libcloud.
@@ -166,7 +166,7 @@ class RimuHostingNodeDriver(NodeDriver):
# Will only include active ones.
res = self.connection.request('/orders;include_inactive=N').object
return map(lambda x : self._to_node(x), res['about_orders'])
-
+
def list_images(self, location=None):
# Get all base images.
# TODO: add other image sources. (Such as a backup of a VPS)
@@ -183,7 +183,7 @@ class RimuHostingNodeDriver(NodeDriver):
self.connection.request(uri,data=json.dumps(data),method='PUT')
# XXX check that the response was actually successful
return True
-
+
def destroy_node(self, node):
# Shutdown a VPS.
uri = self._order_uri(node,'vps')
@@ -238,7 +238,7 @@ class RimuHostingNodeDriver(NodeDriver):
},
'pricing_plan_code': size.id,
}
-
+
if kwargs.has_key('ex_control_panel'):
data['instantiation_options']['control_panel'] = kwargs['ex_control_panel']
@@ -247,17 +247,17 @@ class RimuHostingNodeDriver(NodeDriver):
if not isinstance(auth, NodeAuthPassword):
raise ValueError('auth must be of NodeAuthPassword type')
data['instantiation_options']['password'] = auth.password
-
+
if kwargs.has_key('ex_billing_oid'):
#TODO check for valid oid.
data['billing_oid'] = kwargs['ex_billing_oid']
-
+
if kwargs.has_key('ex_host_server_oid'):
data['host_server_oid'] = kwargs['ex_host_server_oid']
-
+
if kwargs.has_key('ex_vps_order_oid_to_clone'):
data['vps_order_oid_to_clone'] = kwargs['ex_vps_order_oid_to_clone']
-
+
if kwargs.has_key('ex_num_ips') and int(kwargs['ex_num_ips']) > 1:
if not kwargs.has_key('ex_extra_ip_reason'):
raise RimuHostingException('Need an reason for having an extra IP')
@@ -266,22 +266,22 @@ class RimuHostingNodeDriver(NodeDriver):
data['ip_request'] = {}
data['ip_request']['num_ips'] = int(kwargs['ex_num_ips'])
data['ip_request']['extra_ip_reason'] = kwargs['ex_extra_ip_reason']
-
+
if kwargs.has_key('ex_memory_mb'):
if not data.has_key('vps_parameters'):
data['vps_parameters'] = {}
data['vps_parameters']['memory_mb'] = kwargs['ex_memory_mb']
-
+
if kwargs.has_key('ex_disk_space_mb'):
if not data.has_key('ex_vps_parameters'):
data['vps_parameters'] = {}
data['vps_parameters']['disk_space_mb'] = kwargs['ex_disk_space_mb']
-
+
if kwargs.has_key('ex_disk_space_2_mb'):
if not data.has_key('vps_parameters'):
data['vps_parameters'] = {}
data['vps_parameters']['disk_space_2_mb'] = kwargs['ex_disk_space_2_mb']
-
+
res = self.connection.request(
'/orders/new-vps',
method='POST',
@@ -290,7 +290,7 @@ class RimuHostingNodeDriver(NodeDriver):
node = self._to_node(res['about_order'])
node.extra['password'] = res['new_order_request']['instantiation_options']['password']
return node
-
+
def list_locations(self):
return [
NodeLocation('DCAUCKLAND', "RimuHosting Auckland", 'NZ', self),
@@ -300,4 +300,3 @@ class RimuHostingNodeDriver(NodeDriver):
]
features = {"create_node": ["password"]}
-
Modified: incubator/libcloud/trunk/libcloud/drivers/slicehost.py
URL: http://svn.apache.org/viewvc/incubator/libcloud/trunk/libcloud/drivers/slicehost.py?rev=941116&r1=941115&r2=941116&view=diff
==============================================================================
--- incubator/libcloud/trunk/libcloud/drivers/slicehost.py (original)
+++ incubator/libcloud/trunk/libcloud/drivers/slicehost.py Wed May 5 00:10:25 2010
@@ -35,7 +35,7 @@ class SlicehostResponse(Response):
def parse_error(self):
if self.status == 401:
- raise InvalidCredsException(self.body)
+ raise InvalidCredsException(self.body)
try:
object = ET.XML(self.body)
@@ -44,7 +44,7 @@ class SlicehostResponse(Response):
object.findall('error') ])
except ExpatError:
return self.body
-
+
class SlicehostConnection(ConnectionKey):
@@ -55,7 +55,7 @@ class SlicehostConnection(ConnectionKey)
headers['Authorization'] = ('Basic %s'
% (base64.b64encode('%s:' % self.key)))
return headers
-
+
class SlicehostNodeDriver(NodeDriver):
@@ -117,7 +117,7 @@ class SlicehostNodeDriver(NodeDriver):
def reboot_node(self, node):
"""Reboot the node by passing in the node object"""
- # 'hard' could bubble up as kwarg depending on how reboot_node
+ # 'hard' could bubble up as kwarg depending on how reboot_node
# turns out. Defaulting to soft reboot.
#hard = False
#reboot = self.api.hard_reboot if hard else self.api.reboot
@@ -151,14 +151,14 @@ class SlicehostNodeDriver(NodeDriver):
def _to_node(self, element):
- attrs = [ 'name', 'image-id', 'progress', 'id', 'bw-out', 'bw-in',
+ attrs = [ 'name', 'image-id', 'progress', 'id', 'bw-out', 'bw-in',
'flavor-id', 'status', 'ip-address', 'root-password' ]
node_attrs = {}
for attr in attrs:
node_attrs[attr] = element.findtext(attr)
- # slicehost does not determine between public and private, so we
+ # slicehost does not determine between public and private, so we
# have to figure it out
public_ip = element.findtext('ip-address')
private_ip = None
@@ -173,7 +173,7 @@ class SlicehostNodeDriver(NodeDriver):
private_ip = ip
else:
public_ip = ip
-
+
try:
state = self.NODE_STATE_MAP[element.findtext('status')]
except:
@@ -183,8 +183,8 @@ class SlicehostNodeDriver(NodeDriver):
node_attrs['password'] = node_attrs['root-password']
extra = {}
for k in node_attrs.keys():
- ek = k.replace("-", "_")
- extra[ek] = node_attrs[k]
+ ek = k.replace("-", "_")
+ extra[ek] = node_attrs[k]
n = Node(id=element.findtext('id'),
name=element.findtext('name'),
state=state,
Modified: incubator/libcloud/trunk/libcloud/drivers/softlayer.py
URL: http://svn.apache.org/viewvc/incubator/libcloud/trunk/libcloud/drivers/softlayer.py?rev=941116&r1=941115&r2=941116&view=diff
==============================================================================
--- incubator/libcloud/trunk/libcloud/drivers/softlayer.py (original)
+++ incubator/libcloud/trunk/libcloud/drivers/softlayer.py Wed May 5 00:10:25 2010
@@ -164,7 +164,7 @@ class SoftLayerConnection(object):
def __init__(self, user, key):
self.user = user
- self.key = key
+ self.key = key
self.ua = []
def request(self, service, method, *args, **kwargs):
@@ -255,7 +255,7 @@ class SoftLayerNodeDriver(NodeDriver):
'password': password
}
)
-
+
def _to_nodes(self, hosts):
return [self._to_node(h) for h in hosts]
@@ -391,10 +391,10 @@ class SoftLayerNodeDriver(NodeDriver):
res = self.connection.request(
"SoftLayer_Location_Datacenter",
"getDatacenters"
- )
+ )
# checking "in DATACENTERS", because some of the locations returned by getDatacenters are not useable.
- return [self._to_loc(l) for l in res if l['name'] in DATACENTERS]
+ return [self._to_loc(l) for l in res if l['name'] in DATACENTERS]
def list_nodes(self):
mask = {
@@ -415,8 +415,8 @@ class SoftLayerNodeDriver(NodeDriver):
def reboot_node(self, node):
res = self.connection.request(
- "SoftLayer_Virtual_Guest",
- "rebootHard",
+ "SoftLayer_Virtual_Guest",
+ "rebootHard",
id=node.id
)
return res
Modified: incubator/libcloud/trunk/libcloud/drivers/vcloud.py
URL: http://svn.apache.org/viewvc/incubator/libcloud/trunk/libcloud/drivers/vcloud.py?rev=941116&r1=941115&r2=941116&view=diff
==============================================================================
--- incubator/libcloud/trunk/libcloud/drivers/vcloud.py (original)
+++ incubator/libcloud/trunk/libcloud/drivers/vcloud.py Wed May 5 00:10:25 2010
@@ -178,13 +178,13 @@ class InstantiateVAppXML(object):
return elm
def _add_virtual_quantity(self, parent, amount):
- elm = ET.SubElement(
- parent,
- "VirtualQuantity",
- {'xmlns': 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData'}
- )
- elm.text = amount
- return elm
+ elm = ET.SubElement(
+ parent,
+ "VirtualQuantity",
+ {'xmlns': 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData'}
+ )
+ elm.text = amount
+ return elm
def _add_network_association(self, parent):
return ET.SubElement(
@@ -312,13 +312,13 @@ class VCloudNodeDriver(NodeDriver):
# Following code to find private IPs works for Terremark
connections = elm.findall('{http://schemas.dmtf.org/ovf/envelope/1}NetworkConnectionSection/{http://www.vmware.com/vcloud/v0.8}NetworkConnection')
for connection in connections:
- ips = [ip.text
- for ip
- in connection.findall(fixxpath(elm, "IpAddress"))]
- if connection.get('Network') == 'Internal':
- private_ips.extend(ips)
- else:
- public_ips.extend(ips)
+ ips = [ip.text
+ for ip
+ in connection.findall(fixxpath(elm, "IpAddress"))]
+ if connection.get('Network') == 'Internal':
+ private_ips.extend(ips)
+ else:
+ public_ips.extend(ips)
node = Node(id=elm.get('href'),
name=name,
@@ -345,18 +345,18 @@ class VCloudNodeDriver(NodeDriver):
res = self.connection.request(task_href)
status = res.object.get('status')
while status != 'success':
- if status == 'error':
- raise Exception("Error status returned by task %s."
- % task_href)
- if status == 'canceled':
- raise Exception("Canceled status returned by task %s."
- % task_href)
- if (time.time() - start_time >= timeout):
- raise Exception("Timeout while waiting for task %s."
- % task_href)
- time.sleep(5)
- res = self.connection.request(task_href)
- status = res.object.get('status')
+ if status == 'error':
+ raise Exception("Error status returned by task %s."
+ % task_href)
+ if status == 'canceled':
+ raise Exception("Canceled status returned by task %s."
+ % task_href)
+ if (time.time() - start_time >= timeout):
+ raise Exception("Timeout while waiting for task %s."
+ % task_href)
+ time.sleep(5)
+ res = self.connection.request(task_href)
+ status = res.object.get('status')
def destroy_node(self, node):
node_path = get_url_path(node.id)
Modified: incubator/libcloud/trunk/libcloud/drivers/vpsnet.py
URL: http://svn.apache.org/viewvc/incubator/libcloud/trunk/libcloud/drivers/vpsnet.py?rev=941116&r1=941115&r2=941116&view=diff
==============================================================================
--- incubator/libcloud/trunk/libcloud/drivers/vpsnet.py (original)
+++ incubator/libcloud/trunk/libcloud/drivers/vpsnet.py Wed May 5 00:10:25 2010
@@ -57,7 +57,7 @@ class VPSNetResponse(Response):
def success(self):
# vps.net wrongly uses 406 for invalid auth creds
if self.status == 406 or self.status == 403:
- raise InvalidCredsException()
+ raise InvalidCredsException()
return True
def parse_error(self):
@@ -154,15 +154,15 @@ class VPSNetNodeDriver(NodeDriver):
return node
def reboot_node(self, node):
- res = self.connection.request('/virtual_machines/%s/%s.%s' %
+ res = self.connection.request('/virtual_machines/%s/%s.%s' %
(node.id, 'reboot', API_VERSION),
method="POST")
node = self._to_node(res.object['virtual_machine'])
return True
-
+
def list_sizes(self, location=None):
res = self.connection.request('/nodes.%s' % (API_VERSION,))
- available_nodes = len([size for size in res.object
+ available_nodes = len([size for size in res.object
if not size['slice']["virtual_machine_id"]])
sizes = [self._to_size(i) for i in range(1,available_nodes + 1)]
return sizes
@@ -175,7 +175,7 @@ class VPSNetNodeDriver(NodeDriver):
def list_nodes(self):
res = self.connection.request('/virtual_machines.%s' % (API_VERSION,))
- return [self._to_node(i['virtual_machine']) for i in res.object]
+ return [self._to_node(i['virtual_machine']) for i in res.object]
def list_images(self, location=None):
res = self.connection.request('/available_clouds.%s' % (API_VERSION,))