def _apply_rubs(self, node, steps): """ Does the actual job over SSH :param node: the node to be polished :type node: :class:`libcloud.compute.base.Node` :param steps: the various steps of the rubbing :type steps: :class:`libcloud.compute.deployment.MultiStepDeployment` :return: ``True`` if everything went fine, ``False`` otherwise :rtype: ``bool`` """ if node is None or node.state != NodeState.RUNNING: logging.info("- skipped - node is not running") return False # select the address to use if len(node.public_ips) > 0: target_ip = node.public_ips[0] elif node.extra['ipv6']: target_ip = node.extra['ipv6'] else: target_ip = node.private_ips[0] # use libcloud to communicate with remote nodes session = SSHClient(hostname=target_ip, port=22, username='******', password=self.secret, key_files=None, timeout=9) try: session.connect() if self.engine.safeMode: logging.info("- no actual ssh interaction in safe mode") else: node = steps.run(node, session) except Exception as feedback: logging.info("Error: unable to rub '{}' at '{}'!".format( node.name, target_ip)) logging.error(str(feedback)) logging.info("- failed") result = False else: result = True try: session.close() except: pass return result
def _apply_rubs(self, node, steps): """ Does the actual job over SSH :param node: the node to be polished :type node: :class:`libcloud.compute.base.Node` :param steps: the various steps of the rubbing :type steps: :class:`libcloud.compute.deployment.MultiStepDeployment` :return: ``True`` if everything went fine, ``False`` otherwise :rtype: ``bool`` """ if node is None or node.state != NodeState.RUNNING: logging.info("- skipped - node is not running") return False # select the address to use if len(node.public_ips) > 0: target_ip = node.public_ips[0] elif node.extra['ipv6']: target_ip = node.extra['ipv6'] else: target_ip = node.private_ips[0] # use libcloud to communicate with remote nodes session = SSHClient(hostname=target_ip, port=22, username='******', password=self.secret, key_files=None, timeout=6) try: session.connect() node = steps.run(node, session) except Exception as feedback: logging.info("Error: unable to rub '{}' at '{}'!".format(node.name, target_ip)) logging.error(str(feedback)) logging.info("- failed") result = False else: result = True try: session.close() except: pass return result
def test_usecase(self): client = SSHClient(hostname=self.ip_addresses[0], timeout=self.sshConnectTimeout) self.driver._ssh_client_connect(ssh_client=client, wait_period=self.wait_period, timeout=self.sshTimeout) cmd = '/bin/true' stdout, stderr, status = client.run(cmd) client.close() self.assertEqual(status, 0) print 'execute:', cmd
def _apply_rubs(self, node, steps): """ Does the actual job over SSH :param node: the node to be polished :type node: :class:`libcloud.compute.base.Node` :param steps: the various steps of the rubbing :type steps: :class:`libcloud.compute.deployment.MultiStepDeployment` :returns: ``bool`` - ``True`` if everything went fine, ``False`` otherwise """ # use libcloud to communicate with remote nodes session = SSHClient(hostname=node.private_ips[0], port=22, username='******', password=self.secret, key_files=None, timeout=15) try: session.connect() node = steps.run(node, session) except Exception as feedback: logging.info("Error: unable to rub '{}' at '{}'!".format(node.name, node.private_ips[0])) logging.info(str(feedback)) result = False else: result = True try: session.close() except: pass return result
def _apply_prepares(self, node, steps): """ Does the actual job over SSH :param node: the node to be polished :type node: :class:`libcloud.compute.base.Node` :param steps: the various steps of the preparing :type steps: :class:`libcloud.compute.deployment.MultiStepDeployment` :return: ``True`` if everything went fine, ``False`` otherwise :rtype: ``bool`` """ if node is None or node.state != NodeState.RUNNING: plogging.warning("- skipped - node is not running") return False # select the address to use if len(node.public_ips) > 0: target_ip = node.public_ips[0] elif node.extra['ipv6']: target_ip = node.extra['ipv6'] else: target_ip = node.private_ips[0] # guess location of user key path = os.path.expanduser('~/.ssh/id_rsa') # use libcloud to communicate with remote nodes session = SSHClient(hostname=target_ip, port=22, username=self.user, password=self.secret, key_files=path, timeout=9) try: session.connect() except Exception as feedback: plogging.error("Error: unable to prepare '{}' at '{}'!".format( node.name, target_ip)) plogging.error(str(feedback)) plogging.error("- failed") return False while True: try: if self.engine.safeMode: plogging.info("- skipped - no ssh interaction in safe mode") else: node = steps.run(node, session) except Exception as feedback: if 'RESOURCE_BUSY' in str(feedback): time.sleep(10) continue plogging.error("Error: unable to prepare '{}' at '{}'!".format( node.name, target_ip)) plogging.error(str(feedback)) plogging.error("- failed") result = False else: result = True break try: session.close() except: pass return result
def deploy_node(self, **kwargs): """ Create a new node, and start deployment. Depends on a Provider Driver supporting either using a specific password or returning a generated password. This function may raise a L{DeploymentException}, if a create_node call was successful, but there is a later error (like SSH failing or timing out). This exception includes a Node object which you may want to destroy if incomplete deployments are not desirable. @keyword deploy: Deployment to run once machine is online and availble to SSH. @type deploy: L{Deployment} @keyword ssh_username: Optional name of the account which is used when connecting to SSH server (default is root) @type ssh_username: C{str} @keyword ssh_port: Optional SSH server port (default is 22) @type ssh_port: C{int} @keyword ssh_timeout: Optional SSH connection timeout in seconds (default is None) @type ssh_timeout: C{float} See L{NodeDriver.create_node} for more keyword args. >>> from libcloud.compute.drivers.dummy import DummyNodeDriver >>> from libcloud.deployment import ScriptDeployment, MultiStepDeployment >>> from libcloud.compute.base import NodeAuthSSHKey >>> driver = DummyNodeDriver(0) >>> key = NodeAuthSSHKey('...') # read from file >>> script = ScriptDeployment("yum -y install emacs strace tcpdump") >>> msd = MultiStepDeployment([key, script]) >>> def d(): ... try: ... node = driver.deploy_node(deploy=msd) ... except NotImplementedError: ... print "not implemented for dummy driver" >>> d() not implemented for dummy driver Deploy node is typically not overridden in subclasses. The existing implementation should be able to handle most such. """ # TODO: support ssh keys # FIX: this method is too long and complicated WAIT_PERIOD = 3 password = None if 'generates_password' not in self.features["create_node"]: if 'password' not in self.features["create_node"]: raise NotImplementedError, \ 'deploy_node not implemented for this driver' if not kwargs.has_key('auth'): kwargs['auth'] = NodeAuthPassword(os.urandom(16).encode('hex')) password = kwargs['auth'].password node = self.create_node(**kwargs) try: if 'generates_password' in self.features["create_node"]: password = node.extra.get('password') start = time.time() end = start + (60 * 15) # FIX: this should be soft-coded while time.time() < end: # need to wait until we get a public IP address. # TODO: there must be a better way of doing this time.sleep(WAIT_PERIOD) nodes = self.list_nodes() nodes = filter(lambda n: n.uuid == node.uuid, nodes) if len(nodes) == 0: raise DeploymentError(node, ("Booted node[%s] " % node + "is missing from list_nodes.")) if len(nodes) > 1: raise DeploymentError( node, ("Booted single node[%s], " % node + "but multiple nodes have same UUID")) node = nodes[0] if (node.public_ip is not None and node.public_ip != "" and node.state == NodeState.RUNNING): break ssh_username = kwargs.get('ssh_username', 'root') ssh_port = kwargs.get('ssh_port', 22) ssh_timeout = kwargs.get('ssh_timeout', 20) client = SSHClient(hostname=node.public_ip[0], port=ssh_port, username=ssh_username, password=password, timeout=ssh_timeout) while time.time() < end: try: client.connect() except (IOError, socket.gaierror, socket.error), e: # Retry if a connection is refused or timeout # occured client.close() time.sleep(WAIT_PERIOD) continue max_tries, tries = 3, 0 while tries < max_tries: try: n = kwargs["deploy"].run(node, client) client.close() raise except Exception, e: tries += 1 if tries >= max_tries: raise DeploymentError( node, 'Failed after %d tries' % (max_tries))
def _apply_prepares(self, node, steps): """ Does the actual job over SSH :param node: the node to be polished :type node: :class:`libcloud.compute.base.Node` :param steps: the various steps of the preparing :type steps: ``list`` of ``dict`` :return: ``True`` if everything went fine, ``False`` otherwise :rtype: ``bool`` """ if node is None or node.state != NodeState.RUNNING: plogging.warning("- skipped - node is not running") return False # select the address to use if len(node.public_ips) > 0: target_ip = node.public_ips[0] elif node.extra['ipv6']: target_ip = node.extra['ipv6'] else: target_ip = node.private_ips[0] # use libcloud to communicate with remote nodes session = SSHClient(hostname=target_ip, port=22, username=self.user, password=self.secret, key_files=self.key_files, timeout=10) repeats = 0 while True: try: session.connect() break except Exception as feedback: repeats += 1 if repeats > 5: plogging.error( "Error: can not connect to '{}'!".format(target_ip)) plogging.error("- failed to connect") return False plogging.debug(str(feedback)) plogging.debug( "- connection {} failed, retrying".format(repeats)) time.sleep(10) continue while True: try: if self.engine.safeMode: plogging.info( "- skipped - no ssh interaction in safe mode") else: for step in steps: plogging.info('- {}'.format(step['description'])) step['genius'].run(node, session) except Exception as feedback: if 'RESOURCE_BUSY' in str(feedback): time.sleep(10) continue plogging.error("Error: unable to prepare '{}' at '{}'!".format( node.name, target_ip)) plogging.error(str(feedback)) plogging.error("- failed") result = False else: result = True break try: session.close() except: pass return result
def _apply_prepares(self, node, steps): """ Does the actual job over SSH :param node: the node to be polished :type node: :class:`libcloud.compute.base.Node` :param steps: the various steps of the preparing :type steps: :class:`libcloud.compute.deployment.MultiStepDeployment` :return: ``True`` if everything went fine, ``False`` otherwise :rtype: ``bool`` """ if node is None or node.state != NodeState.RUNNING: plogging.warning("- skipped - node is not running") return False # select the address to use if len(node.public_ips) > 0: target_ip = node.public_ips[0] elif node.extra['ipv6']: target_ip = node.extra['ipv6'] else: target_ip = node.private_ips[0] # guess location of user key path = os.path.expanduser('~/.ssh/id_rsa') # use libcloud to communicate with remote nodes session = SSHClient(hostname=target_ip, port=22, username=self.user, password=self.secret, key_files=path, timeout=9) try: session.connect() except Exception as feedback: plogging.error("Error: unable to prepare '{}' at '{}'!".format( node.name, target_ip)) plogging.error(str(feedback)) plogging.error("- failed") return False while True: try: if self.engine.safeMode: plogging.info( "- skipped - no ssh interaction in safe mode") else: node = steps.run(node, session) except Exception as feedback: if 'RESOURCE_BUSY' in str(feedback): time.sleep(10) continue plogging.error("Error: unable to prepare '{}' at '{}'!".format( node.name, target_ip)) plogging.error(str(feedback)) plogging.error("- failed") result = False else: result = True break try: session.close() except: pass return result
def deploy_node(self, **kwargs): """ Create a new node, and start deployment. Depends on a Provider Driver supporting either using a specific password or returning a generated password. This function may raise a L{DeploymentException}, if a create_node call was successful, but there is a later error (like SSH failing or timing out). This exception includes a Node object which you may want to destroy if incomplete deployments are not desirable. @keyword deploy: Deployment to run once machine is online and availble to SSH. @type deploy: L{Deployment} @keyword ssh_username: Optional name of the account which is used when connecting to SSH server (default is root) @type ssh_username: C{str} @keyword ssh_port: Optional SSH server port (default is 22) @type ssh_port: C{int} See L{NodeDriver.create_node} for more keyword args. >>> from libcloud.compute.drivers.dummy import DummyNodeDriver >>> from libcloud.deployment import ScriptDeployment, MultiStepDeployment >>> from libcloud.compute.base import NodeAuthSSHKey >>> driver = DummyNodeDriver(0) >>> key = NodeAuthSSHKey('...') # read from file >>> script = ScriptDeployment("yum -y install emacs strace tcpdump") >>> msd = MultiStepDeployment([key, script]) >>> def d(): ... try: ... node = driver.deploy_node(deploy=msd) ... except NotImplementedError: ... print "not implemented for dummy driver" >>> d() not implemented for dummy driver Deploy node is typically not overridden in subclasses. The existing implementation should be able to handle most such. """ # TODO: support ssh keys WAIT_PERIOD=3 password = None if 'generates_password' not in self.features["create_node"]: if 'password' not in self.features["create_node"]: raise NotImplementedError, \ 'deploy_node not implemented for this driver' if not kwargs.has_key('auth'): kwargs['auth'] = NodeAuthPassword(os.urandom(16).encode('hex')) password = kwargs['auth'].password node = self.create_node(**kwargs) try: if 'generates_password' in self.features["create_node"]: password = node.extra.get('password') start = time.time() end = start + (60 * 15) while time.time() < end: # need to wait until we get a public IP address. # TODO: there must be a better way of doing this time.sleep(WAIT_PERIOD) nodes = self.list_nodes() nodes = filter(lambda n: n.uuid == node.uuid, nodes) if len(nodes) == 0: raise DeploymentError(node, "Booted node[%s] is missing form list_nodes." % node) if len(nodes) > 1: raise DeploymentError(node, "Booted single node[%s], but multiple nodes have same UUID"% node) node = nodes[0] if node.public_ip is not None and node.public_ip != "" and node.state == NodeState.RUNNING: break ssh_username = kwargs.get('ssh_username', 'root') ssh_port = kwargs.get('ssh_port', 22) client = SSHClient(hostname=node.public_ip[0], port=ssh_port, username=ssh_username, password=password) laste = None while time.time() < end: laste = None try: client.connect() break except (IOError, socket.gaierror, socket.error), e: laste = e time.sleep(WAIT_PERIOD) if laste is not None: raise e tries = 3 while tries >= 0: try: n = kwargs["deploy"].run(node, client) client.close() break except Exception, e: tries -= 1 if tries == 0: raise client.connect()
def _apply_prepares(self, node, steps): """ Does the actual job over SSH :param node: the node to be polished :type node: :class:`libcloud.compute.base.Node` :param steps: the various steps of the preparing :type steps: ``list`` of ``dict`` :return: ``True`` if everything went fine, ``False`` otherwise :rtype: ``bool`` """ if node is None or node.state != NodeState.RUNNING: plogging.warning("- skipped - node is not running") return False # select the address to use if len(node.public_ips) > 0: target_ip = node.public_ips[0] elif node.extra['ipv6']: target_ip = node.extra['ipv6'] else: target_ip = node.private_ips[0] # use libcloud to communicate with remote nodes session = SSHClient(hostname=target_ip, port=22, username=self.user, password=self.secret, key_files=self.key_files, timeout=10) repeats = 0 while True: try: session.connect() break except Exception as feedback: repeats += 1 if repeats > 5: plogging.error("Error: can not connect to '{}'!".format( target_ip)) plogging.error("- failed to connect") return False plogging.debug(str(feedback)) plogging.debug("- connection {} failed, retrying".format(repeats)) time.sleep(10) continue while True: try: if self.engine.safeMode: plogging.info("- skipped - no ssh interaction in safe mode") else: for step in steps: plogging.info('- {}'.format(step['description'])) step['genius'].run(node, session) except Exception as feedback: if 'RESOURCE_BUSY' in str(feedback): time.sleep(10) continue plogging.error("Error: unable to prepare '{}' at '{}'!".format( node.name, target_ip)) plogging.error(str(feedback)) plogging.error("- failed") result = False else: result = True break try: session.close() except: pass return result