Jelajahi Sumber

Added authenticate method to test provider connectivity.

Nuwan Goonasekera 9 tahun lalu
induk
melakukan
001a67c02c

+ 14 - 0
cloudbridge/cloud/base/provider.py

@@ -8,6 +8,7 @@ from os.path import expanduser
 
 from cloudbridge.cloud.interfaces import CloudProvider
 from cloudbridge.cloud.interfaces.resources import Configuration
+from cloudbridge.cloud.interfaces.resources import ProviderConnectionException
 
 DEFAULT_RESULT_LIMIT = 50
 DEFAULT_WAIT_TIMEOUT = 600
@@ -81,6 +82,19 @@ class BaseCloudProvider(CloudProvider):
     def name(self):
         return str(self.__class__.__name__)
 
+    def authenticate(self):
+        """
+        A basic implementation which simply runs a low impact command to
+        check whether cloud credentials work. Providers should override with
+        more efficient implementations.
+        """
+        try:
+            self.security.key_pairs.list()
+            return True
+        except Exception as e:
+            raise ProviderConnectionException(
+                "Authentication with cloud provider failed: %s" % (e,))
+
     def has_service(self, service_type):
         """
         Checks whether this provider supports a given service.

+ 26 - 0
cloudbridge/cloud/interfaces/provider.py

@@ -54,6 +54,32 @@ class CloudProvider(object):
                   configuration properties.
         """
 
+    @abstractmethod
+    def authenticate(self):
+        """
+        Checks whether a provider can be successfully authenticated with the
+        configured settings. Clients are *not* required to call this method
+        prior to accessing provider services, as most cloud connections are
+        initialized lazily. The authenticate() method will return True if
+        cloudbridge can establish a successful connection to the provider.
+        It will raise an exception with the appropriate error details
+        otherwise.
+
+        Example:
+
+        .. code-block:: python
+
+            try:
+                if provider.authenticate():
+                   print("Provider connection successful")
+            except ProviderConnectionException as e:
+                print("Could not authenticate with provider: %s" % (e, ))
+
+        :rtype: :class:`bool`
+        :return: ``True`` if authentication is successful.
+        """
+        pass
+
     @abstractmethod
     def has_service(self, service_type):
         """

+ 11 - 0
cloudbridge/cloud/interfaces/resources.py

@@ -80,6 +80,17 @@ class InvalidConfigurationException(CloudBridgeBaseException):
     pass
 
 
+class ProviderConnectionException(CloudBridgeBaseException):
+
+    """
+    Marker interface for connection errors to a cloud provider.
+    Thrown when cloudbridge is unable to connect with a provider,
+    for example, when credentials are incorrect, or connection
+    settings are invalid.
+    """
+    pass
+
+
 class Configuration(dict):
     """
     Represents a cloudbridge configuration object