示例#1
0
    def main():
        import sys
        import argparse

        args = argparse.ArgumentParser()
        args.add_argument('--cloud-controller', required=True)
        args.add_argument('--guid', required=True)
        args.add_argument('-i', dest='index', required=True)
        args.add_argument('-c', '--command', dest='command', required=True)
        args.add_argument('--stderr', action='store_true', required=False)
        args = args.parse_args()
        rt = os.getenv('CF_REFRESH_TOKEN')
        cc = cf_api.new_cloud_controller(args.cloud_controller,
                                         refresh_token=rt,
                                         client_id='cf',
                                         client_secret='')
        ssh = SSHSession(cc.ssh_proxy, args.guid, args.index)
        ssh.authenticate()

        try:
            ssh.open(allow_agent=False, look_for_keys=False)
            si, so, se = ssh.execute(args.command)
            for line in so:
                sys.stdout.write(line)
            if args.stderr:
                for line in se:
                    sys.stderr.write(line)
        finally:
            ssh.close()
示例#2
0
    def test_refresh_tokens_callback(self):
        orig_token = make_uaa_oauth_token(2)
        refreshed_token = make_uaa_oauth_token(2)
        self.assertNotEqual(orig_token['access_token'], refreshed_token['access_token'])
        prepare_request(cc_api_url, 'GET', 'info', body=cc_v2_info)
        prepare_request(uaa_api_url, 'POST', 'oauth/token', body=orig_token, version=None)
        prepare_request(cc_api_url, 'GET', 'apps')
        prepare_request(uaa_api_url, 'POST', 'oauth/token', body=refreshed_token, version=None)
        prepare_request(cc_api_url, 'GET', 'apps')

        cc = cf_api.new_cloud_controller(
            cc_api_url,
            client_id='abc',
            client_secret='',
            verify_ssl=False,
        )
        cc.set_refresh_tokens_callback()
        app = cc.apps().get().resource
        self.assertIsInstance(app, cf_api.Resource)
        self.assertEqual(cc.uaa.get_access_token().to_string(),
                         orig_token['access_token'])
        time.sleep(2)
        app = cc.apps().get().resource
        self.assertIsInstance(app, cf_api.Resource)
        self.assertEqual(cc.uaa.get_access_token().to_string(),
                         refreshed_token['access_token'])
def main():
    import argparse
    from getpass import getpass
    from .deploy_space import Space
    import cf_api
    args = argparse.ArgumentParser()
    args.add_argument('--cloud-controller', required=True)
    args.add_argument('-u', '--user')
    args.add_argument('-o', '--org', required=True)
    args.add_argument('-s', '--space', required=True)
    args.add_argument('-m', '--manifest', required=True)
    args = args.parse_args()

    kwargs = dict(
        client_id='cf',
        client_secret='',
    )
    if args.user:
        kwargs['username'] = args.user
        kwargs['password'] = getpass()
    else:
        kwargs['refresh_token'] = os.getenv('CF_REFRESH_TOKEN', '')

    cc = cf_api.new_cloud_controller(args.cloud_controller, **kwargs)
    space = Space(cc, org_name=args.org, space_name=args.space).set_debug(True)
    for manifest in space.deploy_blue_green(args.manifest):
        pass
    for manifest in space.wait_blue_green(args.manifest):
        pass
示例#4
0
    def __init__(self, json_cf, mail):
        self.mail = mail

        self.cc = cf_api.new_cloud_controller(
            json_cf['cloud_controller'],
            client_id=self.deploy_client_id,
            client_secret=self.deploy_client_secret,
            username=json_cf['cfuser'],
            password=json_cf['cloud_controller']).set_verify_ssl(verify_ssl)
示例#5
0
 def test_set_version(self):
     cc = cf_api.new_cloud_controller(
         cc_api_url,
         client_id='abc',
         client_secret='',
         verify_ssl=False,
     )
     cc.set_version(3)
     req = cc.request('apps')
     self.assertEqual('{0}/v3/apps'.format(cc_api_url), req.base_url)
示例#6
0
 def test_no_auth(self):
     cc = cf_api.new_cloud_controller(
         cc_api_url,
         client_id='abc',
         client_secret='',
         verify_ssl=False,
         no_auth=True,
     )
     self.assertIsNone(cc.uaa.get_access_token())
     self.assertIsNone(cc.uaa.get_refresh_token())
示例#7
0
 def test_new_cloud_controller(self):
     cc = cf_api.new_cloud_controller(
         cc_api_url,
         client_id='abc',
         client_secret='',
         verify_ssl=False,
     )
     self.assertIsInstance(cc, cf_api.CloudController)
     self.assertIsInstance(cc.info, cf_api.CFInfo)
     self.assertIsInstance(cc.uaa, cf_api.UAA)
     self.assertFalse(cc.verify_ssl)
     self.assertFalse(cc.uaa.verify_ssl)
示例#8
0
    def test_custom_cloud_controller(self):

        class MyCC(cf_api.CloudController):
            pass

        cc = cf_api.new_cloud_controller(
            cc_api_url,
            client_id='abc',
            client_secret='',
            verify_ssl=False,
            cloud_controller_class=MyCC,
        )
        self.assertIsInstance(cc, MyCC)
        self.assertIsInstance(cc.info, cf_api.CFInfo)
        self.assertIsInstance(cc.uaa, cf_api.UAA)
        self.assertFalse(cc.verify_ssl)
        self.assertFalse(cc.uaa.verify_ssl)
示例#9
0
    def test_get_all_resources(self):
        prepare_request(cc_api_url, 'GET', 'apps',
                        body=make_response_list(2, 'apps', 1,
                                                next_url='apps'))
        prepare_request(cc_api_url, 'GET', 'apps',
                        body=make_response_list(2, 'apps', 1))

        cc = cf_api.new_cloud_controller(
            cc_api_url,
            client_id='abc',
            client_secret='',
            verify_ssl=False,
        )
        req = cc.apps()
        apps = cc.get_all_resources(req)
        self.assertIsInstance(apps, list)
        self.assertIsInstance(apps[0], cf_api.Resource)
        self.assertEqual(2, len(apps))
from cf_api.deploy_space import Space
from getpass import getpass


print('----------')
# cloud_controller_url = 'https://api.changeme.com'
cloud_controller_url = raw_input('cloud controller url: ').strip()
username = raw_input('username: '******'password: '******'----------')
print('Authenticating with UAA...')
cc = cf_api.new_cloud_controller(
    cloud_controller_url,
    client_id='cf',  # the ``cf`` command uses this client and the secret below
    client_secret='',
    username=username,
    password=password,
)
print('Login OK!')
print('----------')

org_name = raw_input('organization name: ').strip()
space_name = raw_input('space name: ').strip()

space = Space(cc, org_name=org_name, space_name=space_name)

service_name = raw_input('service type: ').strip()
service_plan = raw_input('service plan: ').strip()
service_instance_name = raw_input('service name: ').strip()
service = space.get_deploy_service()
示例#11
0
    server.handle_request()

    return server.result


print('----------')
cloud_controller_url = raw_input('cloud controller url: ').strip()
client_id = 'test-client-id'
client_secret = 'test-client-secret'

print('----------')
print('Redirecting to UAA...')
# we create an instance of the cloud controller, but tell it to NOT authorize
# with UAA.
cc_noauth = cf_api.new_cloud_controller(cloud_controller_url,
                                        client_id=client_id,
                                        client_secret=client_secret,
                                        no_auth=True)

# we use noauth client to create the redirect URI
uaa_uri = cc_noauth.uaa.authorization_code_url('code')

# get the authorization code by logging in at the web browser, receiving
# the redirect, and extracting the authorization code
code = browser_authorize(uaa_uri)
print('authorization code: ' + str(code))

print('----------')
print('Verifying authorization code...')
# we create a UAA authenticated client using the authorization code by passing
# in the "authorization_code" keyword argument
cc = cf_api.new_cloud_controller(cloud_controller_url,
示例#12
0
"""Log in with UAA client credentials (using grant_type "client_credentials")
"""
from __future__ import print_function
import sys
import json
import cf_api
from getpass import getpass

print('----------')
# cloud_controller_url = 'https://api.changeme.com'
cloud_controller_url = raw_input('cloud controller url: ').strip()
client_id = raw_input('client id: ').strip()
client_secret = getpass('client secret: ').strip()

print('----------')
print('Authenticating with UAA...')
cc = cf_api.new_cloud_controller(
    cloud_controller_url,
    client_id=client_id,
    client_secret=client_secret,
)
print('Login OK!')

print('----------')
access_token = cc.uaa.get_access_token()
print('access_token: ' + str(access_token) + '\n')
print('access_token_data:')
json.dump(access_token.attrs, sys.stdout, indent=2)
print()
示例#13
0
    def main():
        args = argparse.ArgumentParser(
            description='This tool deploys a service to a Cloud Foundry '
            'org/space in the same manner as '
            '`cf create-service\'')
        args.add_argument('--cloud-controller',
                          dest='cloud_controller',
                          required=True,
                          help='The Cloud Controller API endpoint '
                          '(excluding leading slashes)')
        args.add_argument('-u',
                          '--user',
                          dest='user',
                          help='The user to use for the deployment')
        args.add_argument(
            '-o',
            '--org',
            dest='org',
            required=True,
            help='The organization to which the service will be deployed')
        args.add_argument(
            '-s',
            '--space',
            dest='space',
            required=True,
            help='The space to which the service will be deployed')
        args.add_argument('--skip-ssl',
                          dest='skip_ssl',
                          action='store_true',
                          help='Indicates to skip SSL cert verification')
        args.add_argument('--name',
                          dest='name',
                          required=True,
                          help='User defined service name to be deployed')
        args.add_argument('--service-name',
                          dest='service_name',
                          required=True,
                          help='Service type to be deployed')
        args.add_argument('--service-plan',
                          dest='service_plan',
                          required=True,
                          help='Service plan to be deployed')
        args.add_argument(
            '-a',
            '--action',
            dest='action',
            choices=['create', 'destroy'],
            help='Service action to be executed. Only `create\' and '
            '`destroy\' are supported values')
        args.add_argument('-w',
                          '--wait',
                          dest='wait',
                          default=False,
                          action='store_true',
                          help='Indicates to wait until the service is '
                          'created before exiting')
        args.add_argument(
            '-v',
            '--verbose',
            dest='verbose',
            default=False,
            action='store_true',
            help='Indicates that verbose logging will be enabled')
        args.add_argument(
            '--provisioned',
            dest='provisioned',
            default=False,
            action='store_true',
            help='Used with --wait. Indicates to wait until the service '
            'is provisioned')
        args.add_argument(
            '--deprovisioned',
            dest='deprovisioned',
            default=False,
            action='store_true',
            help='Used with --wait. Indicates to wait until the service '
            'is provisioned')
        args.add_argument(
            '-t',
            '--timeout',
            dest='timeout',
            type=int,
            default=300,
            help='Sets a number of seconds to allow before timing out '
            'the deployment execution')
        args = args.parse_args()

        if args.user:
            username = args.user
            password = getpass('Password: '******'CF_REFRESH_TOKEN')

        cc = cf_api.new_cloud_controller(
            args.cloud_controller,
            username=username,
            password=password,
            refresh_token=refresh_token,
            client_id='cf',
            client_secret='',
            verify_ssl=not args.skip_ssl,
        )

        service_name = args.name
        service = DeployService(cc)\
            .set_debug(args.verbose)\
            .set_org_and_space(args.org, args.space)

        res = None
        status = get_status(args)
        if 'create' == args.action:
            res = service.create(service_name, args.service_name,
                                 args.service_plan)

        elif 'destroy' == args.action:
            try:
                res = service.destroy(service_name)
            except Exception as e:
                service.log(str(e))
                return

        if res is not None:
            service.log(res)

        if status is not None and args.wait:
            service.wait_service(service_name, status, args.timeout)
示例#14
0
Password = '******'

proxy_host = 'CHANGEME'
proxy_port = '2878'

AppsTotalName = 'BIZ.TANZU.TotalApps '
SpacesName = 'BIZ.TANZU.Spaces'
OrgName = 'BIZ.TANZU.Orgs'
AppsName = 'BIZ.TANZU.Apps'
OrgTotalName = 'BIZ.TANZU.TotalOrgs '
SpacesTotalName = 'BIZ.TANZU.TotalSpaces '

cc = cf_api.new_cloud_controller(
    cloud_controller,
    client_id=deploy_client_id,
    client_secret=deploy_client_secret,
    username=username,
    password=Password,
).set_verify_ssl(verify_ssl)


def sendMetric(metric):
    entireMetric = metric + '| nc -q0 ' + proxy_host + ' ' + proxy_port
    if debug == True:
        print(entireMetric)
    os.popen(entireMetric)


# List all organizations
req = cc.organizations()
res = req.get()
示例#15
0
    def main():

        args = argparse.ArgumentParser(
            description='This tool performs operations against the Cloud '
                        'Foundry Doppler logging service. It can tail a '
                        'specific application\'s logs, fetch recent logs, or '
                        'read directly from the firehose.')
        args.add_argument(
            '--cloud-controller', dest='cloud_controller', required=True,
            help='The Cloud Controller API endpoint '
                 '(excluding leading slashes)')
        args.add_argument(
            '-u', '--user', dest='user', default=None,
            help='The user used to authenticate. This may be omitted '
                 'if --client-id and --client-secret have sufficient '
                 'authorization to perform the desired operation without a '
                 'user\'s permission')
        args.add_argument(
            '-o', '--org', dest='org', default=None,
            help='The organization to be accessed')
        args.add_argument(
            '-s', '--space', dest='space', default=None,
            help='The space to be accessed')
        args.add_argument(
            '-a', '--app', dest='app', default=None,
            help='The application whose logs will be accessed')
        args.add_argument(
            '-r', '--recent', dest='recent_logs', action='store_true',
            help='Indicates to fetch the recent logs from the application')
        args.add_argument(
            '-t', '--tail', dest='tail_logs', action='store_true',
            help='Indicates to tail the logs from the application')
        args.add_argument(
            '-f', '--firehose', dest='firehose', default=None,
            help='Indicates to connect to the Cloud Foundry firehose. '
                 'The value of this option should be a unique '
                 'user-defined subscription ID that represents your logging '
                 'session. Note that you must set a custom --client-id and '
                 '--client-secret that is authorized to access the '
                 'firehose')
        args.add_argument(
            '-e', '--event-types', dest='event_types', default='',
            help='')
        args.add_argument(
            '--client-id', dest='client_id', default='cf',
            help='Used to set a custom client ID. This is required to '
                 'use the --firehose. Scope should include '
                 '`doppler.firehose\'')
        args.add_argument(
            '--client-secret', dest='client_secret', default='',
            help='Secret corresponding to --client-id')
        args.add_argument(
            '--skip-ssl', dest='skip_ssl', action='store_true',
            help='Indicates to skip SSL cert verification')
        args = args.parse_args()

        event_types = args.event_types.split(',')

        def render_log(msg):
            d = DopplerEnvelope.wrap(msg)
            if args.event_types and not d.is_event_type(*event_types):
                return
            sys.stdout.write(''.join([str(d), '\n']))
            sys.stdout.flush()

        cc = cf_api.new_cloud_controller(
            args.cloud_controller,
            username=args.user,
            password=getpass().strip() if args.user is not None else None,
            client_id=args.client_id,
            client_secret=args.client_secret,
            verify_ssl=not args.skip_ssl,
            init_doppler=True,
            refresh_token=os.getenv('CF_REFRESH_TOKEN'),
        )

        if args.firehose:
            print('*' * 40, 'firehose', '*' * 40)
            subscription_id = '-'.join([args.firehose, str(uuid4())])
            ws = cc.doppler.ws_request('firehose', subscription_id)
            try:
                ws.connect()
                ws.watch(render_log)
            except Exception as e:
                print(e)
            finally:
                ws.close()

        else:
            if not args.org or not args.space or not args.app:
                raise Exception('Org, space, and app are required')

            from . import deploy_space
            space = deploy_space.Space(
                cc,
                org_name=args.org,
                space_name=args.space,
                is_debug=True
            )

            app = space.get_app_by_name(args.app)

            if args.recent_logs:
                print('*' * 40, 'recent logs', '*' * 40)
                logs = cc.doppler.apps(app.guid, 'recentlogs').get()
                for part in logs.multipart:
                    render_log(part)

            if args.tail_logs:
                print('*' * 40, 'streaming logs', '*' * 40)
                ws = cc.doppler.ws_request('apps', app.guid, 'stream')
                try:
                    ws.connect()
                    ws.watch(render_log)
                except Exception as e:
                    print(e)
                finally:
                    ws.close()