def check_heal(nodes_to_monitor, depl_id):
    if cooldown():
        print('Exiting...\n')
        exit(0)
    c = CloudifyClient('localhost')
    c_influx = InfluxDBClient(host='localhost', port=8086, database='cloudify')
    f = open('/home/ubuntu/logfile', 'w')
    f.write('in check heal\n')
    c = CloudifyClient('localhost')
    # compare influx data (monitoring) to cloudify desired state

    for node_name in nodes_to_monitor:
        instances = c.node_instances.list(depl_id, node_name)
        #        f.write('instances{0}\n'.format(instances))
        for instance in instances:
            q_string='SELECT MEAN(value) FROM /' + depl_id + '\.' + node_name + '\.' + instance.id + '\.cpu_total_system/ GROUP BY time(10s) '\
                     'WHERE  time > now() - 40s'
            f.write('query string is{0}\n'.format(q_string))
            try:
                result = c_influx.query(q_string)
                f.write('result is {0} \n'.format(result))
                if not result:
                    open('/home/ubuntu/cooldown', 'a').close()
                    utime('/home/ubuntu/cooldown', None)
                    execution_id = c.executions.start(depl_id, 'heal',
                                                      {'node_id': instance.id})
            except InfluxDBClientError as ee:
                f.write('DBClienterror {0}\n'.format(str(ee)))
                f.write('instance id is {0}\n'.format(instance))
            except Exception as e:
                f.write(str(e))
    def create_client(self, headers=None):
        client = CloudifyClient(host='localhost',
                                headers=headers)
        mock_http_client = MockHTTPClient(self.app,
                                          headers=headers,
                                          file_server=self.file_server)
        client._client = mock_http_client
        client.blueprints.api = mock_http_client
        client.deployments.api = mock_http_client
        client.deployments.outputs.api = mock_http_client
        client.deployment_modifications.api = mock_http_client
        client.executions.api = mock_http_client
        client.nodes.api = mock_http_client
        client.node_instances.api = mock_http_client
        client.manager.api = mock_http_client
        client.evaluate.api = mock_http_client
        client.tokens.api = mock_http_client
        client.events.api = mock_http_client
        # only exists in v2 and above
        if CLIENT_API_VERSION != 'v1':
            client.plugins.api = mock_http_client
            client.snapshots.api = mock_http_client

            # only exists in v2.1 and above
            if CLIENT_API_VERSION != 'v2':
                client.maintenance_mode.api = mock_http_client
                client.deployment_updates.api = mock_http_client

        return client
Esempio n. 3
0
    def create_client(self, headers=None):
        client = CloudifyClient(host='localhost', headers=headers)
        mock_http_client = MockHTTPClient(self.app, headers=headers)
        client._client = mock_http_client
        client.blueprints.api = mock_http_client
        client.deployments.api = mock_http_client
        client.deployments.outputs.api = mock_http_client
        client.deployment_modifications.api = mock_http_client
        client.executions.api = mock_http_client
        client.nodes.api = mock_http_client
        client.node_instances.api = mock_http_client
        client.manager.api = mock_http_client
        client.evaluate.api = mock_http_client
        client.tokens.api = mock_http_client
        client.events.api = mock_http_client
        # only exists in v2 and above
        if CLIENT_API_VERSION != 'v1':
            client.plugins.api = mock_http_client
            client.snapshots.api = mock_http_client

            # only exists in v2.1 and above
            if CLIENT_API_VERSION != 'v2':
                client.maintenance_mode.api = mock_http_client
                client.deployment_updates.api = mock_http_client

        return client
Esempio n. 4
0
    def create_client(cls, headers=None, app=None):
        if app is None:
            app = cls.app
        client = CloudifyClient(host='localhost', headers=headers)
        mock_http_client = MockHTTPClient(app,
                                          headers=headers,
                                          root_path=cls.tmpdir)
        client._client = mock_http_client
        client.blueprints.api = mock_http_client
        client.deployments.api = mock_http_client
        client.deployments.outputs.api = mock_http_client
        client.deployment_modifications.api = mock_http_client
        client.executions.api = mock_http_client
        client.nodes.api = mock_http_client
        client.node_instances.api = mock_http_client
        client.manager.api = mock_http_client
        client.evaluate.api = mock_http_client
        client.tokens.api = mock_http_client
        client.events.api = mock_http_client
        # only exists in v2 and above
        if CLIENT_API_VERSION != 'v1':
            client.plugins.api = mock_http_client
            client.snapshots.api = mock_http_client

            # only exists in v2.1 and above
            if CLIENT_API_VERSION != 'v2':
                client.maintenance_mode.api = mock_http_client
                client.deployment_updates.api = mock_http_client

                # only exists in v3 and above
                if CLIENT_API_VERSION != 'v2.1':
                    client.tenants.api = mock_http_client
                    client.user_groups.api = mock_http_client
                    client.users.api = mock_http_client
                    client.ldap.api = mock_http_client
                    client.secrets.api = mock_http_client

                    # only exists in v3.1 and above
                    if CLIENT_API_VERSION != 'v3':
                        client.deployments.capabilities.api = mock_http_client
                        client.agents.api = mock_http_client
                        client.tasks_graphs.api = mock_http_client
                        client.operations.api = mock_http_client
                        client.plugins_update.api = mock_http_client
                        client.sites.api = mock_http_client
                        client.inter_deployment_dependencies.api = \
                            mock_http_client
                        client.deployments_labels.api = mock_http_client
                        client.blueprints_filters.api = mock_http_client
                        client.deployments_filters.api = mock_http_client
                        client.deployment_groups.api = mock_http_client
                        client.execution_groups.api = mock_http_client
                        client.execution_schedules.api = mock_http_client
                        client.blueprints_labels.api = mock_http_client
                        client.workflows.api = mock_http_client

        return client
Esempio n. 5
0
    def setUp(self):
        super(CliCommandTest, self).setUp()
        logdir = os.path.dirname(env.DEFAULT_LOG_FILE)
        env.profile = env.ProfileContext()
        cfy.invoke('init -r')
        # create log folder
        if not os.path.exists(logdir):
            os.makedirs(logdir)

        self.client = CloudifyClient()

        def get_mock_rest_client(*args, **kwargs):
            if 'tenant_name' in kwargs:
                self.client._client.headers[CLOUDIFY_TENANT_HEADER] = \
                    kwargs['tenant_name']
            return self.client

        self.original_utils_get_rest_client = env.get_rest_client
        env.get_rest_client = get_mock_rest_client
        self.original_utils_get_cwd = utils.get_cwd
        utils.get_cwd = lambda: env.CLOUDIFY_WORKDIR
        self.original_utils_os_getcwd = utils_os.getcwd
        utils_os.getcwd = lambda: env.CLOUDIFY_WORKDIR
        # reset in case a test set it
        set_global_json_output(False)
Esempio n. 6
0
def get_rest_client(rest_host,
                    rest_port,
                    rest_token,
                    rest_tenant,
                    ssl_cert_path,
                    bypass_maintenance_mode=False):

    headers = {}
    if bypass_maintenance_mode:
        headers['X-BYPASS-MAINTENANCE'] = 'true'

    for value, name in [(rest_token, 'auth token'),
                        (rest_tenant, 'tenant'),
                        (ssl_cert_path, 'SSL Cert path')]:
        assert value, 'REST {0} is missing! It is required to ' \
                      'create a REST client for a secured ' \
                      'manager [{1}]'.format(name, rest_host)

    return CloudifyClient(
        host=rest_host,
        protocol=SECURED_PROTOCOL,
        port=rest_port,
        headers=headers,
        token=rest_token,
        tenant=rest_tenant,
        cert=ssl_cert_path
    )
Esempio n. 7
0
def create_rest_client(**kwargs):
    # Doing it with kwargs instead of arguments with default values to allow
    # not passing args (which will then use the default values), or explicitly
    # passing None (or False) which will then be passed as-is to the Client

    username = kwargs.get('username', get_manager_username())
    password = kwargs.get('password', get_manager_password())
    tenant = kwargs.get('tenant', get_manager_tenant())
    token = kwargs.get('token')
    rest_port = kwargs.get('rest_port',
                           os.environ.get(constants.CLOUDIFY_REST_PORT, 80))
    rest_protocol = kwargs.get('rest_protocol',
                               'https' if rest_port == '443' else 'http')
    cert_path = kwargs.get('cert_path', cli_env.get_ssl_cert())
    trust_all = kwargs.get('trust_all', cli_env.get_ssl_trust_all())

    headers = create_auth_header(username, password, token, tenant)

    return CloudifyClient(
            host=get_manager_ip(),
            port=rest_port,
            protocol=rest_protocol,
            headers=headers,
            trust_all=trust_all,
            cert=cert_path)
Esempio n. 8
0
def check_replationship(deployment):

    client = CloudifyClient('185.98.149.80')

    depl_id = client.deployments.get(deployment).id
    print('<<< Deployment : ' + depl_id + ' >>>\n')

    deployment_nodes = client.nodes.list(deployment_id=depl_id)

    for node in deployment_nodes:
        print('## node : ' + node.id + ' ##')

        #        if 'FortinetFireWall' in node.id:
        instances = client.node_instances.list(deployment_id=depl_id,
                                               node_name=node.id)
        for instance in instances:
            print('<< instance id : ' + instance.id + ' >>')

            for relationship in instance.relationships:
                #                   if 'connected_to_port' in relationship.get('type'):
                print 'Node relationship --> ',
                print relationship.get('target_name'), relationship.get(
                    'target_id'), '\n'

                getTargetProps(client, depl_id, relationship.get('target_id'))
 def __init__(self, port, file_server_dir, file_server_base_uri,
              file_server_blueprints_folder, file_server_deployments_folder,
              file_server_uploaded_blueprints_folder,
              file_server_resources_uri, rest_service_log_level,
              rest_service_log_path, rest_service_log_file_size_MB,
              rest_service_log_files_backup_count, securest_log_level,
              securest_log_file, securest_log_file_size_MB,
              securest_log_files_backup_count, tempdir, amqp_username,
              amqp_password, maintenance_folder):
     self.process = None
     self.port = port or MANAGER_REST_PORT
     self.file_server_dir = file_server_dir
     self.file_server_base_uri = file_server_base_uri
     self.file_server_blueprints_folder = file_server_blueprints_folder
     self.file_server_deployments_folder = file_server_deployments_folder
     self.file_server_uploaded_blueprints_folder = \
         file_server_uploaded_blueprints_folder
     self.file_server_resources_uri = file_server_resources_uri
     self.rest_service_log_level = rest_service_log_level
     self.rest_service_log_path = rest_service_log_path
     self.rest_service_log_file_size_MB = rest_service_log_file_size_MB
     self.rest_service_log_files_backup_count = \
         rest_service_log_files_backup_count
     self.securest_log_level = securest_log_level
     self.securest_log_file = securest_log_file
     self.securest_log_file_size_MB = securest_log_file_size_MB
     self.securest_log_files_backup_count = securest_log_files_backup_count
     self.client = CloudifyClient('localhost', port=port)
     self.tempdir = tempdir
     self.amqp_username = amqp_username
     self.amqp_password = amqp_password
     self.maintenance_folder = maintenance_folder
Esempio n. 10
0
 def execute(self):
     """
     Deploy Cloudify Manager.
     """
     scpc = scp.SCPClient(self.ssh.get_transport())
     scpc.put(self.cloudify_archive,
              remote_path=os.path.basename(self.cloudify_archive))
     (_, stdout, stderr) = self.ssh.exec_command(
         "sudo wget https://get.docker.com/ -O script.sh && "
         "sudo chmod +x script.sh && "
         "sudo ./script.sh && "
         "sudo docker load -i ~/{} && "
         "sudo docker run --name cfy_manager_local -d "
         "--restart unless-stopped -v /sys/fs/cgroup:/sys/fs/cgroup:ro "
         "--tmpfs /run --tmpfs /run/lock --security-opt seccomp:unconfined "
         "--cap-add SYS_ADMIN --network=host {}".format(
             os.path.basename(self.cloudify_archive),
             self.cloudify_container))
     self.__logger.debug("output:\n%s", stdout.read().decode("utf-8"))
     self.__logger.debug("error:\n%s", stderr.read().decode("utf-8"))
     self.cfy_client = CloudifyClient(
         host=self.fip.floating_ip_address if self.fip else
         (self.sshvm.public_v4),
         username='******',
         password='******',
         tenant='default_tenant')
     self.__logger.info("Attemps running status of the Manager")
     secret_key = "foo"
     secret_value = "bar"
     for loop in range(20):
         try:
             self.__logger.debug("status %s",
                                 self.cfy_client.manager.get_status())
             cfy_status = self.cfy_client.manager.get_status()['status']
             self.__logger.info("The current manager status is %s",
                                cfy_status)
             if str(cfy_status) != 'running':
                 raise Exception("Cloudify Manager isn't up and running")
             for secret in iter(self.cfy_client.secrets.list()):
                 if secret_key == secret["key"]:
                     self.__logger.debug("Updating secrets: %s", secret_key)
                     self.cfy_client.secrets.update(secret_key,
                                                    secret_value)
                     break
             else:
                 self.__logger.debug("Creating secrets: %s", secret_key)
                 self.cfy_client.secrets.create(secret_key, secret_value)
             self.cfy_client.secrets.delete(secret_key)
             self.__logger.info("Secrets API successfully reached")
             break
         except Exception:  # pylint: disable=broad-except
             self.__logger.debug(
                 "try %s: Cloudify Manager isn't up and running \n%s",
                 loop + 1, traceback.format_exc())
             time.sleep(30)
     else:
         self.__logger.error("Cloudify Manager isn't up and running")
         return 1
     self.__logger.info("Cloudify Manager is up and running")
     return 0
Esempio n. 11
0
def get_rest_client():
    """
    :returns: A REST client configured to connect to the manager in context
    :rtype: cloudify_rest_client.CloudifyClient
    """
    return CloudifyClient(utils.get_manager_ip(),
                          utils.get_manager_rest_service_port())
Esempio n. 12
0
    def create_client(self, headers=None):
        client = CloudifyClient(host="localhost", headers=headers)
        mock_http_client = MockHTTPClient(self.app, headers=headers)
        client._client = mock_http_client
        client.blueprints.api = mock_http_client
        client.deployments.api = mock_http_client
        client.deployments.outputs.api = mock_http_client
        client.deployment_modifications.api = mock_http_client
        client.executions.api = mock_http_client
        client.nodes.api = mock_http_client
        client.node_instances.api = mock_http_client
        client.manager.api = mock_http_client
        client.evaluate.api = mock_http_client
        client.tokens.api = mock_http_client

        return client
Esempio n. 13
0
def dep_list(host, tenant, user, password, ssl, cert, **kwargs):
    cm_client = CloudifyClient(host=host,
                               tenant=tenant,
                               username=user,
                               password=password,
                               protocol=SECURED_PROTOCOL if ssl else DEFAULT_PROTOCOL,
                               cert=cert)

    report = {}
    offset = 0
    while True:
        all_node_instances = cm_client.node_instances.list(_size=1000, _offset=offset)
        ni_count = len(all_node_instances)
        if not ni_count:
            break
        for node_instance in all_node_instances:
            dep_report = report.get(node_instance.deployment_id)
            if dep_report is None:
                dep_report = {'node_instances': list()}
                report[node_instance.deployment_id] = dep_report
            dep_node_instances = dep_report['node_instances']
            dep_node_instances.append(node_instance.id)
        offset += ni_count

    print(json.dumps(report, indent=True))
Esempio n. 14
0
def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('-u', '--username', type=str, required=True)
    parser.add_argument('-p', '--password', type=str, required=True)
    parser.add_argument('--ssl', default=False, action='store_true')

    subparsers = parser.add_subparsers()
    config_parser = subparsers.add_parser('config')
    config_parser.add_argument('-c', '--config', type=str, required=True)
    config_parser.add_argument('-i',
                               '--iaas',
                               type=str,
                               required=True,
                               choices=['aws', 'azure', 'openstack'])

    debug_parser = subparsers.add_parser('debug')
    debug_parser.add_argument('--print-agent-env',
                              default=True,
                              action='store_true')

    kwargs = parser.parse_args()

    cfy_client = CloudifyClient(username=kwargs.username,
                                password=kwargs.password,
                                trust_all=kwargs.ssl,
                                tenant='default_tenant',
                                host='localhost',
                                port=(443 if kwargs.ssl else 80),
                                protocol=('https' if kwargs.ssl else 'http'))

    if 'print_agent_env' in kwargs:
        print_agent_env(cfy_client)
    else:
        configure_manager(cfy_client, kwargs.iaas, kwargs.config)
Esempio n. 15
0
 def execute(self):
     """
     Deploy Cloudify Manager.
     """
     self.cfy_client = CloudifyClient(host=self.fip.floating_ip_address,
                                      username='******',
                                      password='******',
                                      tenant='default_tenant',
                                      api_version='v3')
     self.__logger.info("Attemps running status of the Manager")
     for loop in range(10):
         try:
             self.__logger.debug("status %s",
                                 self.cfy_client.manager.get_status())
             cfy_status = self.cfy_client.manager.get_status()['status']
             self.__logger.info("The current manager status is %s",
                                cfy_status)
             if str(cfy_status) != 'running':
                 raise Exception("Cloudify Manager isn't up and running")
             self.cfy_client.secrets.create("foo", "bar")
             self.__logger.debug("List secrets: %s",
                                 self.cfy_client.secrets.list())
             self.cfy_client.secrets.delete("foo")
             self.__logger.info("Secrets API successfully reached")
             break
         except Exception:  # pylint: disable=broad-except
             self.__logger.info(
                 "try %s: Cloudify Manager isn't up and running", loop + 1)
             time.sleep(30)
     else:
         self.__logger.error("Cloudify Manager isn't up and running")
         return 1
     self.__logger.info("Cloudify Manager is up and running")
     return 0
Esempio n. 16
0
def _get_client():
    # Configure Cloudify endpoint from configuration file
    config = configparser.RawConfigParser()
    config_file = str(os.path.dirname(os.path.realpath(__file__))) + '/cfi.cfg'
    print('Reading Cloudify configuration from file {file}'.format(
        file=config_file))
    config.read(config_file)
    client = None
    try:
        cloudify_server = config.get('Cloudify', 'host')
        cloudify_username = config.get('Cloudify', 'username')
        cloudify_password = config.get('Cloudify', 'password')
        cloudify_tenant = config.get('Cloudify', 'tenant')
        cloudify_protocol = config.get('Cloudify', 'protocol')

        client = CloudifyClient(host=cloudify_server,
                                username=cloudify_username,
                                password=cloudify_password,
                                tenant=cloudify_tenant,
                                protocol=cloudify_protocol,
                                trust_all=True)
    except configparser.NoSectionError:
        pass

    return client
Esempio n. 17
0
def get_rest_client(manager_ip=None, rest_port=None, protocol=None):
    if not manager_ip:
        manager_ip = get_management_server_ip()

    if not rest_port:
        rest_port = get_rest_port()

    if not protocol:
        protocol = get_protocol()

    username = get_username()

    password = get_password()

    headers = get_auth_header(username, password)

    cert = get_ssl_cert()

    trust_all = get_ssl_trust_all()

    return CloudifyClient(host=manager_ip,
                          port=rest_port,
                          protocol=protocol,
                          headers=headers,
                          cert=cert,
                          trust_all=trust_all)
Esempio n. 18
0
def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('-u', '--username', type=str, required=True)
    parser.add_argument('-p', '--password', type=str, required=True)
    parser.add_argument('--ssl', default=False, action='store_true')

    subparsers = parser.add_subparsers()
    config_parser = subparsers.add_parser('config')
    config_parser.add_argument('-c', '--config', type=str, required=True)
    config_parser.add_argument('-i',
                               '--iaas',
                               type=str,
                               required=True,
                               choices=['aws', 'azure', 'openstack'])

    debug_parser = subparsers.add_parser('debug')
    debug_parser.add_argument('--print-agent-env',
                              default=True,
                              action='store_true')

    kwargs = parser.parse_args()

    headers = {'Authorization': 'Basic ' + base64_encode('{user}:{password}'.format(user=kwargs.username,password=kwargs.password))}
    cfy_client = CloudifyClient(host='localhost', port=443, protocol='https', headers=headers, trust_all=True)

    if 'print_agent_env' in kwargs:
        print_agent_env(cfy_client)
    else:
        configure_manager(cfy_client,
                          kwargs.iaas,
                          kwargs.config)
Esempio n. 19
0
    def create_client(cls, headers=None):
        client = CloudifyClient(host='localhost',
                                headers=headers)
        mock_http_client = MockHTTPClient(cls.app,
                                          headers=headers,
                                          file_server=cls.file_server)
        client._client = mock_http_client
        client.blueprints.api = mock_http_client
        client.deployments.api = mock_http_client
        client.deployments.outputs.api = mock_http_client
        client.deployment_modifications.api = mock_http_client
        client.executions.api = mock_http_client
        client.nodes.api = mock_http_client
        client.node_instances.api = mock_http_client
        client.manager.api = mock_http_client
        client.evaluate.api = mock_http_client
        client.tokens.api = mock_http_client
        client.events.api = mock_http_client
        # only exists in v2 and above
        if CLIENT_API_VERSION != 'v1':
            client.plugins.api = mock_http_client
            client.snapshots.api = mock_http_client

            # only exists in v2.1 and above
            if CLIENT_API_VERSION != 'v2':
                client.maintenance_mode.api = mock_http_client
                client.deployment_updates.api = mock_http_client

                # only exists in v3 and above
                if CLIENT_API_VERSION != 'v2.1':
                    client.tenants.api = mock_http_client
                    client.user_groups.api = mock_http_client
                    client.users.api = mock_http_client
                    client.ldap.api = mock_http_client
                    client.secrets.api = mock_http_client

                    # only exists in v3.1 and above
                    if CLIENT_API_VERSION != 'v3':
                        client.deployments.capabilities.api = mock_http_client
                        client.agents.api = mock_http_client
                        client.tasks_graphs.api = mock_http_client
                        client.operations.api = mock_http_client
                        client.plugins_update.api = mock_http_client
                        client.sites.api = mock_http_client

        return client
def check_liveness(nodes_to_monitor, depl_id):
    c = CloudifyClient('localhost')
    c_influx = InfluxDBClient(host='localhost', port=8086, database='cloudify')
    print('in check_liveness\n')
    print('nodes_to_monitor: {0}\n'.format(nodes_to_monitor))
    c = CloudifyClient('localhost')

    # compare influx data (monitoring) to cloudify desired state

    for node_name in nodes_to_monitor:
        instances = c.node_instances.list(depl_id, node_name)
        for instance in instances:
            q_string='SELECT MEAN(value) FROM /' + depl_id + '\.' + node_name + '\.' + instance.id + '\.cpu_total_system/ GROUP BY time(10s) '\
                     'WHERE  time > now() - 40s'
            print('query string is {0}\n'.format(q_string))
            try:
                result = c_influx.query(q_string)
                print('result is {0} \n'.format(result))
                if not result:
                    executions = c.executions.list(depl_id)
                    has_pending_execution = False
                    if executions and len(executions) > 0:
                        for execution in executions:
                            #    print("Execution {0} : {1}".format(execution.id, execution.status))
                            if execution.status not in execution.END_STATES:
                                has_pending_execution = True

                    if not has_pending_execution:
                        print(
                            'Setting state to error for instance {0} and its children'
                            .format(instance.id))
                        update_nodes_tree_state(c, depl_id, instance, 'error')
                        params = {'node_instance_id': instance.id}
                        print(
                            'Calling Auto-healing workflow for container instance {0}'
                            .format(instance.id))
                        c.executions.start(depl_id, 'a4c_heal', params)
                    else:
                        print(
                            'pendding executions on the deployment...waiting for their end before calling heal workfllow...'
                        )
            except InfluxDBClientError as ee:
                print('DBClienterror {0}\n'.format(str(ee)))
                print('instance id is {0}\n'.format(instance))
            except Exception as e:
                print(str(e))
Esempio n. 21
0
    def create_client(self, headers=None):
        client = CloudifyClient(host='localhost', headers=headers)
        mock_http_client = MockHTTPClient(self.app,
                                          headers=headers,
                                          file_server=self.file_server)
        client._client = mock_http_client
        client.blueprints.api = mock_http_client
        client.deployments.api = mock_http_client
        client.deployments.outputs.api = mock_http_client
        client.deployment_modifications.api = mock_http_client
        client.executions.api = mock_http_client
        client.nodes.api = mock_http_client
        client.node_instances.api = mock_http_client
        client.manager.api = mock_http_client
        client.evaluate.api = mock_http_client
        client.tokens.api = mock_http_client
        client.events.api = mock_http_client
        # only exists in v2 and above
        if CLIENT_API_VERSION != 'v1':
            client.plugins.api = mock_http_client
            client.snapshots.api = mock_http_client

            # only exists in v2.1 and above
            if CLIENT_API_VERSION != 'v2':
                client.maintenance_mode.api = mock_http_client
                client.deployment_updates.api = mock_http_client

                # only exists in v3 and above
                if CLIENT_API_VERSION != 'v2.1':
                    client.tenants.api = mock_http_client
                    client.user_groups.api = mock_http_client
                    client.users.api = mock_http_client
                    client.ldap.api = mock_http_client
                    client.secrets.api = mock_http_client

                    if CLIENT_API_VERSION != 'v3':
                        # support for ARIA was only added in V3.1
                        client.aria_service_templates.api = mock_http_client
                        client.aria_services.api = mock_http_client
                        client.aria_node_templates.api = mock_http_client
                        client.aria_nodes.api = mock_http_client
                        client.aria_executions.api = mock_http_client
                        client.aria_logs.api = mock_http_client
                        client.aria_plugins.api = mock_http_client

        return client
Esempio n. 22
0
    def create_client(cls, headers=None):
        client = CloudifyClient(host='localhost',
                                headers=headers)
        mock_http_client = MockHTTPClient(cls.app,
                                          headers=headers,
                                          file_server=cls.file_server)
        client._client = mock_http_client
        client.blueprints.api = mock_http_client
        client.deployments.api = mock_http_client
        client.deployments.outputs.api = mock_http_client
        client.deployment_modifications.api = mock_http_client
        client.executions.api = mock_http_client
        client.nodes.api = mock_http_client
        client.node_instances.api = mock_http_client
        client.manager.api = mock_http_client
        client.evaluate.api = mock_http_client
        client.tokens.api = mock_http_client
        client.events.api = mock_http_client
        # only exists in v2 and above
        if CLIENT_API_VERSION != 'v1':
            client.plugins.api = mock_http_client
            client.snapshots.api = mock_http_client

            # only exists in v2.1 and above
            if CLIENT_API_VERSION != 'v2':
                client.maintenance_mode.api = mock_http_client
                client.deployment_updates.api = mock_http_client

                # only exists in v3 and above
                if CLIENT_API_VERSION != 'v2.1':
                    client.tenants.api = mock_http_client
                    client.user_groups.api = mock_http_client
                    client.users.api = mock_http_client
                    client.ldap.api = mock_http_client
                    client.secrets.api = mock_http_client

                    # only exists in v3.1 and above
                    if CLIENT_API_VERSION != 'v3':
                        client.deployments.capabilities.api = mock_http_client
                        client.agents.api = mock_http_client
                        client.tasks_graphs.api = mock_http_client
                        client.operations.api = mock_http_client
                        client.sites.api = mock_http_client

        return client
Esempio n. 23
0
 def test_use_with_verify(self):
     host = 'localhost'
     self.client = CloudifyClient(host=host, protocol='https')
     self._test_use()
     self.assertEqual(
         self.request_url,
         'https://{0}:{1}/api/{2}/status'.format(host, SSL_PORT,
                                                 API_VERSION))
     self.assertTrue(self.verify)
Esempio n. 24
0
def get_DashboardId():
    host = parse_args(
        '/Users/wecash/PycharmProjects/datasort/setting.conf')  #读取配置文件
    client = CloudifyClient(host)
    blueprints = client.blueprints.list()
    blueprints_list = []
    for blueprint in blueprints:
        blueprints_list.append(blueprint.id)
    return blueprints_list
Esempio n. 25
0
def get_rest_client(manager_ip=None, rest_port=None):

    if not manager_ip:
        manager_ip = get_management_server_ip()

    if not rest_port:
        rest_port = get_rest_port()

    return CloudifyClient(manager_ip, rest_port)
    def bootstrap(self):
        self.cfy.bootstrap(blueprint_path=self.test_manager_blueprint_path,
                           inputs_file=self.test_inputs_path,
                           task_retries=5,
                           install_plugins=self.env.install_plugins)

        # override the client instance to use the correct ip
        self.client = CloudifyClient(self.cfy.get_management_ip())

        self.addCleanup(self.cfy.teardown)
Esempio n. 27
0
    def test_use_with_authorization(self):
        host = '127.0.0.1'
        auth_header = utils.get_auth_header('test_username', 'test_password')
        self.client = CloudifyClient(host=host, headers=auth_header)

        self._test_use()

        # assert Authorization in headers
        eventual_request_headers = self.client._client.headers
        self.assertEqual(self.do_request_headers, eventual_request_headers)
Esempio n. 28
0
 def test_use_trust_all(self):
     host = 'localhost'
     self.client = CloudifyClient(host=host,
                                  protocol='https',
                                  trust_all=True)
     self._test_use()
     self.assertEqual(
         self.request_url,
         'https://{0}:{1}/api/{2}/status'.format(host, SSL_PORT,
                                                 constants.API_VERSION))
     self.assertFalse(self.verify)
Esempio n. 29
0
def check_deployments(current_deployment_id, allowed_days, allowed_hours):
    try:
        cloudify_client = CloudifyClient('localhost')

        blueprint_id = "sfsdfdxxxx"
        deployment_inputs = {"xxx": "yyyxxx", "zzzxxx": "wwwxxx"}
        child_deployment = cloudify_client.deployments.create(
            blueprint_id, current_deployment_id, inputs=deployment_inputs)
        cloudify_client.executions.start(current_deployment_id, 'install')
    except Exception as e:
        print str(e)
Esempio n. 30
0
 def _get_cloudify_http_client(self, host):
     if self._ca_cert_valid:
         return CloudifyClient(host=host,
                               username=self._cloudify_user_name,
                               headers={CLOUDIFY_API_AUTH_TOKEN_HEADER:
                                        self._token},
                               cert=CA_DEFAULT_PATH,
                               tenant='default_tenant',
                               port=INTERNAL_REST_PORT,
                               protocol=SECURED_PROTOCOL,
                               timeout=self._request_timeout
                               )
     else:
         return CloudifyClient(host=host,
                               username=self._cloudify_user_name,
                               tenant='default_tenant',
                               port=DEFAULT_PORT,
                               protocol=DEFAULT_PROTOCOL,
                               timeout=self._request_timeout
                               )
Esempio n. 31
0
    def create_client(self, api_version=DEFAULT_API_VERSION, headers=None):
        client = CloudifyClient(host='localhost',
                                api_version=api_version,
                                headers=headers)
        mock_http_client = MockHTTPClient(self.app,
                                          api_version=api_version,
                                          headers=headers)
        client._client = mock_http_client
        client.blueprints.api = mock_http_client
        client.deployments.api = mock_http_client
        client.deployments.outputs.api = mock_http_client
        client.deployment_modifications.api = mock_http_client
        client.executions.api = mock_http_client
        client.nodes.api = mock_http_client
        client.node_instances.api = mock_http_client
        client.manager.api = mock_http_client
        client.evaluate.api = mock_http_client
        client.tokens.api = mock_http_client

        return client
Esempio n. 32
0
def create_rest_client(
        manager_ip,
        username=None,
        password=None,
        tenant=None,
        **kwargs):
    return CloudifyClient(
        host=manager_ip,
        username=username or cli_env.get_username(),
        password=password or cli_env.get_password(),
        tenant=tenant or cli_env.get_tenant_name(),
        **kwargs)
Esempio n. 33
0
def get_rest_client(client_profile=None,
                    rest_host=None,
                    rest_port=None,
                    rest_protocol=None,
                    rest_cert=None,
                    username=None,
                    password=None,
                    tenant_name=None,
                    trust_all=False,
                    cluster=None,
                    kerberos_env=None):
    if client_profile is None:
        client_profile = profile
    rest_host = rest_host or client_profile.manager_ip
    rest_port = rest_port or client_profile.rest_port
    rest_protocol = rest_protocol or client_profile.rest_protocol
    rest_cert = rest_cert or get_ssl_cert(client_profile)
    username = username or get_username(client_profile)
    password = password or get_password(client_profile)
    tenant_name = tenant_name or get_tenant_name(client_profile)
    trust_all = trust_all or get_ssl_trust_all()
    headers = get_auth_header(username, password)
    headers[constants.CLOUDIFY_TENANT_HEADER] = tenant_name
    cluster = cluster or is_cluster(client_profile)
    kerberos_env = kerberos_env \
        if kerberos_env is not None else client_profile.kerberos_env

    if kerberos_env is False \
            or (kerberos_env is None and not is_kerberos_env()):
        if not username:
            raise CloudifyCliError('Command failed: Missing Username')
        if not password:
            raise CloudifyCliError('Command failed: Missing password')

    if cluster:
        client = CloudifyClusterClient(host=rest_host,
                                       port=rest_port,
                                       protocol=rest_protocol,
                                       headers=headers,
                                       cert=rest_cert,
                                       trust_all=trust_all,
                                       profile=client_profile,
                                       kerberos_env=kerberos_env)
    else:
        client = CloudifyClient(host=rest_host,
                                port=rest_port,
                                protocol=rest_protocol,
                                headers=headers,
                                cert=rest_cert,
                                trust_all=trust_all,
                                kerberos_env=kerberos_env)
    return client
Esempio n. 34
0
def check_blueprints(allowed_seconds):
    cloudify_client = CloudifyClient('localhost')
    for blueprint in cloudify_client.blueprints.list():
        deployment_list = cloudify_client.deployments.list(
            blueprint_id=blueprint.id)
        if deployment_list is None or len(deployment_list) == 0:
            print "There are no deployments for blueprint {0}".format(
                blueprint.id)
            time_diff = get_time_diff(blueprint.created_at)
            seconds_diff = time_diff.total_seconds()
            if allowed_seconds < seconds_diff:
                print "Deleting blueprint {0} ...".format(blueprint.id)
                cloudify_client.blueprints.delete(blueprint.id)