You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@libcloud.apache.org by GitBox <gi...@apache.org> on 2020/08/30 15:14:52 UTC

[GitHub] [libcloud] Kami commented on a change in pull request #1481: V sphere drv

Kami commented on a change in pull request #1481:
URL: https://github.com/apache/libcloud/pull/1481#discussion_r479781870



##########
File path: libcloud/compute/drivers/vsphere.py
##########
@@ -0,0 +1,1992 @@
+# 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.
+
+"""
+VMware vSphere driver. Uses pyvmomi - https://github.com/vmware/pyvmomi
+Code inspired by https://github.com/vmware/pyvmomi-community-samples
+
+Authors: Dimitris Moraitis, Alex Tsiliris, Markos Gogoulos
+"""
+
+import time
+import logging
+import json
+import base64
+import warnings
+import asyncio
+import ssl
+import functools
+import itertools
+import hashlib
+
+try:
+    from pyVim import connect
+    from pyVmomi import vim, vmodl, VmomiSupport
+    from pyVim.task import WaitForTask
+except ImportError:
+    pyvmomi = None
+
+import atexit
+
+
+from libcloud.common.types import InvalidCredsError, LibcloudError
+from libcloud.compute.base import NodeDriver
+from libcloud.compute.base import Node, NodeSize
+from libcloud.compute.base import NodeImage, NodeLocation
+from libcloud.compute.types import NodeState, Provider
+from libcloud.utils.networking import is_public_subnet
+from libcloud.utils.py3 import httplib
+from libcloud.common.types import ProviderError
+from libcloud.common.exceptions import BaseHTTPError
+from libcloud.common.base import JsonResponse, ConnectionKey
+
+logger = logging.getLogger('libcloud.compute.drivers.vsphere')
+
+
+def recurse_snapshots(snapshot_list):
+    ret = []
+    for s in snapshot_list:
+        ret.append(s)
+        ret += recurse_snapshots(getattr(s, 'childSnapshotList', []))
+    return ret
+
+
+def format_snapshots(snapshot_list):
+    ret = []
+    for s in snapshot_list:
+        ret.append({
+            'id': s.id,
+            'name': s.name,
+            'description': s.description,
+            'created': s.createTime.strftime('%Y-%m-%d %H:%M'),
+            'state': s.state})
+    return ret
+
+
+# 6.5 and older, probably won't work on anything earlier than 4.x
+class VSphereNodeDriver(NodeDriver):
+    name = 'VMware vSphere'
+    website = 'http://www.vmware.com/products/vsphere/'
+    type = Provider.VSPHERE
+
+    NODE_STATE_MAP = {
+        'poweredOn': NodeState.RUNNING,
+        'poweredOff': NodeState.STOPPED,
+        'suspended': NodeState.SUSPENDED,
+    }
+
+    def __init__(self, host, username, password, port=443, ca_cert=None):
+        """Initialize a connection by providing a hostname,
+        username and password
+        """
+        if pyvmomi is None:
+            raise ImportError('Missing "pyvmomi" dependency. '
+                              'You can install it '
+                              'using pip - pip install pyvmomi')
+        self.host = host
+        try:
+            if ca_cert is None:
+                self.connection = connect.SmartConnect(
+                    host=host, port=port, user=username, pwd=password,
+                )
+            else:
+                context = ssl.create_default_context(cafile=ca_cert)
+                self.connection = connect.SmartConnect(
+                    host=host, port=port, user=username, pwd=password,
+                    sslContext=context
+                )
+            atexit.register(connect.Disconnect, self.connection)
+        except Exception as exc:
+            error_message = str(exc).lower()
+            if 'incorrect user name' in error_message:
+                raise InvalidCredsError('Check your username and '
+                                        'password are valid')
+            if 'connection refused' in error_message or 'is not a vim server' \
+                                                        in error_message:
+                raise LibcloudError('Check that the host provided is a '
+                                    'vSphere installation')
+            if 'name or service not known' in error_message:
+                raise LibcloudError(
+                    'Check that the vSphere host is accessible')
+            if 'certificate verify failed' in error_message:
+                # bypass self signed certificates
+                try:
+                    context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
+                    context.verify_mode = ssl.CERT_NONE
+                except ImportError:
+                    raise ImportError('To use self signed certificates, '
+                                      'please upgrade to python 2.7.11 and '
+                                      'pyvmomi 6.0.0+')
+
+                self.connection = connect.SmartConnect(
+                    host=host, port=port, user=username, pwd=password,
+                    sslContext=context
+                )
+                atexit.register(connect.Disconnect, self.connection)
+            else:
+                raise LibcloudError('Cannot connect to vSphere')
+
+    def list_locations(self, ex_show_hosts_in_drs=True):
+        """
+        Lists locations
+        """
+        content = self.connection.RetrieveContent()
+
+        potential_locations = [dc for dc in
+                               content.viewManager.CreateContainerView(
+                                   content.rootFolder, [
+                                       vim.ClusterComputeResource,
+                                       vim.HostSystem],
+                                   recursive=True).view]
+
+        # Add hosts and clusters with DRS enabled
+        locations = []
+        hosts_all = []
+        clusters = []
+        for location in potential_locations:
+            if isinstance(location, vim.HostSystem):
+                hosts_all.append(location)
+            elif isinstance(location, vim.ClusterComputeResource):
+                if location.configuration.drsConfig.enabled:
+                    clusters.append(location)
+        if ex_show_hosts_in_drs:
+            hosts = hosts_all
+        else:
+            hosts_filter = [host for cluster in clusters
+                            for host in cluster.host]
+            hosts = [host for host in hosts_all if host not in hosts_filter]
+
+        for cluster in clusters:
+            locations.append(self._to_location(cluster))
+        for host in hosts:
+            locations.append(self._to_location(host))
+        return locations
+
+    def _to_location(self, data):
+        try:
+            if isinstance(data, vim.HostSystem):
+                extra = {
+                    "type": "host",
+                    "state": data.runtime.connectionState,
+                    "hypervisor": data.config.product.fullName,
+                    "vendor": data.hardware.systemInfo.vendor,
+                    "model": data.hardware.systemInfo.model,
+                    "ram": data.hardware.memorySize,
+                    "cpu": {
+                        "packages": data.hardware.cpuInfo.numCpuPackages,
+                        "cores": data.hardware.cpuInfo.numCpuCores,
+                        "threads": data.hardware.cpuInfo.numCpuThreads,
+                    },
+                    "uptime": data.summary.quickStats.uptime,
+                    "parent": str(data.parent)
+                }
+            elif isinstance(data, vim.ClusterComputeResource):
+                extra = {
+                    "type": "cluster",
+                    "overallStatus": data.overallStatus,
+                    "drs": data.configuration.drsConfig.enabled,
+                    'hosts': [host.name for host in data.host],
+                    'parent': str(data.parent)
+                }
+        except AttributeError as exc:
+            logger.error('Cannot convert location %s: %r' % (data.name, exc))
+            extra = {}
+        return NodeLocation(id=data.name, name=data.name, country=None,
+                            extra=extra, driver=self)
+
+    def ex_list_networks(self):
+        """
+        List networks
+        """
+        content = self.connection.RetrieveContent()
+        networks = content.viewManager.CreateContainerView(
+            content.rootFolder,
+            [vim.Network],
+            recursive=True
+        ).view
+
+        return [self._to_network(network) for network in networks]
+
+    def _to_network(self, data):
+        summary = data.summary
+        extra = {
+            'hosts': [h.name for h in data.host],
+            'ip_pool_name': summary.ipPoolName,
+            'ip_pool_id': summary.ipPoolId,
+            'accessible': summary.accessible
+        }
+        return VSphereNetwork(id=data.name, name=data.name, extra=extra)
+
+    def list_sizes(self):
+        """
+        Returns sizes
+        """
+        return []
+
+    def list_images(self, location=None, folder_ids=[]):

Review comment:
       Please don't default to a mutable value and do ``folder_ids=None`` and then inside the method ``folder_ids = folder_ids or []``.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org