def connect_to_cloud(endpoint_credentials):
    """
    Connect to cloud foundry target api using the credentials
    """
    client_cf = None
    try:

        logging.info(': Using API Endpoint: %s', endpoint_credentials[0])
        proxy = {
            'http':
            'http://cis-india-pitc-bangalorez.proxy.corporate.ge.com:80',
            'https':
            'http://cis-india-pitc-bangalorez.proxy.corporate.ge.com:80'
        }
        client_cf = CloudFoundryClient(target_endpoint=endpoint_credentials[0],
                                       proxy=proxy,
                                       skip_verification=True)
        client_cf.init_with_user_credentials(endpoint_credentials[1],
                                             endpoint_credentials[2])
        logging.info(': %s user logged into CloudFoundry',
                     endpoint_credentials[1])
    except (ConnectionResetError, ConnectionRefusedError,
            ConnectionAbortedError, OAuthError) as error_x:
        logging.info('In Except block of method cloud_connect:::: %s', error_x)
        exit_program()
    return client_cf
Пример #2
0
 def test_grant_password_request_with_token_format_opaque(self):
     requests = FakeRequests()
     session = MockSession()
     with patch('oauth2_client.credentials_manager.requests', new=requests), \
          patch('cloudfoundry_client.client.requests', new=requests):
         requests.Session.return_value = session
         self._mock_info_calls(requests)
         requests.post.return_value = MockResponse(
             '%s/oauth/token' % self.AUTHORIZATION_ENDPOINT,
             status_code=HTTPStatus.OK.value,
             text=json.dumps(
                 dict(access_token='access-token',
                      refresh_token='refresh-token')))
         client = CloudFoundryClient(self.TARGET_ENDPOINT,
                                     token_format='opaque')
         client.init_with_user_credentials('somebody', 'p@s$w0rd')
         self.assertEqual('Bearer access-token',
                          session.headers.get('Authorization'))
         requests.post.assert_called_with(requests.post.return_value.url,
                                          data=dict(grant_type='password',
                                                    username='******',
                                                    scope='',
                                                    password='******',
                                                    token_format='opaque'),
                                          headers=dict(
                                              Accept='application/json',
                                              Authorization='Basic Y2Y6'),
                                          proxies=dict(http='', https=''),
                                          verify=True)
Пример #3
0
 def test_refresh_request_with_token_format_opaque(self):
     requests = FakeRequests()
     session = MockSession()
     with patch('oauth2_client.credentials_manager.requests', new=requests), \
          patch('cloudfoundry_client.client.requests', new=requests):
         requests.Session.return_value = session
         requests.get.return_value = MockResponse(
             '%s/v2/info' % TARGET_ENDPOINT,
             status_code=OK,
             text=json.dumps(
                 dict(api_version='2.1',
                      authorization_endpoint=TARGET_ENDPOINT)))
         requests.post.return_value = MockResponse(
             '%s/oauth/token' % TARGET_ENDPOINT,
             status_code=OK,
             text=json.dumps(
                 dict(access_token='access-token',
                      refresh_token='refresh-token')))
         client = CloudFoundryClient(TARGET_ENDPOINT, token_format='opaque')
         client.init_with_token('refresh-token')
         self.assertEqual('Bearer access-token',
                          session.headers.get('Authorization'))
         requests.post.assert_called_with(
             requests.post.return_value.url,
             data=dict(grant_type='refresh_token',
                       scope='',
                       refresh_token='refresh-token',
                       token_format='opaque'),
             headers=dict(Accept='application/json',
                          Authorization='Basic Y2Y6'),
             proxies=dict(http='', https=''),
             verify=True)
 def test_refresh_request_with_token_format_opaque(self):
     requests = FakeRequests()
     session = MockSession()
     with patch("oauth2_client.credentials_manager.requests",
                new=requests), patch("cloudfoundry_client.client.requests",
                                     new=requests):
         requests.Session.return_value = session
         self._mock_info_calls(requests)
         requests.post.return_value = MockResponse(
             "%s/oauth/token" % self.AUTHORIZATION_ENDPOINT,
             status_code=HTTPStatus.OK.value,
             text=json.dumps(
                 dict(access_token="access-token",
                      refresh_token="refresh-token")),
         )
         client = CloudFoundryClient(self.TARGET_ENDPOINT,
                                     token_format="opaque")
         client.init_with_token("refresh-token")
         self.assertEqual("Bearer access-token",
                          session.headers.get("Authorization"))
         requests.post.assert_called_with(
             requests.post.return_value.url,
             data=dict(grant_type="refresh_token",
                       scope="",
                       refresh_token="refresh-token",
                       token_format="opaque"),
             headers=dict(Accept="application/json",
                          Authorization="Basic Y2Y6"),
             proxies=dict(http="", https=""),
             verify=True,
         )
def cf_get_client(username, password, endpoint, http_proxy="", https_proxy=""):
    target_endpoint = endpoint
    proxy = dict(http=http_proxy, https=https_proxy)
    client = CloudFoundryClient(target_endpoint, proxy=proxy)
    client.init_with_user_credentials(username, password)

    return client
Пример #6
0
 def test_grant_password_request_with_login_hint(self):
     requests = FakeRequests()
     session = MockSession()
     with patch("oauth2_client.credentials_manager.requests", new=requests), patch(
         "cloudfoundry_client.client.requests", new=requests
     ):
         requests.Session.return_value = session
         self._mock_info_calls(requests)
         requests.post.return_value = MockResponse(
             "%s/oauth/token" % self.AUTHORIZATION_ENDPOINT,
             status_code=HTTPStatus.OK.value,
             text=json.dumps(dict(access_token="access-token", refresh_token="refresh-token")),
         )
         client = CloudFoundryClient(
             self.TARGET_ENDPOINT, login_hint=quote(json.dumps(dict(origin="uaa"), separators=(",", ":")))
         )
         client.init_with_user_credentials("somebody", "p@s$w0rd")
         self.assertEqual("Bearer access-token", session.headers.get("Authorization"))
         requests.post.assert_called_with(
             requests.post.return_value.url,
             data=dict(
                 grant_type="password",
                 username="******",
                 scope="",
                 password="******",
                 login_hint="%7B%22origin%22%3A%22uaa%22%7D",
             ),
             headers=dict(Accept="application/json", Authorization="Basic Y2Y6"),
             proxies=dict(http="", https=""),
             verify=True,
         )
 def test_check_response_500_json(self):
     response = MockResponse("http://some-cf-url",
                             500,
                             text=json.dumps(
                                 dict(entity="entityTest",
                                      metadata="metadataTest")))
     with self.assertRaisesRegex(InvalidStatusCode, "metadataTest"):
         CloudFoundryClient._check_response(response)
Пример #8
0
def loginCF(config):
    #cf login
    cf_endpoint = config.get('pcf_conf', 'endpoint')
    cf_user = config.get('pcf_conf', 'user')
    cf_passwd = config.get('pcf_conf', 'password')
    proxy = dict(http = os.environ.get('HTTP_PROXY', ''), https = os.environ.get('HTTPS_PROXY', ''))
    client = CloudFoundryClient(cf_endpoint, proxy = proxy, skip_verification = True)
    client.init_with_user_credentials(cf_user, cf_passwd)
    return client, client.service_information
Пример #9
0
 def test_check_response_500_with_vcap(self):
     response = MockResponse(
         "http://some-cf-url",
         500,
         text=json.dumps(dict(entity="entityTest", metadata="metadataTest")),
         headers={"x-vcap-request-id": "testVcap"},
     )
     with self.assertRaisesRegex(InvalidStatusCode, "testVcap"):
         CloudFoundryClient._check_response(response)
Пример #10
0
 def __init__(self, target_endpoint, username, password, organization_name,
              space_name):
     client = CloudFoundryClient(target_endpoint, skip_verification=False)
     client.init_with_user_credentials(username, password)
     self.client = client
     self.target_endpoint = target_endpoint
     self.organization_name = organization_name
     self.space_name = space_name
     self.space_guid = self.get_space_guid(self.organization_name,
                                           self.space_name)
Пример #11
0
 def test_log_request_empty_headers(self):
     response = MockResponse("http://some-cf-url", 200, text=json.dumps(dict(entity="entityTest", metadata="metadataTest")))
     with self.assertLogs(level="DEBUG") as cm:
         CloudFoundryClient._log_request("GET", "testURL", response)
     self.assertEqual(
         cm.output,
         [
             "DEBUG:cloudfoundry_client.client:GET: url=testURL - status_code=200 - vcap-request-id=N/A - response="
             '{"entity": "entityTest", "metadata": "metadataTest"}'
         ],
     )
def get_cf_client(config):
    # "why is this a function, and the rest of these are static?"
    # good question. The __init__ on this immediately probes the
    # api endpoint, which means we need to stub it for testing.
    # and having to add that stub to every test that _might_
    # `import extensions` would be bonkers. As a function, we should
    # only need to stub when we're actually thinking about CF
    logger.debug("getting cf client")
    client = CloudFoundryClient(config.CF_API_ENDPOINT)
    client.init_with_user_credentials(config.CF_USERNAME, config.CF_PASSWORD)
    return client
Пример #13
0
def dbname_get_cf_info(postgres_certification, cf_user, cf_passwd):
    client = CloudFoundryClient(cf_endpoint, proxy = proxy, skip_verification = True)
    client.init_with_user_credentials(cf_user, cf_passwd)
    sql_dbnames = 'SELECT datname FROM pg_database WHERE datistemplate = false;'
    conn = psycopg2.connect(postgres_certification)
    cur = conn.cursor()
    cur.execute(sql_dbnames)
    dbnames = cur.fetchall()
    conn.commit()
    for i in dbnames:
        if i[0] != 'template0' and i[0] != 'template1' and i[0] != 'postgres':
            getServiceInfo(client, i[0])
Пример #14
0
 def test_get_info(self):
     requests = FakeRequests()
     session = MockSession()
     with patch("oauth2_client.credentials_manager.requests", new=requests), patch(
         "cloudfoundry_client.client.requests", new=requests
     ):
         requests.Session.return_value = session
         self._mock_info_calls(requests)
         client = CloudFoundryClient(self.TARGET_ENDPOINT)
         self._mock_info_calls(requests)
         info = client._get_info(self.TARGET_ENDPOINT)
         self.assertEqual(info.api_endpoint, self.TARGET_ENDPOINT)
         self.assertEqual(info.api_v2_version, self.API_V2_VERSION)
         self.assertEqual(info.doppler_endpoint, self.DOPPLER_ENDPOINT)
         self.assertEqual(info.log_stream_endpoint, self.LOG_STREAM_ENDPOINT)
def connect_to_cloud(endpoint_credentials):
    """
    Connect to cloud foundry target api using the credentials
    """
    client_cf = None


    logging.info(': Using API Endpoint: %s', endpoint_credentials[0])
    proxy = {'http': 'http://cis-india-pitc-bangalorez.proxy.corporate.ge.com:80',
             'https': 'http://cis-india-pitc-bangalorez.proxy.corporate.ge.com:80'}
    client_cf = CloudFoundryClient(target_endpoint=endpoint_credentials[0],
                                   proxy=proxy, skip_verification=True)
    client_cf.init_with_user_credentials(endpoint_credentials[1], endpoint_credentials[2])
    logging.info(': %s user logged into CloudFoundry', endpoint_credentials[1])
    return client_cf
 def test_check_response_200(self):
     response = MockResponse("http://some-cf-url",
                             200,
                             text=json.dumps(
                                 dict(entity="entityTest",
                                      metadata="metadataTest")))
     self.assertIsNotNone(CloudFoundryClient._check_response(response))
    def get_cloudfoundry_client(self):
        if self.client is None:
            proxy = dict(http=os.environ.get('HTTP_PROXY', ''),
                         https=os.environ.get('HTTPS_PROXY', ''))
            client = CloudFoundryClient(self.api_url, proxy=proxy)
            try:
                client.init_with_user_credentials(self.username, self.password)
                self.client = client
            except BaseException as e:
                msg = 'Failed to authenticate: {}, waiting 5 minutes and exiting'.format(
                    str(e))
                logging.error(msg)
                # The sleep is added to avoid automatically banning the user for too many failed login attempts
                time.sleep(5 * 60)

        return self.client
Пример #18
0
def scan(target_endpoint, token, env_value):
    """
    Scan for value in paas
    """
    client = CloudFoundryClient(target_endpoint)
    client._access_token = token

    for app in client.v2.apps:
        app_name = app["entity"]["name"]
        print(f"checking {app_name}")

        if (app["entity"]["environment_json"]
                and env_value in app["entity"]["environment_json"].values()):
            space_name = app.space()["entity"]["name"]
            print(f"Found! {space_name} / {app_name}")

    print("Done.")
 def test_invalid_token_v2(self):
     response = MockResponse("http://some-cf-url",
                             401,
                             text=json.dumps(
                                 dict(code=1000,
                                      error_code="CF-InvalidAuthToken")))
     result = CloudFoundryClient._is_token_expired(response)
     self.assertTrue(result)
Пример #20
0
 def __init__(self):
     self.__spaces = []
     self.__apps = []
     self.__scaler_conf = {}
     api_endpoint = os.getenv("api_endpoint")
     username = os.getenv("user")
     password = os.getenv("password")
     proxy = dict(http=os.environ.get('HTTP_PROXY', ''), https=os.environ.get('HTTPS_PROXY', ''))
     print("Connecting to Api:{}".format(api_endpoint))
     self.__client = CloudFoundryClient(api_endpoint, proxy=proxy, verify=False)
     print("Authenticating")
     self.__client.init_with_user_credentials(username, password)
     print("Initializing PCF spaces")
     self.get_spaces()
     print("Initializing PCF apps")
     self.get_apps()
     self.init_scaling_confs()
Пример #21
0
 def build_client(self):
     with patch('cloudfoundry_client.client.requests') as fake_requests:
         fake_info_response = mock_response('/v2/info', 200, None)
         fake_info_response.text = json.dumps(dict(api_version='2.X',
                                                   authorization_endpoint=TARGET_ENDPOINT,
                                                   logging_endpoint=TARGET_ENDPOINT))
         fake_requests.get.return_value = fake_info_response
         self.client = CloudFoundryClient(TARGET_ENDPOINT)
Пример #22
0
    def __init__(self, target_endpoint, skip_verification, login, password,
                 organization_name, space_name, application_name,
                 service_broker_endpoint, service_broker_name,
                 service_broker_auth_user, service_broker_auth_password,
                 instance_name, default_create_instance_parameters):
        Cloudfoundry._check_parameters(default_create_instance_parameters)
        self.proxies = dict(http=os.environ.get('HTTP_PROXY', ''),
                            https=os.environ.get('HTTPS_PROXY', ''))
        self.client = CloudFoundryClient(target_endpoint,
                                         skip_verification=skip_verification,
                                         proxy=self.proxies)
        self.client.init_with_user_credentials(login, password)
        organization = self.client.organizations.get_first(
            name=organization_name)
        if organization is None:
            raise AssertionError('Unknown organization %s' % organization_name)
        space = self.client.spaces.get_first(
            organization_guid=organization['metadata']['guid'],
            name=space_name)
        if space is None:
            raise AssertionError('Unknown space %s' % space_name)
        self.space_guid = space['metadata']['guid']
        application = self.client.apps.get_first(space_guid=self.space_guid,
                                                 name=application_name)
        if application is None:
            raise AssertionError('Unknown application %s in space %s' %
                                 (application_name, space_name))
        self.application_guid = application['metadata']['guid']
        self.service_broker_name = service_broker_name
        self.service_broker_endpoint = service_broker_endpoint
        self.service_broker_auth_user = service_broker_auth_user
        self.service_broker_auth_password = service_broker_auth_password
        self.instance_name = instance_name
        self.default_create_instance_parameters = default_create_instance_parameters

        self.instance_guid = None
        self.binding_guid = None
        self.broker_guid = None
        for service_broker in self.client.service_brokers.list(
                space_guid=self.space_guid):
            if service_broker['entity']['name'] == self.service_broker_name \
                    and service_broker['entity']['broker_url'] == self.service_broker_endpoint:
                self.broker_guid = service_broker['metadata']['guid']
        self.plan_guid = None
        self._set_plan_from_broker()
Пример #23
0
 def test_build_client_when_no_doppler(self):
     requests = FakeRequests()
     session = MockSession()
     with patch('oauth2_client.credentials_manager.requests', new=requests), \
          patch('cloudfoundry_client.client.requests', new=requests):
         requests.Session.return_value = session
         self._mock_info_calls(requests, with_doppler=False)
         client = CloudFoundryClient(self.TARGET_ENDPOINT, token_format='opaque')
         self.assertRaises(NotImplementedError, lambda: client.doppler)
Пример #24
0
 def test_build_client_when_no_log_stream(self):
     requests = FakeRequests()
     session = MockSession()
     with patch("oauth2_client.credentials_manager.requests", new=requests), patch(
         "cloudfoundry_client.client.requests", new=requests
     ):
         requests.Session.return_value = session
         self._mock_info_calls(requests, with_log_streams=False)
         client = CloudFoundryClient(self.TARGET_ENDPOINT, token_format="opaque")
         self.assertRaises(NotImplementedError, lambda: client.rlpgateway)
Пример #25
0
def build_client_from_configuration(previous_configuration=None):
    dir_conf = os.path.join(os.path.expanduser('~'))
    if not os.path.isdir(dir_conf):
        if os.path.exists(dir_conf):
            raise IOError('%s exists but is not a directory')
        os.mkdir(dir_conf)
    config_file = os.path.join(dir_conf, '.cf_client_python.json')
    if not os.path.isfile(config_file):
        target_endpoint = _read_value_from_user(
            'Please enter a target endpoint',
            'Url must starts with http:// or https://',
            lambda s: s.startswith('http://') or s.startswith('https://'),
            default='' if previous_configuration is None else
            previous_configuration.get('target_endpoint', ''))
        skip_ssl_verification = _read_value_from_user(
            'Skip ssl verification (true/false)',
            'Enter either true or false',
            lambda s: s == 'true' or s == 'false',
            default='false' if previous_configuration is None else json.dumps(
                previous_configuration.get('skip_ssl_verification', False)))
        login = _read_value_from_user('Please enter your login')
        password = _read_value_from_user('Please enter your password')
        client = CloudFoundryClient(
            target_endpoint,
            skip_verification=(skip_ssl_verification == 'true'))
        client.init_with_user_credentials(login, password)
        with open(config_file, 'w') as f:
            f.write(
                json.dumps(dict(
                    target_endpoint=target_endpoint,
                    skip_ssl_verification=(skip_ssl_verification == 'true'),
                    refresh_token=client.refresh_token),
                           indent=2))
        return client
    else:
        try:
            configuration = None
            with open(config_file, 'r') as f:
                configuration = json.load(f)
                client = CloudFoundryClient(
                    configuration['target_endpoint'],
                    skip_verification=configuration['skip_ssl_verification'])
                client.init_with_token(configuration['refresh_token'])
                return client
        except Exception as ex:
            if type(ex) == ConnectionError:
                raise
            else:
                _logger.exception(
                    "Could not restore configuration. Cleaning and recreating")
                os.remove(config_file)
                return build_client_from_configuration(configuration)
Пример #26
0
 def test_invalid_token_v3(self):
     response = MockResponse(
         'http://some-cf-url',
         401,
         text=json.dumps(
             dict(errors=[
                 dict(code=666, title='Some-Error', detail='Error detail'),
                 dict(code=1000,
                      title='CF-InvalidAuthToken',
                      detail='Invalid token')
             ])))
     result = CloudFoundryClient._is_token_expired(response)
     self.assertTrue(result)
 def test_invalid_token_v3(self):
     response = MockResponse(
         "http://some-cf-url",
         401,
         text=json.dumps(
             dict(errors=[
                 dict(code=666, title="Some-Error", detail="Error detail"),
                 dict(code=1000,
                      title="CF-InvalidAuthToken",
                      detail="Invalid token"),
             ])),
     )
     result = CloudFoundryClient._is_token_expired(response)
     self.assertTrue(result)
Пример #28
0
 def test_grant_password_request_with_login_hint(self):
     requests = FakeRequests()
     session = MockSession()
     with patch('oauth2_client.credentials_manager.requests', new=requests), \
          patch('cloudfoundry_client.client.requests', new=requests):
         requests.Session.return_value = session
         requests.get.return_value = MockResponse(
             '%s/v2/info' % TARGET_ENDPOINT,
             status_code=OK,
             text=json.dumps(
                 dict(api_version='2.1',
                      authorization_endpoint=TARGET_ENDPOINT)))
         requests.post.return_value = MockResponse(
             '%s/oauth/token' % TARGET_ENDPOINT,
             status_code=OK,
             text=json.dumps(
                 dict(access_token='access-token',
                      refresh_token='refresh-token')))
         client = CloudFoundryClient(TARGET_ENDPOINT,
                                     login_hint=quote(
                                         json.dumps(dict(origin='uaa'),
                                                    separators=(',', ':'))))
         client.init_with_user_credentials('somebody', 'p@s$w0rd')
         self.assertEqual('Bearer access-token',
                          session.headers.get('Authorization'))
         requests.post.assert_called_with(
             requests.post.return_value.url,
             data=dict(grant_type='password',
                       username='******',
                       scope='',
                       password='******',
                       login_hint='%7B%22origin%22%3A%22uaa%22%7D'),
             headers=dict(Accept='application/json',
                          Authorization='Basic Y2Y6'),
             proxies=dict(http='', https=''),
             verify=True)
Пример #29
0
def build_client_from_configuration(
        previous_configuration: dict = None) -> CloudFoundryClient:
    config_file = get_config_file()
    if not os.path.isfile(config_file):
        target_endpoint = _read_value_from_user(
            "Please enter a target endpoint",
            "Url must starts with http:// or https://",
            lambda s: s.startswith("http://") or s.startswith("https://"),
            default="" if previous_configuration is None else
            previous_configuration.get("target_endpoint", ""),
        )
        verify = _read_value_from_user(
            "Verify ssl (true/false)",
            "Enter either true or false",
            lambda s: s == "true" or s == "false",
            default="true" if previous_configuration is None else json.dumps(
                previous_configuration.get("verify", True)),
        )
        login = _read_value_from_user("Please enter your login")
        password = _read_value_from_user("Please enter your password")
        client = CloudFoundryClient(target_endpoint, verify=(verify == "true"))
        client.init_with_user_credentials(login, password)
        with open(config_file, "w") as f:
            f.write(
                json.dumps(dict(target_endpoint=target_endpoint,
                                verify=(verify == "true"),
                                refresh_token=client.refresh_token),
                           indent=2))
        return client
    else:
        try:
            configuration = None
            with open(config_file, "r") as f:
                configuration = json.load(f)
                client = CloudFoundryClient(configuration["target_endpoint"],
                                            verify=configuration["verify"])
                client.init_with_token(configuration["refresh_token"])
                return client
        except Exception as ex:
            if type(ex) == ConnectionError:
                raise
            else:
                _logger.exception(
                    "Could not restore configuration. Cleaning and recreating")
                os.remove(config_file)
                return build_client_from_configuration(configuration)
Пример #30
0
def build_client_from_configuration(previous_configuration=None):
    dir_conf = os.path.join(os.path.expanduser("~"))
    if not os.path.isdir(dir_conf):
        if os.path.exists(dir_conf):
            raise IOError("%s exists but is not a directory")
        os.mkdir(dir_conf)
    config_file = os.path.join(dir_conf, ".cf_client_python.json")
    if not os.path.isfile(config_file):
        target_endpoint = _read_value_from_user(
            "Please enter a target endpoint",
            "Url must starts with http:// or https://",
            lambda s: s.startswith("http://") or s.startswith("https://"),
            default="" if previous_configuration is None else previous_configuration.get("target_endpoint", ""),
        )
        skip_ssl_verification = _read_value_from_user(
            "Skip ssl verification (true/false)",
            "Enter either true or false",
            lambda s: s == "true" or s == "false",
            default="false"
            if previous_configuration is None
            else json.dumps(previous_configuration.get("skip_ssl_verification", False)),
        )
        login = _read_value_from_user("Please enter your login")
        password = _read_value_from_user("Please enter your password")
        client = CloudFoundryClient(target_endpoint, skip_verification=(skip_ssl_verification == "true"))
        client.init_with_user_credentials(login, password)
        with open(config_file, "w") as f:
            f.write(
                json.dumps(
                    dict(
                        target_endpoint=target_endpoint,
                        skip_ssl_verification=(skip_ssl_verification == "true"),
                        refresh_token=client.refresh_token,
                    ),
                    indent=2,
                )
            )
        return client
    else:
        try:
            configuration = None
            with open(config_file, "r") as f:
                configuration = json.load(f)
                client = CloudFoundryClient(
                    configuration["target_endpoint"], skip_verification=configuration["skip_ssl_verification"]
                )
                client.init_with_token(configuration["refresh_token"])
                return client
        except Exception as ex:
            if type(ex) == ConnectionError:
                raise
            else:
                _logger.exception("Could not restore configuration. Cleaning and recreating")
                os.remove(config_file)
                return build_client_from_configuration(configuration)
Пример #31
0
def build_client_from_configuration(
        previous_configuration: dict = None) -> CloudFoundryClient:
    config_file = get_config_file()
    if not os.path.isfile(config_file):
        target_endpoint = _read_value_from_user(
            'Please enter a target endpoint',
            'Url must starts with http:// or https://',
            lambda s: s.startswith('http://') or s.startswith('https://'),
            default='' if previous_configuration is None else
            previous_configuration.get('target_endpoint', ''))
        verify = _read_value_from_user(
            'Verify ssl (true/false)',
            'Enter either true or false',
            lambda s: s == 'true' or s == 'false',
            default='true' if previous_configuration is None else json.dumps(
                previous_configuration.get('verify', True)))
        login = _read_value_from_user('Please enter your login')
        password = _read_value_from_user('Please enter your password')
        client = CloudFoundryClient(target_endpoint, verify=(verify == 'true'))
        client.init_with_user_credentials(login, password)
        with open(config_file, 'w') as f:
            f.write(
                json.dumps(dict(target_endpoint=target_endpoint,
                                verify=(verify == 'true'),
                                refresh_token=client.refresh_token),
                           indent=2))
        return client
    else:
        try:
            configuration = None
            with open(config_file, 'r') as f:
                configuration = json.load(f)
                client = CloudFoundryClient(configuration['target_endpoint'],
                                            verify=configuration['verify'])
                client.init_with_token(configuration['refresh_token'])
                return client
        except Exception as ex:
            if type(ex) == ConnectionError:
                raise
            else:
                _logger.exception(
                    "Could not restore configuration. Cleaning and recreating")
                os.remove(config_file)
                return build_client_from_configuration(configuration)
Пример #32
0
def build_client_from_configuration(previous_configuration=None):
    dir_conf = os.path.join(os.path.expanduser('~'))
    if not os.path.isdir(dir_conf):
        if os.path.exists(dir_conf):
            raise IOError('%s exists but is not a directory')
        os.mkdir(dir_conf)
    config_file = os.path.join(dir_conf, '.cf_client_python.json')
    if not os.path.isfile(config_file):
        target_endpoint = _read_value_from_user('Please enter a target endpoint',
                                                'Url must starts with http:// or https://',
                                                lambda s: s.startswith('http://') or s.startswith('https://'),
                                                default='' if previous_configuration is None else
                                                previous_configuration.get('target_endpoint', ''))
        skip_ssl_verification = _read_value_from_user('Skip ssl verification (true/false)',
                                                      'Enter either true or false',
                                                      lambda s: s == 'true' or s == 'false',
                                                      default='false' if previous_configuration is None else
                                                      json.dumps(
                                                          previous_configuration.get('skip_ssl_verification', False)))
        login = _read_value_from_user('Please enter your login')
        password = _read_value_from_user('Please enter your password')
        client = CloudFoundryClient(target_endpoint, skip_verification=(skip_ssl_verification == 'true'))
        client.init_with_user_credentials(login, password)
        with open(config_file, 'w') as f:
            f.write(json.dumps(dict(target_endpoint=target_endpoint,
                                    skip_ssl_verification=(skip_ssl_verification == 'true'),
                                    refresh_token=client.refresh_token), indent=2))
        return client
    else:
        try:
            configuration = None
            with open(config_file, 'r') as f:
                configuration = json.load(f)
                client = CloudFoundryClient(configuration['target_endpoint'],
                                            skip_verification=configuration['skip_ssl_verification'])
                client.init_with_token(configuration['refresh_token'])
                return client
        except Exception, ex:
            if type(ex) == ConnectionError:
                raise
            else:
                _logger.exception("Could not restore configuration. Cleaning and recreating")
                os.remove(config_file)
                return build_client_from_configuration(configuration)
Пример #33
0
def build_client_from_configuration():
    global _client
    if _client is None:
        _init_logging()
        cfg = ConfigParser()
        cfg.read(get_resource('test.properties'))
        proxy = None
        try:
            http = cfg.get('proxy', 'http')
            https = cfg.get('proxy', 'https')
            proxy = dict(http=http, https=https)
        except (NoSectionError, NoOptionError):
            pass
        skip_verification = False
        try:
            skip_verification_str = cfg.get('service', 'skip_ssl_verification')
            skip_verification = skip_verification_str.lower() == 'true'
        except (NoSectionError, NoOptionError):
            pass
        client = CloudFoundryClient(cfg.get('service', 'target_endpoint'), proxy=proxy,
                                    skip_verification=skip_verification)
        client.init_with_user_credentials(cfg.get('authentification', 'login'),
                                                              cfg.get('authentification', 'password'))
        client.org_guid = cfg.get('test_data', 'org_guid')
        client.space_guid = cfg.get('test_data', 'space_guid')
        client.app_guid = cfg.get('test_data', 'app_guid')
        client.log_app_guid = cfg.get('test_data', 'log_app_guid')
        client.service_guid = cfg.get('test_data', 'service_guid')
        client.service_name = cfg.get('test_data', 'service_name')
        client.plan_guid = cfg.get('test_data', 'plan_guid')
        client.creation_parameters = eval(cfg.get('test_data', 'creation_parameters'))
        client.update_parameters = eval(cfg.get('test_data', 'update_parameters'))
        _client = client

    return _client
        cfg = ConfigParser.ConfigParser()
        cfg.read(get_resource('test.properties'))
        proxy = None
        try:
            http = cfg.get('proxy', 'http')
            https = cfg.get('proxy', 'https')
            proxy = dict(http=http, https=https)
        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError), _:
            pass
        skip_verification = False
        try:
            skip_verification_str = cfg.get('service', 'skip_ssl_verification')
            skip_verification = skip_verification_str.lower() == 'true'
        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError), _:
            pass
        client = CloudFoundryClient(cfg.get('service', 'target_endpoint'), proxy=proxy,
                                    skip_verification=skip_verification)
        client.init_with_user_credentials(cfg.get('authentification', 'login'),
                                                              cfg.get('authentification', 'password'))
        client.org_guid = cfg.get('test_data', 'org_guid')
        client.space_guid = cfg.get('test_data', 'space_guid')
        client.app_guid = cfg.get('test_data', 'app_guid')
        client.log_app_guid = cfg.get('test_data', 'log_app_guid')
        client.service_guid = cfg.get('test_data', 'service_guid')
        client.service_name = cfg.get('test_data', 'service_name')
        client.plan_guid = cfg.get('test_data', 'plan_guid')
        client.creation_parameters = eval(cfg.get('test_data', 'creation_parameters'))
        client.update_parameters = eval(cfg.get('test_data', 'update_parameters'))
        _client = client

    return _client