You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@libcloud.apache.org by an...@apache.org on 2016/11/14 23:51:10 UTC
[23/56] [abbrv] libcloud git commit: Removed sdist
http://git-wip-us.apache.org/repos/asf/libcloud/blob/8afcda91/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/linode.py
----------------------------------------------------------------------
diff --git a/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/linode.py b/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/linode.py
deleted file mode 100644
index e24e367..0000000
--- a/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/linode.py
+++ /dev/null
@@ -1,683 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""libcloud driver for the Linode(R) API
-
-This driver implements all libcloud functionality for the Linode API.
-Since the API is a bit more fine-grained, create_node abstracts a significant
-amount of work (and may take a while to run).
-
-Linode home page http://www.linode.com/
-Linode API documentation http://www.linode.com/api/
-Alternate bindings for reference http://github.com/tjfontaine/linode-python
-
-Linode(R) is a registered trademark of Linode, LLC.
-
-"""
-
-import os
-
-try:
- import simplejson as json
-except ImportError:
- import json
-
-import itertools
-import binascii
-
-from copy import copy
-
-from libcloud.utils.py3 import PY3
-
-from libcloud.common.linode import (API_ROOT, LinodeException,
- LinodeConnection, LINODE_PLAN_IDS,
- LINODE_DISK_FILESYSTEMS)
-from libcloud.compute.types import Provider, NodeState
-from libcloud.compute.base import NodeDriver, NodeSize, Node, NodeLocation
-from libcloud.compute.base import NodeAuthPassword, NodeAuthSSHKey
-from libcloud.compute.base import NodeImage, StorageVolume
-
-
-class LinodeNodeDriver(NodeDriver):
- """libcloud driver for the Linode API
-
- Rough mapping of which is which:
-
- - list_nodes linode.list
- - reboot_node linode.reboot
- - destroy_node linode.delete
- - create_node linode.create, linode.update,
- linode.disk.createfromdistribution,
- linode.disk.create, linode.config.create,
- linode.ip.addprivate, linode.boot
- - list_sizes avail.linodeplans
- - list_images avail.distributions
- - list_locations avail.datacenters
- - list_volumes linode.disk.list
- - destroy_volume linode.disk.delete
-
- For more information on the Linode API, be sure to read the reference:
-
- http://www.linode.com/api/
- """
- type = Provider.LINODE
- name = "Linode"
- website = 'http://www.linode.com/'
- connectionCls = LinodeConnection
- _linode_plan_ids = LINODE_PLAN_IDS
- _linode_disk_filesystems = LINODE_DISK_FILESYSTEMS
- features = {'create_node': ['ssh_key', 'password']}
-
- def __init__(self, key):
- """Instantiate the driver with the given API key
-
- :param key: the API key to use (required)
- :type key: ``str``
-
- :rtype: ``None``
- """
- self.datacenter = None
- NodeDriver.__init__(self, key)
-
- # Converts Linode's state from DB to a NodeState constant.
- LINODE_STATES = {
- (-2): NodeState.UNKNOWN, # Boot Failed
- (-1): NodeState.PENDING, # Being Created
- 0: NodeState.PENDING, # Brand New
- 1: NodeState.RUNNING, # Running
- 2: NodeState.TERMINATED, # Powered Off
- 3: NodeState.REBOOTING, # Shutting Down
- 4: NodeState.UNKNOWN # Reserved
- }
-
- def list_nodes(self):
- """
- List all Linodes that the API key can access
-
- This call will return all Linodes that the API key in use has access
- to.
- If a node is in this list, rebooting will work; however, creation and
- destruction are a separate grant.
-
- :return: List of node objects that the API key can access
- :rtype: ``list`` of :class:`Node`
- """
- params = {"api_action": "linode.list"}
- data = self.connection.request(API_ROOT, params=params).objects[0]
- return self._to_nodes(data)
-
- def reboot_node(self, node):
- """
- Reboot the given Linode
-
- Will issue a shutdown job followed by a boot job, using the last booted
- configuration. In most cases, this will be the only configuration.
-
- :param node: the Linode to reboot
- :type node: :class:`Node`
-
- :rtype: ``bool``
- """
- params = {"api_action": "linode.reboot", "LinodeID": node.id}
- self.connection.request(API_ROOT, params=params)
- return True
-
- def destroy_node(self, node):
- """Destroy the given Linode
-
- Will remove the Linode from the account and issue a prorated credit. A
- grant for removing Linodes from the account is required, otherwise this
- method will fail.
-
- In most cases, all disk images must be removed from a Linode before the
- Linode can be removed; however, this call explicitly skips those
- safeguards. There is no going back from this method.
-
- :param node: the Linode to destroy
- :type node: :class:`Node`
-
- :rtype: ``bool``
- """
- params = {"api_action": "linode.delete", "LinodeID": node.id,
- "skipChecks": True}
- self.connection.request(API_ROOT, params=params)
- return True
-
- def create_node(self, **kwargs):
- """Create a new Linode, deploy a Linux distribution, and boot
-
- This call abstracts much of the functionality of provisioning a Linode
- and getting it booted. A global grant to add Linodes to the account is
- required, as this call will result in a billing charge.
-
- Note that there is a safety valve of 5 Linodes per hour, in order to
- prevent a runaway script from ruining your day.
-
- :keyword name: the name to assign the Linode (mandatory)
- :type name: ``str``
-
- :keyword image: which distribution to deploy on the Linode (mandatory)
- :type image: :class:`NodeImage`
-
- :keyword size: the plan size to create (mandatory)
- :type size: :class:`NodeSize`
-
- :keyword auth: an SSH key or root password (mandatory)
- :type auth: :class:`NodeAuthSSHKey` or :class:`NodeAuthPassword`
-
- :keyword location: which datacenter to create the Linode in
- :type location: :class:`NodeLocation`
-
- :keyword ex_swap: size of the swap partition in MB (128)
- :type ex_swap: ``int``
-
- :keyword ex_rsize: size of the root partition in MB (plan size - swap).
- :type ex_rsize: ``int``
-
- :keyword ex_kernel: a kernel ID from avail.kernels (Latest 2.6 Stable).
- :type ex_kernel: ``str``
-
- :keyword ex_payment: one of 1, 12, or 24; subscription length (1)
- :type ex_payment: ``int``
-
- :keyword ex_comment: a small comment for the configuration (libcloud)
- :type ex_comment: ``str``
-
- :keyword ex_private: whether or not to request a private IP (False)
- :type ex_private: ``bool``
-
- :keyword lconfig: what to call the configuration (generated)
- :type lconfig: ``str``
-
- :keyword lroot: what to call the root image (generated)
- :type lroot: ``str``
-
- :keyword lswap: what to call the swap space (generated)
- :type lswap: ``str``
-
- :return: Node representing the newly-created Linode
- :rtype: :class:`Node`
- """
- name = kwargs["name"]
- image = kwargs["image"]
- size = kwargs["size"]
- auth = self._get_and_check_auth(kwargs["auth"])
-
- # Pick a location (resolves LIBCLOUD-41 in JIRA)
- if "location" in kwargs:
- chosen = kwargs["location"].id
- elif self.datacenter:
- chosen = self.datacenter
- else:
- raise LinodeException(0xFB, "Need to select a datacenter first")
-
- # Step 0: Parameter validation before we purchase
- # We're especially careful here so we don't fail after purchase, rather
- # than getting halfway through the process and having the API fail.
-
- # Plan ID
- plans = self.list_sizes()
- if size.id not in [p.id for p in plans]:
- raise LinodeException(0xFB, "Invalid plan ID -- avail.plans")
-
- # Payment schedule
- payment = "1" if "ex_payment" not in kwargs else \
- str(kwargs["ex_payment"])
- if payment not in ["1", "12", "24"]:
- raise LinodeException(0xFB, "Invalid subscription (1, 12, 24)")
-
- ssh = None
- root = None
- # SSH key and/or root password
- if isinstance(auth, NodeAuthSSHKey):
- ssh = auth.pubkey
- elif isinstance(auth, NodeAuthPassword):
- root = auth.password
-
- if not ssh and not root:
- raise LinodeException(0xFB, "Need SSH key or root password")
- if root is not None and len(root) < 6:
- raise LinodeException(0xFB, "Root password is too short")
-
- # Swap size
- try:
- swap = 128 if "ex_swap" not in kwargs else int(kwargs["ex_swap"])
- except:
- raise LinodeException(0xFB, "Need an integer swap size")
-
- # Root partition size
- imagesize = (size.disk - swap) if "ex_rsize" not in kwargs else\
- int(kwargs["ex_rsize"])
- if (imagesize + swap) > size.disk:
- raise LinodeException(0xFB, "Total disk images are too big")
-
- # Distribution ID
- distros = self.list_images()
- if image.id not in [d.id for d in distros]:
- raise LinodeException(0xFB,
- "Invalid distro -- avail.distributions")
-
- # Kernel
- if "ex_kernel" in kwargs:
- kernel = kwargs["ex_kernel"]
- else:
- if image.extra['64bit']:
- # For a list of available kernel ids, see
- # https://www.linode.com/kernels/
- kernel = 138
- else:
- kernel = 137
- params = {"api_action": "avail.kernels"}
- kernels = self.connection.request(API_ROOT, params=params).objects[0]
- if kernel not in [z["KERNELID"] for z in kernels]:
- raise LinodeException(0xFB, "Invalid kernel -- avail.kernels")
-
- # Comments
- comments = "Created by Apache libcloud <http://www.libcloud.org>" if\
- "ex_comment" not in kwargs else kwargs["ex_comment"]
-
- # Step 1: linode.create
- params = {
- "api_action": "linode.create",
- "DatacenterID": chosen,
- "PlanID": size.id,
- "PaymentTerm": payment
- }
- data = self.connection.request(API_ROOT, params=params).objects[0]
- linode = {"id": data["LinodeID"]}
-
- # Step 1b. linode.update to rename the Linode
- params = {
- "api_action": "linode.update",
- "LinodeID": linode["id"],
- "Label": name
- }
- self.connection.request(API_ROOT, params=params)
-
- # Step 1c. linode.ip.addprivate if it was requested
- if "ex_private" in kwargs and kwargs["ex_private"]:
- params = {
- "api_action": "linode.ip.addprivate",
- "LinodeID": linode["id"]
- }
- self.connection.request(API_ROOT, params=params)
-
- # Step 1d. Labels
- # use the linode id as the name can be up to 63 chars and the labels
- # are limited to 48 chars
- label = {
- "lconfig": "[%s] Configuration Profile" % linode["id"],
- "lroot": "[%s] %s Disk Image" % (linode["id"], image.name),
- "lswap": "[%s] Swap Space" % linode["id"]
- }
- for what in ["lconfig", "lroot", "lswap"]:
- if what in kwargs:
- label[what] = kwargs[what]
-
- # Step 2: linode.disk.createfromdistribution
- if not root:
- root = binascii.b2a_base64(os.urandom(8)).decode('ascii').strip()
-
- params = {
- "api_action": "linode.disk.createfromdistribution",
- "LinodeID": linode["id"],
- "DistributionID": image.id,
- "Label": label["lroot"],
- "Size": imagesize,
- "rootPass": root,
- }
- if ssh:
- params["rootSSHKey"] = ssh
- data = self.connection.request(API_ROOT, params=params).objects[0]
- linode["rootimage"] = data["DiskID"]
-
- # Step 3: linode.disk.create for swap
- params = {
- "api_action": "linode.disk.create",
- "LinodeID": linode["id"],
- "Label": label["lswap"],
- "Type": "swap",
- "Size": swap
- }
- data = self.connection.request(API_ROOT, params=params).objects[0]
- linode["swapimage"] = data["DiskID"]
-
- # Step 4: linode.config.create for main profile
- disks = "%s,%s,,,,,,," % (linode["rootimage"], linode["swapimage"])
- params = {
- "api_action": "linode.config.create",
- "LinodeID": linode["id"],
- "KernelID": kernel,
- "Label": label["lconfig"],
- "Comments": comments,
- "DiskList": disks
- }
- data = self.connection.request(API_ROOT, params=params).objects[0]
- linode["config"] = data["ConfigID"]
-
- # Step 5: linode.boot
- params = {
- "api_action": "linode.boot",
- "LinodeID": linode["id"],
- "ConfigID": linode["config"]
- }
- self.connection.request(API_ROOT, params=params)
-
- # Make a node out of it and hand it back
- params = {"api_action": "linode.list", "LinodeID": linode["id"]}
- data = self.connection.request(API_ROOT, params=params).objects[0]
- nodes = self._to_nodes(data)
-
- if len(nodes) == 1:
- node = nodes[0]
- if getattr(auth, "generated", False):
- node.extra['password'] = auth.password
- return node
-
- return None
-
- def list_sizes(self, location=None):
- """
- List available Linode plans
-
- Gets the sizes that can be used for creating a Linode. Since available
- Linode plans vary per-location, this method can also be passed a
- location to filter the availability.
-
- :keyword location: the facility to retrieve plans in
- :type location: :class:`NodeLocation`
-
- :rtype: ``list`` of :class:`NodeSize`
- """
- params = {"api_action": "avail.linodeplans"}
- data = self.connection.request(API_ROOT, params=params).objects[0]
- sizes = []
- for obj in data:
- n = NodeSize(id=obj["PLANID"], name=obj["LABEL"], ram=obj["RAM"],
- disk=(obj["DISK"] * 1024), bandwidth=obj["XFER"],
- price=obj["PRICE"], driver=self.connection.driver)
- sizes.append(n)
- return sizes
-
- def list_images(self):
- """
- List available Linux distributions
-
- Retrieve all Linux distributions that can be deployed to a Linode.
-
- :rtype: ``list`` of :class:`NodeImage`
- """
- params = {"api_action": "avail.distributions"}
- data = self.connection.request(API_ROOT, params=params).objects[0]
- distros = []
- for obj in data:
- i = NodeImage(id=obj["DISTRIBUTIONID"],
- name=obj["LABEL"],
- driver=self.connection.driver,
- extra={'pvops': obj['REQUIRESPVOPSKERNEL'],
- '64bit': obj['IS64BIT']})
- distros.append(i)
- return distros
-
- def list_locations(self):
- """
- List available facilities for deployment
-
- Retrieve all facilities that a Linode can be deployed in.
-
- :rtype: ``list`` of :class:`NodeLocation`
- """
- params = {"api_action": "avail.datacenters"}
- data = self.connection.request(API_ROOT, params=params).objects[0]
- nl = []
- for dc in data:
- country = None
- if "USA" in dc["LOCATION"]:
- country = "US"
- elif "UK" in dc["LOCATION"]:
- country = "GB"
- elif "JP" in dc["LOCATION"]:
- country = "JP"
- else:
- country = "??"
- nl.append(NodeLocation(dc["DATACENTERID"],
- dc["LOCATION"],
- country,
- self))
- return nl
-
- def linode_set_datacenter(self, dc):
- """
- Set the default datacenter for Linode creation
-
- Since Linodes must be created in a facility, this function sets the
- default that :class:`create_node` will use. If a location keyword is
- not passed to :class:`create_node`, this method must have already been
- used.
-
- :keyword dc: the datacenter to create Linodes in unless specified
- :type dc: :class:`NodeLocation`
-
- :rtype: ``bool``
- """
- did = dc.id
- params = {"api_action": "avail.datacenters"}
- data = self.connection.request(API_ROOT, params=params).objects[0]
- for datacenter in data:
- if did == dc["DATACENTERID"]:
- self.datacenter = did
- return
-
- dcs = ", ".join([d["DATACENTERID"] for d in data])
- self.datacenter = None
- raise LinodeException(0xFD, "Invalid datacenter (use one of %s)" % dcs)
-
- def destroy_volume(self, volume):
- """
- Destroys disk volume for the Linode. Linode id is to be provided as
- extra["LinodeId"] whithin :class:`StorageVolume`. It can be retrieved
- by :meth:`libcloud.compute.drivers.linode.LinodeNodeDriver\
- .ex_list_volumes`.
-
- :param volume: Volume to be destroyed
- :type volume: :class:`StorageVolume`
-
- :rtype: ``bool``
- """
- if not isinstance(volume, StorageVolume):
- raise LinodeException(0xFD, "Invalid volume instance")
-
- if volume.extra["LINODEID"] is None:
- raise LinodeException(0xFD, "Missing LinodeID")
-
- params = {
- "api_action": "linode.disk.delete",
- "LinodeID": volume.extra["LINODEID"],
- "DiskID": volume.id,
- }
- self.connection.request(API_ROOT, params=params)
-
- return True
-
- def ex_create_volume(self, size, name, node, fs_type):
- """
- Create disk for the Linode.
-
- :keyword size: Size of volume in megabytes (required)
- :type size: ``int``
-
- :keyword name: Name of the volume to be created
- :type name: ``str``
-
- :keyword node: Node to attach volume to.
- :type node: :class:`Node`
-
- :keyword fs_type: The formatted type of this disk. Valid types are:
- ext3, ext4, swap, raw
- :type fs_type: ``str``
-
-
- :return: StorageVolume representing the newly-created volume
- :rtype: :class:`StorageVolume`
- """
- # check node
- if not isinstance(node, Node):
- raise LinodeException(0xFD, "Invalid node instance")
-
- # check space available
- total_space = node.extra['TOTALHD']
- existing_volumes = self.ex_list_volumes(node)
- used_space = 0
- for volume in existing_volumes:
- used_space = used_space + volume.size
-
- available_space = total_space - used_space
- if available_space < size:
- raise LinodeException(0xFD, "Volume size too big. Available space\
- %d" % available_space)
-
- # check filesystem type
- if fs_type not in self._linode_disk_filesystems:
- raise LinodeException(0xFD, "Not valid filesystem type")
-
- params = {
- "api_action": "linode.disk.create",
- "LinodeID": node.id,
- "Label": name,
- "Type": fs_type,
- "Size": size
- }
- data = self.connection.request(API_ROOT, params=params).objects[0]
- volume = data["DiskID"]
- # Make a volume out of it and hand it back
- params = {
- "api_action": "linode.disk.list",
- "LinodeID": node.id,
- "DiskID": volume
- }
- data = self.connection.request(API_ROOT, params=params).objects[0]
- return self._to_volumes(data)[0]
-
- def ex_list_volumes(self, node, disk_id=None):
- """
- List existing disk volumes for for given Linode.
-
- :keyword node: Node to list disk volumes for. (required)
- :type node: :class:`Node`
-
- :keyword disk_id: Id for specific disk volume. (optional)
- :type disk_id: ``int``
-
- :rtype: ``list`` of :class:`StorageVolume`
- """
- if not isinstance(node, Node):
- raise LinodeException(0xFD, "Invalid node instance")
-
- params = {
- "api_action": "linode.disk.list",
- "LinodeID": node.id
- }
- # Add param if disk_id was specified
- if disk_id is not None:
- params["DiskID"] = disk_id
-
- data = self.connection.request(API_ROOT, params=params).objects[0]
- return self._to_volumes(data)
-
- def _to_volumes(self, objs):
- """
- Covert returned JSON volumes into StorageVolume instances
-
- :keyword objs: ``list`` of JSON dictionaries representing the
- StorageVolumes
- :type objs: ``list``
-
- :return: ``list`` of :class:`StorageVolume`s
- """
- volumes = {}
- for o in objs:
- vid = o["DISKID"]
- volumes[vid] = vol = StorageVolume(id=vid, name=o["LABEL"],
- size=int(o["SIZE"]),
- driver=self.connection.driver)
- vol.extra = copy(o)
- return list(volumes.values())
-
- def _to_nodes(self, objs):
- """Convert returned JSON Linodes into Node instances
-
- :keyword objs: ``list`` of JSON dictionaries representing the Linodes
- :type objs: ``list``
- :return: ``list`` of :class:`Node`s"""
-
- # Get the IP addresses for the Linodes
- nodes = {}
- batch = []
- for o in objs:
- lid = o["LINODEID"]
- nodes[lid] = n = Node(id=lid, name=o["LABEL"], public_ips=[],
- private_ips=[],
- state=self.LINODE_STATES[o["STATUS"]],
- driver=self.connection.driver)
- n.extra = copy(o)
- n.extra["PLANID"] = self._linode_plan_ids.get(o.get("TOTALRAM"))
- batch.append({"api_action": "linode.ip.list", "LinodeID": lid})
-
- # Avoid batch limitation
- ip_answers = []
- args = [iter(batch)] * 25
-
- if PY3:
- izip_longest = itertools.zip_longest
- else:
- izip_longest = getattr(itertools, 'izip_longest', _izip_longest)
-
- for twenty_five in izip_longest(*args):
- twenty_five = [q for q in twenty_five if q]
- params = {"api_action": "batch",
- "api_requestArray": json.dumps(twenty_five)}
- req = self.connection.request(API_ROOT, params=params)
- if not req.success() or len(req.objects) == 0:
- return None
- ip_answers.extend(req.objects)
-
- # Add the returned IPs to the nodes and return them
- for ip_list in ip_answers:
- for ip in ip_list:
- lid = ip["LINODEID"]
- which = nodes[lid].public_ips if ip["ISPUBLIC"] == 1 else\
- nodes[lid].private_ips
- which.append(ip["IPADDRESS"])
- return list(nodes.values())
-
-
-def _izip_longest(*args, **kwds):
- """Taken from Python docs
-
- http://docs.python.org/library/itertools.html#itertools.izip
- """
-
- fillvalue = kwds.get('fillvalue')
-
- def sentinel(counter=([fillvalue] * (len(args) - 1)).pop):
- yield counter() # yields the fillvalue, or raises IndexError
-
- fillers = itertools.repeat(fillvalue)
- iters = [itertools.chain(it, sentinel(), fillers) for it in args]
- try:
- for tup in itertools.izip(*iters):
- yield tup
- except IndexError:
- pass
http://git-wip-us.apache.org/repos/asf/libcloud/blob/8afcda91/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/medone.py
----------------------------------------------------------------------
diff --git a/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/medone.py b/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/medone.py
deleted file mode 100644
index 2273303..0000000
--- a/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/medone.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""
-Med-1 Driver
-"""
-
-from libcloud.compute.providers import Provider
-from libcloud.common.dimensiondata import (DimensionDataConnection,
- API_ENDPOINTS)
-from libcloud.compute.drivers.dimensiondata import DimensionDataNodeDriver
-
-DEFAULT_REGION = 'med1-il'
-
-
-class MedOneNodeDriver(DimensionDataNodeDriver):
- """
- Med-1 node driver, based on Dimension Data driver
- """
-
- selected_region = None
- connectionCls = DimensionDataConnection
- name = 'MedOne'
- website = 'http://www.med-1.com/'
- type = Provider.MEDONE
- features = {'create_node': ['password']}
- api_version = 1.0
-
- def __init__(self, key, secret=None, secure=True, host=None, port=None,
- api_version=None, region=DEFAULT_REGION, **kwargs):
-
- if region not in API_ENDPOINTS:
- raise ValueError('Invalid region: %s' % (region))
-
- self.selected_region = API_ENDPOINTS[region]
-
- super(MedOneNodeDriver, self).__init__(
- key=key,
- secret=secret,
- secure=secure,
- host=host,
- port=port,
- api_version=api_version,
- region=region,
- **kwargs)
http://git-wip-us.apache.org/repos/asf/libcloud/blob/8afcda91/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/nephoscale.py
----------------------------------------------------------------------
diff --git a/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/nephoscale.py b/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/nephoscale.py
deleted file mode 100644
index e06b7d3..0000000
--- a/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/nephoscale.py
+++ /dev/null
@@ -1,448 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""
-NephoScale Cloud driver (http://www.nephoscale.com)
-API documentation: http://docs.nephoscale.com
-Created by Markos Gogoulos (https://mist.io)
-"""
-
-import base64
-import sys
-import time
-import os
-import binascii
-
-from libcloud.utils.py3 import httplib
-from libcloud.utils.py3 import b
-from libcloud.utils.py3 import urlencode
-
-from libcloud.compute.providers import Provider
-from libcloud.common.base import JsonResponse, ConnectionUserAndKey
-from libcloud.compute.types import (NodeState, InvalidCredsError,
- LibcloudError)
-from libcloud.compute.base import (Node, NodeDriver, NodeImage, NodeSize,
- NodeLocation)
-from libcloud.utils.networking import is_private_subnet
-
-API_HOST = 'api.nephoscale.com'
-
-NODE_STATE_MAP = {
- 'on': NodeState.RUNNING,
- 'off': NodeState.UNKNOWN,
- 'unknown': NodeState.UNKNOWN,
-}
-
-VALID_RESPONSE_CODES = [httplib.OK, httplib.ACCEPTED, httplib.CREATED,
- httplib.NO_CONTENT]
-
-# used in create_node and specifies how many times to get the list of nodes and
-# check if the newly created node is there. This is because when a request is
-# sent to create a node, NephoScale replies with the job id, and not the node
-# itself thus we don't have the ip addresses, that are required in deploy_node
-CONNECT_ATTEMPTS = 10
-
-
-class NodeKey(object):
- def __init__(self, id, name, public_key=None, key_group=None,
- password=None):
- self.id = id
- self.name = name
- self.key_group = key_group
- self.password = password
- self.public_key = public_key
-
- def __repr__(self):
- return (('<NodeKey: id=%s, name=%s>') %
- (self.id, self.name))
-
-
-class NephoscaleResponse(JsonResponse):
- """
- Nephoscale API Response
- """
-
- def parse_error(self):
- if self.status == httplib.UNAUTHORIZED:
- raise InvalidCredsError('Authorization Failed')
- if self.status == httplib.NOT_FOUND:
- raise Exception("The resource you are looking for is not found.")
-
- return self.body
-
- def success(self):
- return self.status in VALID_RESPONSE_CODES
-
-
-class NephoscaleConnection(ConnectionUserAndKey):
- """
- Nephoscale connection class.
- Authenticates to the API through Basic Authentication
- with username/password
- """
- host = API_HOST
- responseCls = NephoscaleResponse
-
- allow_insecure = False
-
- def add_default_headers(self, headers):
- """
- Add parameters that are necessary for every request
- """
- user_b64 = base64.b64encode(b('%s:%s' % (self.user_id, self.key)))
- headers['Authorization'] = 'Basic %s' % (user_b64.decode('utf-8'))
- return headers
-
-
-class NephoscaleNodeDriver(NodeDriver):
- """
- Nephoscale node driver class.
-
- >>> from libcloud.compute.providers import get_driver
- >>> driver = get_driver('nephoscale')
- >>> conn = driver('nepho_user','nepho_password')
- >>> conn.list_nodes()
- """
-
- type = Provider.NEPHOSCALE
- api_name = 'nephoscale'
- name = 'NephoScale'
- website = 'http://www.nephoscale.com'
- connectionCls = NephoscaleConnection
- features = {'create_node': ['ssh_key']}
-
- def list_locations(self):
- """
- List available zones for deployment
-
- :rtype: ``list`` of :class:`NodeLocation`
- """
- result = self.connection.request('/datacenter/zone/').object
- locations = []
- for value in result.get('data', []):
- location = NodeLocation(id=value.get('id'),
- name=value.get('name'),
- country='US',
- driver=self)
- locations.append(location)
- return locations
-
- def list_images(self):
- """
- List available images for deployment
-
- :rtype: ``list`` of :class:`NodeImage`
- """
- result = self.connection.request('/image/server/').object
- images = []
- for value in result.get('data', []):
- extra = {'architecture': value.get('architecture'),
- 'disks': value.get('disks'),
- 'billable_type': value.get('billable_type'),
- 'pcpus': value.get('pcpus'),
- 'cores': value.get('cores'),
- 'uri': value.get('uri'),
- 'storage': value.get('storage'),
- }
- image = NodeImage(id=value.get('id'),
- name=value.get('friendly_name'),
- driver=self,
- extra=extra)
- images.append(image)
- return images
-
- def list_sizes(self):
- """
- List available sizes containing prices
-
- :rtype: ``list`` of :class:`NodeSize`
- """
- result = self.connection.request('/server/type/cloud/').object
- sizes = []
- for value in result.get('data', []):
- value_id = value.get('id')
- size = NodeSize(id=value_id,
- name=value.get('friendly_name'),
- ram=value.get('ram'),
- disk=value.get('storage'),
- bandwidth=None,
- price=self._get_size_price(size_id=str(value_id)),
- driver=self)
- sizes.append(size)
-
- return sorted(sizes, key=lambda k: k.price)
-
- def list_nodes(self):
- """
- List available nodes
-
- :rtype: ``list`` of :class:`Node`
- """
- result = self.connection.request('/server/cloud/').object
- nodes = [self._to_node(value) for value in result.get('data', [])]
- return nodes
-
- def rename_node(self, node, name, hostname=None):
- """rename a cloud server, optionally specify hostname too"""
- data = {'name': name}
- if hostname:
- data['hostname'] = hostname
- params = urlencode(data)
- result = self.connection.request('/server/cloud/%s/' % node.id,
- data=params, method='PUT').object
- return result.get('response') in VALID_RESPONSE_CODES
-
- def reboot_node(self, node):
- """reboot a running node"""
- result = self.connection.request('/server/cloud/%s/initiator/restart/'
- % node.id, method='POST').object
- return result.get('response') in VALID_RESPONSE_CODES
-
- def ex_start_node(self, node):
- """start a stopped node"""
- result = self.connection.request('/server/cloud/%s/initiator/start/'
- % node.id, method='POST').object
- return result.get('response') in VALID_RESPONSE_CODES
-
- def ex_stop_node(self, node):
- """stop a running node"""
- result = self.connection.request('/server/cloud/%s/initiator/stop/'
- % node.id, method='POST').object
- return result.get('response') in VALID_RESPONSE_CODES
-
- def destroy_node(self, node):
- """destroy a node"""
- result = self.connection.request('/server/cloud/%s/' % node.id,
- method='DELETE').object
- return result.get('response') in VALID_RESPONSE_CODES
-
- def ex_list_keypairs(self, ssh=False, password=False, key_group=None):
- """
- List available console and server keys
- There are two types of keys for NephoScale, ssh and password keys.
- If run without arguments, lists all keys. Otherwise list only
- ssh keys, or only password keys.
- Password keys with key_group 4 are console keys. When a server
- is created, it has two keys, one password or ssh key, and
- one password console key.
-
- :keyword ssh: if specified, show ssh keys only (optional)
- :type ssh: ``bool``
-
- :keyword password: if specified, show password keys only (optional)
- :type password: ``bool``
-
- :keyword key_group: if specified, show keys with this key_group only
- eg key_group=4 for console password keys (optional)
- :type key_group: ``int``
-
- :rtype: ``list`` of :class:`NodeKey`
- """
- if (ssh and password):
- raise LibcloudError('You can only supply ssh or password. To \
-get all keys call with no arguments')
- if ssh:
- result = self.connection.request('/key/sshrsa/').object
- elif password:
- result = self.connection.request('/key/password/').object
- else:
- result = self.connection.request('/key/').object
- keys = [self._to_key(value) for value in result.get('data', [])]
-
- if key_group:
- keys = [key for key in keys if
- key.key_group == key_group]
- return keys
-
- def ex_create_keypair(self, name, public_key=None, password=None,
- key_group=None):
- """Creates a key, ssh or password, for server or console
- The group for the key (key_group) is 1 for Server and 4 for Console
- Returns the id of the created key
- """
- if public_key:
- if not key_group:
- key_group = 1
- data = {
- 'name': name,
- 'public_key': public_key,
- 'key_group': key_group
-
- }
- params = urlencode(data)
- result = self.connection.request('/key/sshrsa/', data=params,
- method='POST').object
- else:
- if not key_group:
- key_group = 4
- if not password:
- password = self.random_password()
- data = {
- 'name': name,
- 'password': password,
- 'key_group': key_group
- }
- params = urlencode(data)
- result = self.connection.request('/key/password/', data=params,
- method='POST').object
- return result.get('data', {}).get('id', '')
-
- def ex_delete_keypair(self, key_id, ssh=False):
- """Delete an ssh key or password given it's id
- """
- if ssh:
- result = self.connection.request('/key/sshrsa/%s/' % key_id,
- method='DELETE').object
- else:
- result = self.connection.request('/key/password/%s/' % key_id,
- method='DELETE').object
- return result.get('response') in VALID_RESPONSE_CODES
-
- def create_node(self, name, size, image, server_key=None,
- console_key=None, zone=None, **kwargs):
- """Creates the node, and sets the ssh key, console key
- NephoScale will respond with a 200-200 response after sending a valid
- request. If nowait=True is specified in the args, we then ask a few
- times until the server is created and assigned a public IP address,
- so that deploy_node can be run
-
- >>> from libcloud.compute.providers import get_driver
- >>> driver = get_driver('nephoscale')
- >>> conn = driver('nepho_user','nepho_password')
- >>> conn.list_nodes()
- >>> name = 'staging-server'
- >>> size = conn.list_sizes()[0]
- <NodeSize: id=27, ...name=CS025 - 0.25GB, 10GB, ...>
- >>> image = conn.list_images()[9]
- <NodeImage: id=49, name=Linux Ubuntu Server 10.04 LTS 64-bit, ...>
- >>> server_keys = conn.ex_list_keypairs(key_group=1)[0]
- <NodeKey: id=71211, name=markos>
- >>> server_key = conn.ex_list_keypairs(key_group=1)[0].id
- 70867
- >>> console_keys = conn.ex_list_keypairs(key_group=4)[0]
- <NodeKey: id=71213, name=mistio28434>
- >>> console_key = conn.ex_list_keypairs(key_group=4)[0].id
- 70907
- >>> node = conn.create_node(name=name, size=size, image=image, \
- console_key=console_key, server_key=server_key)
-
- We can also create an ssh key, plus a console key and
- deploy node with them
- >>> server_key = conn.ex_create_keypair(name, public_key='123')
- 71211
- >>> console_key = conn.ex_create_keypair(name, key_group=4)
- 71213
-
- We can increase the number of connect attempts to wait until
- the node is created, so that deploy_node has ip address to
- deploy the script
- We can also specify the location
- >>> location = conn.list_locations()[0]
- >>> node = conn.create_node(name=name,
- >>> ... size=size,
- >>> ... image=image,
- >>> ... console_key=console_key,
- >>> ... server_key=server_key,
- >>> ... connect_attempts=10,
- >>> ... nowait=True,
- >>> ... zone=location.id)
- """
- hostname = kwargs.get('hostname', name)
- service_type = size.id
- image = image.id
- connect_attempts = int(kwargs.get('connect_attempts',
- CONNECT_ATTEMPTS))
-
- data = {'name': name,
- 'hostname': hostname,
- 'service_type': service_type,
- 'image': image,
- 'server_key': server_key,
- 'console_key': console_key,
- 'zone': zone
- }
-
- params = urlencode(data)
- try:
- node = self.connection.request('/server/cloud/', data=params,
- method='POST')
- except Exception:
- e = sys.exc_info()[1]
- raise Exception("Failed to create node %s" % e)
- node = Node(id='', name=name, state=NodeState.UNKNOWN, public_ips=[],
- private_ips=[], driver=self)
-
- nowait = kwargs.get('ex_wait', False)
- if not nowait:
- return node
- else:
- # try to get the created node public ips, for use in deploy_node
- # At this point we don't have the id of the newly created Node,
- # so search name in nodes
- created_node = False
- while connect_attempts > 0:
- nodes = self.list_nodes()
- created_node = [c_node for c_node in nodes if
- c_node.name == name]
- if created_node:
- return created_node[0]
- else:
- time.sleep(60)
- connect_attempts = connect_attempts - 1
- return node
-
- def _to_node(self, data):
- """Convert node in Node instances
- """
-
- state = NODE_STATE_MAP.get(data.get('power_status'), '4')
- public_ips = []
- private_ips = []
- ip_addresses = data.get('ipaddresses', '')
- # E.g. "ipaddresses": "198.120.14.6, 10.132.60.1"
- if ip_addresses:
- for ip in ip_addresses.split(','):
- ip = ip.replace(' ', '')
- if is_private_subnet(ip):
- private_ips.append(ip)
- else:
- public_ips.append(ip)
- extra = {
- 'zone_data': data.get('zone'),
- 'zone': data.get('zone', {}).get('name'),
- 'image': data.get('image', {}).get('friendly_name'),
- 'create_time': data.get('create_time'),
- 'network_ports': data.get('network_ports'),
- 'is_console_enabled': data.get('is_console_enabled'),
- 'service_type': data.get('service_type', {}).get('friendly_name'),
- 'hostname': data.get('hostname')
- }
-
- node = Node(id=data.get('id'), name=data.get('name'), state=state,
- public_ips=public_ips, private_ips=private_ips,
- driver=self, extra=extra)
- return node
-
- def _to_key(self, data):
- return NodeKey(id=data.get('id'),
- name=data.get('name'),
- password=data.get('password'),
- key_group=data.get('key_group'),
- public_key=data.get('public_key'))
-
- def random_password(self, size=8):
- value = os.urandom(size)
- password = binascii.hexlify(value).decode('ascii')
- return password[:size]
http://git-wip-us.apache.org/repos/asf/libcloud/blob/8afcda91/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/ntta.py
----------------------------------------------------------------------
diff --git a/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/ntta.py b/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/ntta.py
deleted file mode 100644
index 5ef5cb9..0000000
--- a/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/ntta.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""
-NTT America Driver
-"""
-
-from libcloud.compute.providers import Provider
-from libcloud.common.dimensiondata import (DimensionDataConnection,
- API_ENDPOINTS)
-from libcloud.compute.drivers.dimensiondata import DimensionDataNodeDriver
-
-DEFAULT_REGION = 'ntta-na'
-
-
-class NTTAmericaNodeDriver(DimensionDataNodeDriver):
- """
- NTT America node driver, based on Dimension Data driver
- """
-
- selected_region = None
- connectionCls = DimensionDataConnection
- name = 'NTTAmerica'
- website = 'http://www.nttamerica.com/'
- type = Provider.NTTA
- features = {'create_node': ['password']}
- api_version = 1.0
-
- def __init__(self, key, secret=None, secure=True, host=None, port=None,
- api_version=None, region=DEFAULT_REGION, **kwargs):
-
- if region not in API_ENDPOINTS:
- raise ValueError('Invalid region: %s' % (region))
-
- self.selected_region = API_ENDPOINTS[region]
-
- super(NTTAmericaNodeDriver, self).__init__(
- key=key,
- secret=secret,
- secure=secure,
- host=host,
- port=port,
- api_version=api_version,
- region=region,
- **kwargs)
http://git-wip-us.apache.org/repos/asf/libcloud/blob/8afcda91/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/onapp.py
----------------------------------------------------------------------
diff --git a/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/onapp.py b/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/onapp.py
deleted file mode 100644
index 2b0811e..0000000
--- a/apache-libcloud-1.0.0rc2/libcloud/compute/drivers/onapp.py
+++ /dev/null
@@ -1,406 +0,0 @@
-import json
-
-from libcloud.compute.base import Node, NodeDriver
-from libcloud.common.onapp import OnAppConnection
-from libcloud.utils.networking import is_private_subnet
-from libcloud.compute.providers import Provider
-
-
-__all__ = [
- "OnAppNodeDriver"
-]
-
-"""
-Define the extra dictionary for specific resources
-"""
-RESOURCE_EXTRA_ATTRIBUTES_MAP = {
- "node": {
- "add_to_marketplace": {
- "key_name": "add_to_marketplace",
- "transform_func": bool
- },
- "admin_note": {
- "key_name": "admin_note",
- "transform_func": str
- },
- "allow_resize_without_reboot": {
- "key_name": "allow_resize_without_reboot",
- "transform_func": bool
- },
- "allowed_hot_migrate": {
- "key_name": "allowed_hot_migrate",
- "transform_func": bool
- },
- "allowed_swap": {
- "key_name": "allowed_swap",
- "transform_func": bool
- },
- "booted": {
- "key_name": "booted",
- "transform_func": bool
- },
- "built": {
- "key_name": "built",
- "transform_func": bool
- },
- "cpu_priority": {
- "key_name": "cpu_priority",
- "transform_func": int
- },
- "cpu_shares": {
- "key_name": "cpu_shares",
- "transform_func": int
- },
- "cpu_sockets": {
- "key_name": "cpu_sockets",
- "transform_func": int
- },
- "cpu_threads": {
- "key_name": "cpu_threads",
- "transform_func": int
- },
- "cpu_units": {
- "key_name": "cpu_units",
- "transform_func": int
- },
- "cpus": {
- "key_name": "cpus",
- "transform_func": int
- },
- "created_at": {
- "key_name": "created_at",
- "transform_func": str
- },
- "customer_network_id": {
- "key_name": "customer_network_id",
- "transform_func": str
- },
- "deleted_at": {
- "key_name": "deleted_at",
- "transform_func": str
- },
- "edge_server_type": {
- "key_name": "edge_server_type",
- "transform_func": str
- },
- "enable_autoscale": {
- "key_name": "enable_autoscale",
- "transform_func": bool
- },
- "enable_monitis": {
- "key_name": "enable_monitis",
- "transform_func": bool
- },
- "firewall_notrack": {
- "key_name": "firewall_notrack",
- "transform_func": bool
- },
- "hostname": {
- "key_name": "hostname",
- "transform_func": str
- },
- "hypervisor_id": {
- "key_name": "hypervisor_id",
- "transform_func": int
- },
- "id": {
- "key_name": "id",
- "transform_func": int
- },
- "initial_root_password": {
- "key_name": "initial_root_password",
- "transform_func": str
- },
- "initial_root_password_encrypted": {
- "key_name": "initial_root_password_encrypted",
- "transform_func": bool
- },
- "local_remote_access_ip_address": {
- "key_name": "local_remote_access_ip_address",
- "transform_func": str
- },
- "local_remote_access_port": {
- "key_name": "local_remote_access_port",
- "transform_func": int
- },
- "locked": {
- "key_name": "locked",
- "transform_func": bool
- },
- "memory": {
- "key_name": "memory",
- "transform_func": int
- },
- "min_disk_size": {
- "key_name": "min_disk_size",
- "transform_func": int
- },
- "monthly_bandwidth_used": {
- "key_name": "monthly_bandwidth_used",
- "transform_func": int
- },
- "note": {
- "key_name": "note",
- "transform_func": str
- },
- "operating_system": {
- "key_name": "operating_system",
- "transform_func": str
- },
- "operating_system_distro": {
- "key_name": "operating_system_distro",
- "transform_func": str
- },
- "preferred_hvs": {
- "key_name": "preferred_hvs",
- "transform_func": list
- },
- "price_per_hour": {
- "key_name": "price_per_hour",
- "transform_func": float
- },
- "price_per_hour_powered_off": {
- "key_name": "price_per_hour_powered_off",
- "transform_func": float
- },
- "recovery_mode": {
- "key_name": "recovery_mode",
- "transform_func": bool
- },
- "remote_access_password": {
- "key_name": "remote_access_password",
- "transform_func": str
- },
- "service_password": {
- "key_name": "service_password",
- "transform_func": str
- },
- "state": {
- "key_name": "state",
- "transform_func": str
- },
- "storage_server_type": {
- "key_name": "storage_server_type",
- "transform_func": str
- },
- "strict_virtual_machine_id": {
- "key_name": "strict_virtual_machine_id",
- "transform_func": str
- },
- "support_incremental_backups": {
- "key_name": "support_incremental_backups",
- "transform_func": bool
- },
- "suspended": {
- "key_name": "suspended",
- "transform_func": bool
- },
- "template_id": {
- "key_name": "template_id",
- "transform_func": int
- },
- "template_label": {
- "key_name": "template_label",
- "transform_func": str
- },
- "total_disk_size": {
- "key_name": "total_disk_size",
- "transform_func": int
- },
- "updated_at": {
- "key_name": "updated_at",
- "transform_func": str
- },
- "user_id": {
- "key_name": "user_id",
- "transform_func": int
- },
- "vip": {
- "key_name": "vip",
- "transform_func": bool
- },
- "xen_id": {
- "key_name": "xen_id",
- "transform_func": int
- }
- }
-}
-
-
-class OnAppNodeDriver(NodeDriver):
- """
- Base OnApp node driver.
- """
-
- connectionCls = OnAppConnection
- type = Provider.ONAPP
- name = 'OnApp'
- website = 'http://onapp.com/'
-
- def create_node(self, name, ex_memory, ex_cpus, ex_cpu_shares,
- ex_hostname, ex_template_id, ex_primary_disk_size,
- ex_swap_disk_size, ex_required_virtual_machine_build=1,
- ex_required_ip_address_assignment=1, **kwargs):
- """
- Add a VS
-
- :param kwargs: All keyword arguments to create a VS
- :type kwargs: ``dict``
-
- :rtype: :class:`OnAppNode`
- """
- server_params = dict(
- label=name,
- memory=ex_memory,
- cpus=ex_cpus,
- cpu_shares=ex_cpu_shares,
- hostname=ex_hostname,
- template_id=ex_template_id,
- primary_disk_size=ex_primary_disk_size,
- swap_disk_size=ex_swap_disk_size,
- required_virtual_machine_build=ex_required_virtual_machine_build,
- required_ip_address_assignment=ex_required_ip_address_assignment,
- rate_limit=kwargs.get("rate_limit")
- )
-
- server_params.update(OnAppNodeDriver._create_args_to_params(**kwargs))
- data = json.dumps({"virtual_machine": server_params})
-
- response = self.connection.request(
- "/virtual_machines.json",
- data=data,
- headers={
- "Content-type": "application/json"},
- method="POST")
-
- return self._to_node(response.object["virtual_machine"])
-
- def destroy_node(self,
- node,
- ex_convert_last_backup=0,
- ex_destroy_all_backups=0):
- """
- Delete a VS
-
- :param node: OnApp node
- :type node: :class: `OnAppNode`
-
- :param convert_last_backup: set 1 to convert the last VS's backup to
- template, otherwise set 0
- :type convert_last_backup: ``int``
-
- :param destroy_all_backups: set 1 to destroy all existing backups of
- this VS, otherwise set 0
- :type destroy_all_backups: ``int``
- """
- server_params = {
- "convert_last_backup": ex_convert_last_backup,
- "destroy_all_backups": ex_destroy_all_backups
- }
- action = "/virtual_machines/{identifier}.json".format(
- identifier=node.id)
-
- self.connection.request(action, params=server_params, method="DELETE")
- return True
-
- def list_nodes(self):
- """
- List all VS
-
- :rtype: ``list`` of :class:`OnAppNode`
- """
- response = self.connection.request("/virtual_machines.json")
- nodes = []
- for vm in response.object:
- nodes.append(self._to_node(vm["virtual_machine"]))
- return nodes
-
- #
- # Helper methods
- #
-
- def _to_node(self, data):
- identifier = data["identifier"]
- name = data["label"]
- private_ips = []
- public_ips = []
- for ip in data["ip_addresses"]:
- address = ip["ip_address"]['address']
- if is_private_subnet(address):
- private_ips.append(address)
- else:
- public_ips.append(address)
-
- extra = OnAppNodeDriver._get_extra_dict(
- data, RESOURCE_EXTRA_ATTRIBUTES_MAP["node"]
- )
- return Node(identifier,
- name,
- extra['state'],
- public_ips,
- private_ips,
- self,
- extra=extra)
-
- @staticmethod
- def _get_extra_dict(response, mapping):
- """
- Extract attributes from the element based on rules provided in the
- mapping dictionary.
-
- :param response: The JSON response to parse the values from.
- :type response: ``dict``
-
- :param mapping: Dictionary with the extra layout
- :type mapping: ``dict``
-
- :rtype: ``dict``
- """
- extra = {}
- for attribute, values in mapping.items():
- transform_func = values["transform_func"]
- value = response.get(values["key_name"])
-
- extra[attribute] = transform_func(value) if value else None
- return extra
-
- @staticmethod
- def _create_args_to_params(**kwargs):
- """
- Extract server params from keyword args to create a VS
-
- :param kwargs: keyword args
- :return: ``dict``
- """
- params = [
- "ex_cpu_sockets",
- "ex_cpu_threads",
- "ex_enable_autoscale",
- "ex_data_store_group_primary_id",
- "ex_data_store_group_swap_id",
- "ex_hypervisor_group_id",
- "ex_hypervisor_id",
- "ex_initial_root_password",
- "ex_note",
- "ex_primary_disk_min_iops",
- "ex_primary_network_id",
- "ex_primary_network_group_id",
- "ex_recipe_ids",
- "ex_required_automatic_backup",
- "ex_required_virtual_machine_startup",
- "ex_required_virtual_machine_startup",
- "ex_selected_ip_address_id",
- "ex_swap_disk_min_iops",
- "ex_type_of_format",
- "ex_custom_recipe_variables",
- "ex_licensing_key",
- "ex_licensing_server_id",
- "ex_licensing_type",
- ]
- server_params = {}
-
- for p in params:
- value = kwargs.get(p)
- if value:
- server_params[p[3:]] = value
- return server_params