Example #1
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('container', help='The destination CloudFiles '
                        'container to enable CDN support on')
    parser.add_argument('--dc', required=False, help='The region to '
                        'build the servers in', choices=['DFW', 'ORD', 'LON'])

    args = parser.parse_args()

    rax = raxcloudrest.RaxCloudREST()
    rax.set_from_file()
    rax.authenticate()
    endpoints = rax.cf_svc_cat()
    cdn_endpoints = rax.cf_cdn_svc_cat()
    dc = args.dc if args.dc else endpoints.keys()[0]
    endpoint = endpoints.get(dc)
    cdn_endpoint = cdn_endpoints.get(dc)

    print 'Working in %s' % dc

    try:
        headers, files = rax.get('%s/%s' % (endpoint, args.container))
        print 'Container %s exists, using...' % args.container
    except requests.exceptions.HTTPError:
        print 'Container %s does not exist, creating...' % args.container
        headers, status = rax.put('%s/%s' % (endpoint, args.container))

    headers, status = rax.put('%s/%s' % (cdn_endpoint, args.container),
                              extra_headers={'X-CDN-Enabled': 'true'})

    print '%s CDN created and enabled:' % args.container
    print 'CDN URI: %s' % headers.get('X-Cdn-Uri')
    print 'CDN SSL URI: %s' % headers.get('X-Cdn-Ssl-Uri')
    print 'CDN Streaming URI: %s' % headers.get('X-Cdn-Streaming-Uri')
Example #2
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('base',
                        help='The base hostname to use, 3x512MB'
                        ' servers will be built using this base hostname')
    parser.add_argument('--dc',
                        required=False,
                        help='The region to '
                        'build the servers in',
                        choices=['DFW', 'ORD', 'LON'])
    parser.add_argument('--image',
                        required=False,
                        help='The image ID to build'
                        ' the servers with',
                        default='5cebb13a-f783-4f8c-8058-c4182c724ccd')

    args = parser.parse_args()
    rax = raxcloudrest.RaxCloudREST()
    rax.set_from_file()
    rax.authenticate()
    endpoints = rax.next_gen_svc_cat()
    dc = args.dc if args.dc else endpoints.keys()[0]
    endpoint = endpoints.get(dc)
    print 'Building servers in: %s' % dc
    server_details = {}
    for i in xrange(0, 3):
        host = '%s%d' % (args.base, i)
        data = {
            'server': {
                'flavorRef': '2',
                'imageRef': args.image,
                'name': host,
            }
        }
        print 'Creating server: %s' % host
        headers, server = rax.post('%s/servers' % endpoint, data)
        server_details[host] = {
            'id': server['server']['id'],
            'adminPass': server['server']['adminPass'],
            'ip': ''
        }
        print '%s: %s' % (host, server['server']['id'])
    complete = 0
    while complete < 3:
        print 'Sleeping 30 seconds before checking for server readiness...'
        time.sleep(30)
        for host, server in server_details.iteritems():
            headers, details = rax.get('%s/servers/%s' %
                                       (endpoint, server['id']))
            if details['server']['status'] == 'ACTIVE':
                server_details[host]['ip'] = details['server']['accessIPv4']
                complete += 1
    t = prettytable.PrettyTable(['ID', 'Host', 'IP', 'Admin Password'])
    for host, server in server_details.iteritems():
        t.add_row([server['id'], host, server['ip'], server['adminPass']])
    print 'Servers online and ready...'
    print t
Example #3
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('base', help='The base server id to clone from')
    parser.add_argument('--dc',
                        required=True,
                        help='The region to '
                        'build the server in',
                        choices=['DFW', 'ORD', 'LON'])
    parser.add_argument('--name',
                        required=False,
                        help='The name of the new'
                        ' server. Defaults to adding "-clone" to the end of'
                        ' the original servers name')
    args = parser.parse_args()
    rax = raxcloudrest.RaxCloudREST()
    rax.set_from_file()
    rax.authenticate()
    endpoints = rax.next_gen_svc_cat()
    endpoint = endpoints.get(args.dc)
    try:
        headers, base_details = rax.get('%s/servers/%s' %
                                        (endpoint, args.base))
    except requests.exceptions.HTTPError as e:
        raise SystemExit(e)

    newhost = (args.name if args.name else '%s-clone' %
               base_details['server']['name'])
    print('Cloning %s to %s in %s' %
          (base_details['server']['name'], newhost, args.dc))

    data = {'createImage': {'name': base_details['server']['name']}}
    headers, body = rax.post('%s/servers/%s/action' % (endpoint, args.base),
                             data)
    base_image = os.path.basename(headers.get('location'))
    while 1:
        print('Sleeping 30 seconds before checking for image ' 'readiness...')
        time.sleep(30)
        headers, image = rax.get('%s/images/%s' % (endpoint, base_image))
        if image['image']['status'] == 'ACTIVE':
            break

    print 'Building %s from image...' % newhost
    data = {
        'server': {
            'flavorRef': base_details['server']['flavor']['id'],
            'imageRef': base_image,
            'name': newhost
        }
    }
    headers, server = rax.post('%s/servers' % endpoint, data)
    adminPass = server['server']['adminPass']
    while 1:
        print 'Sleeping 30 seconds before checking for server readiness...'
        time.sleep(30)
        headers, details = rax.get('%s/servers/%s' %
                                   (endpoint, server['server']['id']))
        if details['server']['status'] == 'ACTIVE':
            break
    print '%s online and ready...' % newhost
    print 'Cleaning up image...'
    headers, status = rax.delete('%s/images/%s' % (endpoint, base_image))
    t = prettytable.PrettyTable(['ID', 'Host', 'IP', 'Admin Password'])
    t.add_row([
        details['server']['id'], newhost, details['server']['accessIPv4'],
        adminPass
    ])
    print
    print t
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('fqdn', help='Fully Qualified Domain Name')
    parser.add_argument('--dc',
                        required=False,
                        help='The region to '
                        'build the servers in',
                        choices=['DFW', 'ORD', 'LON'])
    args = parser.parse_args()

    parts = args.fqdn.split('.')
    if len(parts) < 3:
        print 'Not a proper FQDN: %s' % args.fqdn
        sys.exit(1)
    domain = '.'.join(parts[-2:])

    container = '-'.join(parts[:-2])

    rax = raxcloudrest.RaxCloudREST()
    rax.set_from_file()
    rax.authenticate()
    cf_endpoints = rax.cf_svc_cat()
    cdn_endpoints = rax.cf_cdn_svc_cat()
    dns_endpoint = rax.dns_svc_cat()
    dc = args.dc if args.dc else cf_endpoints.keys()[0]
    cf_endpoint = cf_endpoints.get(dc)
    cdn_endpoint = cdn_endpoints.get(dc)

    print 'Working in %s' % dc

    try:
        headers, files = rax.get('%s/%s' % (cf_endpoint, container))
        print 'Container exists...'
    except requests.exceptions.HTTPError:
        print 'Container %s does not exist, creating...' % container
        headers, status = rax.put('%s/%s' % (cf_endpoint, container))

    headers, status = rax.put('%s/%s' % (cdn_endpoint, container),
                              extra_headers={'X-CDN-Enabled': 'true'})

    cdn_host = headers.get('X-Cdn-Uri').replace('http://', '')

    headers, status = rax.post(
        '%s/%s/' % (cf_endpoint, container),
        data='',
        extra_headers={'X-Container-Meta-Web-Index': 'index.html'})

    headers, status = rax.put('%s/%s/index.html' % (cf_endpoint, container),
                              'It Works!',
                              extra_headers={'Content-Type': 'text/html'})

    headers, domains = rax.get('%s/domains/?name=%s' % (dns_endpoint, domain))
    if not domains['domains']:
        print 'No matching domains: %s' % domain
        sys.exit(1)
    elif len(domains['domains']) > 1:
        print 'Multiple domains matched:'
        print '\n'.join([domain['name'] for domain in domains])
        sys.exit(1)

    domainid = domains['domains'][0]['id']

    data = {
        'records': [{
            'ttl': 300,
            'name': args.fqdn,
            'type': 'CNAME',
            'data': cdn_host
        }]
    }
    headers, record = rax.post('%s/domains/%s/records' %
                               (dns_endpoint, domainid),
                               data=data)
Example #5
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('base',
                        help='The base hostname to use, 3x512MB'
                        ' servers will be built using this base hostname')
    parser.add_argument('--dc',
                        required=False,
                        help='The region to '
                        'build the servers in',
                        choices=['DFW', 'ORD', 'LON'])
    parser.add_argument('--image',
                        required=False,
                        help='The image ID to build'
                        ' the servers with',
                        default='5cebb13a-f783-4f8c-8058-c4182c724ccd')

    args = parser.parse_args()
    rax = raxcloudrest.RaxCloudREST()
    rax.set_from_file()
    rax.authenticate()
    endpoints = rax.next_gen_svc_cat()
    lb_endpoints = rax.lb_svc_cat()
    dc = args.dc if args.dc else endpoints.keys()[0]
    endpoint = endpoints.get(dc)
    lb_endpoint = lb_endpoints.get(dc)
    print 'Building servers in: %s' % dc
    server_details = {}
    for i in xrange(0, 2):
        host = '%s%d' % (args.base, i)
        data = {
            'server': {
                'flavorRef': '2',
                'imageRef': args.image,
                'name': host,
            }
        }
        print 'Creating server: %s' % host
        headers, server = rax.post('%s/servers' % endpoint, data)
        server_details[host] = {
            'id': server['server']['id'],
            'adminPass': server['server']['adminPass'],
            'ip': '',
            'private': ''
        }
        print '%s: %s' % (host, server['server']['id'])
    complete = 0
    while complete < 2:
        print 'Sleeping 30 seconds before checking for server readiness...'
        time.sleep(30)
        for host, server in server_details.iteritems():
            headers, details = rax.get('%s/servers/%s' %
                                       (endpoint, server['id']))
            if details['server']['status'] == 'ACTIVE':
                server_details[host]['ip'] = details['server']['accessIPv4']
                server_details[host]['private'] = (
                    details['server']['addresses']['private'][0]['addr'])
                complete += 1

    data = {
        'loadBalancer': {
            'name': '%s-lb' % args.base,
            'port': 80,
            'protocol': 'HTTP',
            'virtualIps': [{
                'type': 'PUBLIC'
            }],
            'nodes': []
        }
    }

    for host, server in server_details.iteritems():
        data['loadBalancer']['nodes'].append({
            'address': server['private'],
            'port': 80,
            'condition': 'ENABLED'
        })

    headers, loadbalancer = rax.post('%s/loadbalancers' % lb_endpoint, data)
    public_addresses = [
        vip['address'] for vip in loadbalancer['loadBalancer']['virtualIps']
    ]

    t = prettytable.PrettyTable(['ID', 'Host', 'IP', 'Admin Password'])
    for host, server in server_details.iteritems():
        t.add_row([server['id'], host, server['ip'], server['adminPass']])
    print 'Servers and loadbalancer online and ready...'
    print t
    t = prettytable.PrettyTable(['ID', 'Name', 'IP Address'])
    t.add_row([
        loadbalancer['loadBalancer']['id'],
        loadbalancer['loadBalancer']['name'], ', '.join(public_addresses)
    ])
    print
    print t
Example #6
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('fqdn', help='Fully Qualified Domain Name')
    parser.add_argument('ip', help='IP Address')

    args = parser.parse_args()

    parts = args.fqdn.split('.')
    if len(parts) < 3:
        print 'Not a proper FQDN: %s' % args.fqdn
        sys.exit(1)
    domain = '.'.join(parts[-2:])

    if not re.match(
            '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}'
            '(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$', str(args.ip)):
        print 'Not a proper IP: %s' % args.ip
        sys.exit(1)

    rax = raxcloudrest.RaxCloudREST()
    rax.set_from_file()
    rax.authenticate()

    endpoint = rax.dns_svc_cat()

    headers, domains = rax.get('%s/domains/?name=%s' % (endpoint, domain))
    if not domains['domains']:
        print 'No matching domains: %s' % domain
        sys.exit(1)
    elif len(domains['domains']) > 1:
        print 'Multiple domains matched:'
        print '\n'.join([domain['name'] for domain in domains])
        sys.exit(1)

    domainid = domains['domains'][0]['id']
    headers, records = rax.get('%s/domains/%s/records' % (endpoint, domainid))
    namematches = filter(lambda x: x['name'] == args.fqdn, records['records'])
    exactmatches = filter(
        lambda x: x['name'] == args.fqdn and x['data'] == args.ip,
        records['records'])

    if exactmatches:
        print 'Exact record match:'
        print '\n'.join(
            ['%(name)s: %(data)s' % record for record in exactmatches])
        print 'Not adding record'
        sys.exit(1)
    elif namematches:
        print 'Record already exists:'
        print '\n'.join(
            ['%(name)s: %(data)s' % record for record in namematches])
        print 'Adding additional record with same name'

    data = {
        'records': [{
            'ttl': 300,
            'name': args.fqdn,
            'type': 'A',
            'data': args.ip
        }]
    }
    headers, record = rax.post('%s/domains/%s/records' % (endpoint, domainid),
                               data=data)
    print 'Record added'
Example #7
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('instance', help='Name of database instance')
    parser.add_argument('database', help='name of database')
    parser.add_argument('--dc', required=False, help='The region to '
                        'build the database in', choices=['DFW', 'ORD', 'LON'])
    parser.add_argument('--user', required=False, help='The user to create for'
                        'database access. Defaults to current user')
    parser.add_argument('--password', required=False,
                        help='Password for DB user')

    args = parser.parse_args()

    if not args.password:
        chars = string.ascii_letters + string.digits
        random.seed = os.urandom(1024)
        password = ''.join(random.choice(chars) for i in xrange(12))
    else:
        password = args.password

    if not args.user:
        user = os.getlogin()
    else:
        user = args.user

    rax = raxcloudrest.RaxCloudREST()
    rax.set_from_file()
    rax.authenticate()
    endpoints = rax.db_svc_cat()
    dc = args.dc if args.dc else endpoints.keys()[0]
    endpoint = endpoints.get(dc)

    print 'Creating DB instance in %s' % dc

    data = {
        'instance': {
            'databases': [
                {
                    'name': args.database
                }
            ],
            'users': [
                {
                    'databases': [
                        {
                            'name': args.database
                        }
                    ],
                    'name': user,
                    'password': password
                }
            ],
            'flavorRef': '%s/flavors/1',
            'name': args.instance,
            'volume': {
                'size': 1
            }
        }
    }

    headers, instance = rax.post('%s/instances' % endpoint, data)

    t = prettytable.PrettyTable(['ID', 'Name', 'Hostname', 'Database', 'User',
                                 'Password'])
    t.add_row([instance['instance']['id'], instance['instance']['name'],
               instance['instance']['hostname'], args.database, user,
               password])

    print
    print t
Example #8
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('source',
                        help='The source file or directory to '
                        'upload to CloudFiles')
    parser.add_argument('destination',
                        help='The destination CloudFiles '
                        'container to upload files to. Will be created if it '
                        'does not exist')
    parser.add_argument('--dc',
                        required=False,
                        help='The region to '
                        'build the servers in',
                        choices=['DFW', 'ORD', 'LON'])

    args = parser.parse_args()

    source = os.path.abspath(os.path.normpath(args.source))
    destination = re.sub(r'\W+', '-', args.destination)
    if args.destination != destination:
        print('The name of the destination container was sanitized: %s' %
              destination)

    rax = raxcloudrest.RaxCloudREST()
    rax.set_from_file()
    rax.authenticate()
    endpoints = rax.cf_svc_cat()
    dc = args.dc if args.dc else endpoints.keys()[0]
    endpoint = endpoints.get(dc)

    print 'Uploading to %s in %s' % (destination, dc)

    try:
        headers, files = rax.get('%s/%s' % (endpoint, destination))
    except requests.exceptions.HTTPError:
        print 'Container %s does not exist, creating...' % destination
        headers, status = rax.put('%s/%s' % (endpoint, destination))

    if os.path.isfile(source):
        print 'Uploading %s...' % source
        content_type = mimetypes.guess_type(source)[0]
        with open(source) as f:
            headers, status = rax.put(
                '%s/%s/%s' % (endpoint, destination, os.path.basename(source)),
                f,
                extra_headers={'Content-Type': content_type})
    elif os.path.isdir(source):
        files = os.listdir(source)
        if not files:
            print 'No files to upload'
            sys.exit(1)
        for sfile in files:
            filepath = os.path.join(source, sfile)
            if os.path.isfile(filepath):
                print 'Uploading %s...' % filepath
                content_type = mimetypes.guess_type(filepath)[0]
                with open(filepath) as f:
                    headers, status = rax.put(
                        '%s/%s/%s' %
                        (endpoint, destination, os.path.basename(filepath)),
                        f,
                        extra_headers={'Content-Type': content_type})
            else:
                print 'Not uploading directory %s' % filepath