Exemplo n.º 1
0
def create_node(counts, name, node_request, pubkey):
    '''
    Create a node in the cloud provider
    '''
    pyrax.set_setting('identity_type', app.config['AUTH_SYSTEM'])
    pyrax.set_default_region(app.config['AUTH_SYSTEM_REGION'])
    pyrax.set_credentials(app.config['USERNAME'], app.config['API_KEY'])
    nova = pyrax.cloudservers

    flavor = nova.flavors.find(name='1 GB General Purpose v1')
    image = nova.images.find(name='CentOS 7 (PVHVM)')
    node_request = NodeRequest.query.get(node_request)
    keypair = nova.keypairs.create(name, pubkey)
    # create the nodes
    for count in range(int(counts)):
        vm_name = 'softserve-' + name + '.' + str(count + 1)
        node = nova.servers.create(name=vm_name,
                                   flavor=flavor.id,
                                   image=image.id,
                                   key_name=keypair.name)

        # wait for server to get active
        while node.status == 'BUILD':
            time.sleep(5)
            node = nova.servers.get(node.id)

        # get ip_address of the active node
        for network in node.networks['public']:
            if re.match(r'\d+\.\d+\.\d+\.\d+', network):
                machine = Vm(ip_address=network,
                             vm_name=vm_name,
                             state=node.status)
                machine.details = node_request
                db.session.add(machine)
                db.session.commit()
Exemplo n.º 2
0
def connect_to_rackspace(region, access_key_id, secret_access_key):
    """ returns a connection object to Rackspace  """
    pyrax.set_setting('identity_type', 'rackspace')
    pyrax.set_default_region(region)
    pyrax.set_credentials(access_key_id, secret_access_key)
    nova = pyrax.connect_to_cloudservers(region=region)
    return nova
def load(context, path, callback):
    key = (
            context.config.RACKSPACE_PYRAX_REGION, 
            context.config.get('RACKSPACE_PYRAX_IDENTITY_TYPE','rackspace'),
            context.config.RACKSPACE_PYRAX_CFG,
            context.config.RACKSPACE_PYRAX_PUBLIC,
            context.config.RACKSPACE_LOADER_CONTAINER
        )

    if key not in CONNECTIONS:
        if(context.config.RACKSPACE_PYRAX_REGION):
            pyrax.set_default_region(context.config.RACKSPACE_PYRAX_REGION)
        pyrax.set_setting('identity_type', context.config.get('RACKSPACE_PYRAX_IDENTITY_TYPE','rackspace'))
        pyrax.set_credential_file(expanduser(context.config.RACKSPACE_PYRAX_CFG))
        cf = pyrax.connect_to_cloudfiles(public=context.config.RACKSPACE_PYRAX_PUBLIC)
        CONNECTIONS[key] = cf.get_container(context.config.RACKSPACE_LOADER_CONTAINER)

    cont = CONNECTIONS[key]
    file_abspath = normalize_path(context, path)
    logger.debug("[LOADER] getting from %s/%s" % (context.config.RACKSPACE_LOADER_CONTAINER, file_abspath))
    try:
        obj = cont.get_object(file_abspath)
        if obj:
            logger.debug("[LOADER] Found object at %s/%s" % (context.config.RACKSPACE_LOADER_CONTAINER, file_abspath))
        else:
            logger.warning("[LOADER] Unable to find object %s/%s" % (context.config.RACKSPACE_LOADER_CONTAINER, file_abspath ))
    except:
        callback(None)
    else:
        callback(obj.get())
def main():
    parser = argparse.ArgumentParser(
        description="Rackspace server creation/deletion")
    parser.add_argument("action",
                        choices=['create', 'delete'],
                        help='Action to be perfromed')
    parser.add_argument("-n", "--count", help='Number of machines')
    parser.add_argument("--region",
                        help='Region to launch the machines',
                        default='ORD')
    args = parser.parse_args()
    count = args.count
    region = args.region

    # configuration of cloud service provider
    pyrax.set_setting('identity_type', 'rackspace')
    pyrax.set_default_region(region)
    pyrax.set_credentials(os.environ.get('USERNAME'),
                          os.environ.get('PASSWORD'))
    nova_obj = pyrax.cloudservers

    if (args.action == 'create'):
        create_node(nova_obj, count)
    elif (args.action == 'delete'):
        delete_node(nova_obj)
Exemplo n.º 5
0
def connectToClouds():
    """
   Open connections to S3 and Cloud Files
   """
    s3Conn = None
    cfConn = None
    try:
        ## boto reads from /etc/boto.cfg (or ~/boto.cfg)
        s3Conn = boto.connect_s3()
        ## the cloud files library doesn't automatically read from a file, so we handle that here:
        cfConfig = configparser.ConfigParser()
        cfConfig.read('/etc/cloudfiles.cfg')
        pyrax.set_setting("identity_type", "rackspace")
        pyrax.set_default_region(cfConfig.get('Credentials', 'region'))
        pyrax.set_credentials(cfConfig.get('Credentials', 'username'),
                              cfConfig.get('Credentials', 'api_key'))
        cfConn = pyrax.connect_to_cloudfiles(
            cfConfig.get('Credentials', 'region'))
    except (NoSectionError, NoOptionError, MissingSectionHeaderError,
            ParsingError) as err:
        raise MultiCloudMirrorException(
            "Error in reading Cloud Files configuration file (/etc/cloudfiles.cfg): %s"
            % (err))
    except (S3ResponseError, S3PermissionsError) as err:
        raise MultiCloudMirrorException("Error in connecting to S3: [%d] %s" %
                                        (err.status, err.reason))
    except (ClientException, AuthenticationFailed) as err:
        raise MultiCloudMirrorException("Error in connecting to CF: %s" %
                                        str(err))
    return (s3Conn, cfConn)
Exemplo n.º 6
0
 def _connect_to_rackspace(self):
     """ returns a connection object to Rackspace  """
     pyrax.set_setting('identity_type', 'rackspace')
     pyrax.set_default_region(self.state.region)
     pyrax.set_credentials(self.config.access_key_id,
                           self.config.secret_access_key)
     nova = pyrax.connect_to_cloudservers(region=self.state.region)
     return nova
Exemplo n.º 7
0
def rack_creds():
  pyrax.set_setting("identity_type", "rackspace")
  pyrax.set_default_region("DFW")
  if os.path.isfile(os.path.expanduser("~/.rackspace_cloud_credentials")):
    creds_file = os.path.expanduser("~/.rackspace_cloud_credentials")
    pyrax.set_credential_file(creds_file)
  else:
    print("unable to locate rackspace cloud credentials file")
Exemplo n.º 8
0
 def _connect_to_rackspace(self):
     """ returns a connection object to Rackspace  """
     pyrax.set_setting('identity_type', 'rackspace')
     pyrax.set_default_region(self.state.region)
     pyrax.set_credentials(self.config.access_key_id,
                           self.config.secret_access_key)
     nova = pyrax.connect_to_cloudservers(region=self.state.region)
     return nova
    def __init__(self, context):
        self.context = context
        if(self.context.config.RACKSPACE_PYRAX_REGION):
            pyrax.set_default_region(self.context.config.RACKSPACE_PYRAX_REGION)

        pyrax.set_credential_file(expanduser(self.context.config.RACKSPACE_PYRAX_CFG))

        self.cloudfiles = pyrax.connect_to_cloudfiles(public=self.context.config.RACKSPACE_PYRAX_PUBLIC)
Exemplo n.º 10
0
def connect_to_rackspace(region,
                         access_key_id,
                         secret_access_key):
    """ returns a connection object to Rackspace  """
    pyrax.set_setting('identity_type', 'rackspace')
    pyrax.set_default_region(region)
    pyrax.set_credentials(access_key_id, secret_access_key)
    nova = pyrax.connect_to_cloudservers(region=region)
    return nova
Exemplo n.º 11
0
def connect_to_rackspace():
    """ returns a connection object to Rackspace  """
    import pyrax

    pyrax.set_setting('identity_type', env.os_auth_system)
    pyrax.set_default_region(env.os_region_name)
    pyrax.set_credentials(env.os_username, env.os_password)
    nova = pyrax.connect_to_cloudservers(region=env.os_region_name)
    return nova
Exemplo n.º 12
0
def delete_node(vm_name):
    pyrax.set_setting('identity_type', app.config['AUTH_SYSTEM'])
    pyrax.set_default_region(app.config['AUTH_SYSTEM_REGION'])
    pyrax.set_credentials(app.config['USERNAME'], app.config['API_KEY'])
    nova_obj = pyrax.cloudservers
    vm = Vm.query.filter_by(vm_name=vm_name).first()
    try:
        node = nova_obj.servers.find(name=vm_name)
        node.delete()
    except NotFound:
        logging.exception('Server not found')
    vm.state = 'DELETED'
    vm.deleted_at = datetime.now
    db.session.add(vm)
    db.session.commit()
    def __init__(self, region, user_name, api_key, container_name, **kwargs):
        """
        Init adapter
        :param access_key: str
        :param secret_key: str
        :param bucket_name: str
        """
        pyrax.set_setting("identity_type", "rackspace")
        pyrax.set_default_region(region)
        pyrax.set_credentials(user_name, api_key)

        self.cf_conn = pyrax.cloudfiles
        self.container = self.cf_conn.get_container(container_name)

        self.cache_folder = kwargs.get('cache_folder', 'cache').strip('/')
Exemplo n.º 14
0
    def __init__(self, document_url, document_hash, cloudfiles_location=None):
        self.document_url = document_url
        self.document_hash = document_hash

        if cloudfiles_location is None:
            cloudfiles_location = CLOUDFILES_DEFAULT_REGION

        pyrax.set_default_region(cloudfiles_location)
        pyrax.set_credentials(CLOUDFILES_USERNAME, CLOUDFILES_API_KEY,
                              region=cloudfiles_location)
        self.paths = {}

        self.client = pyrax.connect_to_cloudfiles(
            cloudfiles_location, public=not CLOUDFILES_SERVICENET)
        if self.client is None:
            err_msg = ('Error during connection to cloudfiles, region {0} is'
                       ' likely to be wrong.'.format(cloudfiles_location))
            raise PreviewException(err_msg)
        self.container = self.client.create_container(CLOUDFILES_COUNTAINER)
def main():
    parser = argparse.ArgumentParser(description="Rackspace server creation/deletion")
    parser.add_argument("action", choices=['create', 'delete'], help='Action to be perfromed')
    parser.add_argument("-n", "--count", help='Number of machines')
    parser.add_argument("--region", help='Region to launch the machines', default='ORD')
    args = parser.parse_args()
    count = args.count
    region = args.region

    # configuration of cloud service provider
    pyrax.set_setting('identity_type', 'rackspace')
    pyrax.set_default_region(region)
    pyrax.set_credentials(os.environ.get('USERNAME'),os.environ.get('PASSWORD'))
    nova_obj = pyrax.cloudservers

    if (args.action == 'create'):
        create_node(nova_obj, count)
    elif (args.action == 'delete'):
        delete_node(nova_obj)
Exemplo n.º 16
0
    def _get_client(self):
        username = self.config['username']
        api_key = self.config['api_key']

        # Needs to be extracted to per-action
        region = self.config['region'].upper()

        pyrax.set_setting('identity_type', 'rackspace')
        pyrax.set_default_region(region)
        pyrax.set_credentials(username, api_key)

        debug = self.config.get('debug', False)
        if debug:
            pyrax.set_http_debug(True)

        pyrax.cloudservers = pyrax.connect_to_cloudservers(region=region)
        pyrax.cloud_loadbalancers = pyrax.connect_to_cloud_loadbalancers(region=region)
        pyrax.cloud_dns = pyrax.connect_to_cloud_dns(region=region)

        return pyrax
Exemplo n.º 17
0
    def _get_client(self):
        username = self.config['username']
        api_key = self.config['api_key']

        # Needs to be extracted to per-action
        region = self.config['region'].upper()

        pyrax.set_setting('identity_type', 'rackspace')
        pyrax.set_default_region(region)
        pyrax.set_credentials(username, api_key)

        debug = self.config.get('debug', False)
        if debug:
            pyrax.set_http_debug(True)

        pyrax.cloudservers = pyrax.connect_to_cloudservers(region=region)
        pyrax.cloud_loadbalancers = pyrax.connect_to_cloud_loadbalancers(region=region)
        pyrax.cloud_dns = pyrax.connect_to_cloud_dns(region=region)

        return pyrax
Exemplo n.º 18
0
#!/usr/bin/python
print "Build a Rackspace VM"

import time
print "CTRL + C to exit: sleep 10"
time.sleep(10)

import logging
logging.captureWarnings(True)

import pyrax
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_default_region(
    '{region"')  # replace {region} with the region of the Datacenter e.g. DFW
pyrax.set_credentials(
    '{username}',
    '{apiKey}')  # replace {username} & {apiKey} with your RS info

cs = pyrax.cloudservers

image = pyrax.images.get(
    '{image#}')  # replace {image#} with rs image number that you want to use
print "Server Image:"
print(image)

flavor = cs.flavors.get('2')  # set the flavor variable
print "Server Flavor is ID:"
print(flavor)
print "ENTER FLAVOR INFO IF YOU WANT e.g. 512MB Standard Instance | 512ram | 20memory | 1cpu"

server = cs.servers.create(
Exemplo n.º 19
0
#Authentication
import os, os.path, pyrax, pyrax.exceptions as exc, time
pyrax.set_setting("identity_type", "")
pyrax.set_default_region('')
pyrax.set_credentials("", "")
cf = pyrax.cloudfiles

#Container & StorageObject
cont = cf.get_container("")
objs = cont.get_objects()

#Fetch File
for obj in objs:
     cf.download_object("",obj.name,"",structure=False);
Exemplo n.º 20
0
server_id = srv_dict[selection]
print()
nm = raw_input("Enter a name for the image: ")

img_id = cs.servers.create_image(server_id, nm)

print("Image '%s' is being created. Its ID is: %s" % (nm, img_id))
img = pyrax.cloudservers.images.get(img_id)
while img.status != "ACTIVE":
     time.sleep(60)
     img = pyrax.cloudservers.images.get(img_id)
     print ("...still waiting")

print("Image created.")

pyrax.set_default_region("DFW")
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_credential_file("/root/.rackspace_cloud_credentials")

cf_dfw = pyrax.connect_to_cloudfiles("DFW")

cont = cf_dfw.create_container("Export")

cf_dfw.make_container_public("Export", ttl=900)

pyrax.set_default_region("IAD")

cf_iad = pyrax.connect_to_cloudfiles("IAD")

cont = cf_iad.create_container("Import")
cf_iad.make_container_public("Import", ttl=900)
Exemplo n.º 21
0
#ARG parsing
if len(sys.argv[1:]) == 2 :
	index_file_path, container_name = sys.argv[1:]
else:
	usage()

#Validations
if not os.access(index_file_path, os.F_OK):
	sys.exit("Path non existent. Please verify the index file path : " + index_file)

file_name=string.rsplit(index_file_path,'/',1)[-1]

	
##Auth	
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_default_region('SYD')
pyrax.set_credentials('denzelfernando', 'blah')

#cloud file handler
cf = pyrax.cloudfiles

#create the container (will create if does not exist
container = cf.create_container(container_name)

#Make CDN
container.make_public(ttl=900)

#Set meta data (set the uploaded file name as the index)
#X-Container-Meta-Web-Index
container.set_metadata({'Web-Index' : file_name},clear = False, prefix = None)
def main():

    # Parse the command line arguments
    parser = argparse.ArgumentParser(
        description="Image a server and create a clone from the image",
        prog='cs_create_image_and_clone_server.py')
    parser.add_argument(
        '--region', help='Region(default: DFW)', default='DFW')
    parser.add_argument(
        '--flavor',
        help='flavor id or name (default: original server flavor)')
    parser.add_argument(
        '--server_name', help='Server name to create image from',
        required=True)
    parser.add_argument(
        '--image_name', help='Name of new image',
        required=True)
    parser.add_argument(
        '--clone_name', help='Name of your new clone created from image',
        required=True)
    args = parser.parse_args()

    # Set the region
    pyrax.set_default_region(args.region)

    # Authenticate using a credentials file: "~/.rackspace_cloud_credentials"
    cred_file = "%s/.rackspace_cloud_credentials" % (os.environ['HOME'])
    print "Setting authentication file to %s" % (cred_file)
    pyrax.set_credential_file(cred_file)

    # Instantiate a cloudservers object
    print "Instantiating cloudservers object"
    csobj = pyrax.cloudservers

    # Get the server id
    servers = csobj.servers.list()
    found = 0
    for server in servers:
        if server.name == args.server_name:
            found = 1
            curserver = server

    if not found:
        print "Server by the name of " + args.server_name + \
              " doesn't exist"
        sys.exit(1)

    # Get the flavor id
    if args.flavor:
        flavor_id = get_flavor_id(csobj, args.flavor)
        print "Using flavor id of " + flavor_id + \
              " from provided arg of " + args.flavor
    else:
        flavor_id = curserver.flavor['id']
        print "Using flavor id of " + flavor_id + " from orig server"

    # Create an image of the original server
    image_obj = create_image_from_server(csobj, curserver.id,
                                         args.image_name)

    # Wait for active image
    wait_for_active_image(csobj, image_obj.id)

    # Create a new server from the image just created
    cloned_server = create_server(csobj, args.clone_name, flavor_id,
                                  image_obj.id)

    # Wait for the server to complete and get data
    print "Wating on clone to finish building\n"
    updated_cloned_server = pyrax.utils.wait_until(cloned_server, "status",
                                                   ["ACTIVE", "ERROR"],
                                                   attempts=0)

    # Print the data
    print_server_data(image_obj, updated_cloned_server,
                      cloned_server.adminPass)
Exemplo n.º 23
0
#Authentication
import os, os.path, pyrax, pyrax.exceptions as exc, time
pyrax.set_setting("identity_type", "")
pyrax.set_default_region('')
pyrax.set_credentials("", "")
cf = pyrax.cloudfiles

#Container & StorageObject
cont = cf.get_container("")
objs = cont.get_objects()

#Fetch File
for obj in objs:
    cf.download_object("", obj.name, "", structure=False)
Exemplo n.º 24
0
 def wrapper(*args, **kwargs):
     pyrax.set_setting('identity_type', app.config['AUTH_SYSTEM'])
     pyrax.set_default_region(app.config['AUTH_SYSTEM_REGION '])
     pyrax.set_credentials(app.config['USERNAME'], app.config['PASSWORD'])
     nova = pyrax.cloudservers
     return func(*args, **kwargs)
Exemplo n.º 25
0
import ConfigParser
import pyrax
import time
import datetime

settings = ConfigParser.ConfigParser()
settings.read('.spinconfig')

# set defaults for execution
username = settings.get('credentials', 'RAX_USERNAME')
apikey = settings.get('credentials', 'RAX_API_KEY')
datacenter = settings.get('credentials', 'RAX_REGION')

pyrax.set_setting("identity_type", "rackspace")
pyrax.set_default_region(datacenter)
pyrax.set_credentials(username, apikey)

cs = pyrax.cloudservers

# define spinup() function

def spinup():
	imgs = cs.images.list()
	for img in imgs:
	    print img.name, " -- ID:", img.id

	print "\nWhat is the ID of the image you want to spin up from?\n"
	image_name = raw_input("ID: ")

	flvs = cs.list_flavors()
	for flv in flvs:
Exemplo n.º 26
0

#END FUNCTIONS  <-----  ^^
### +_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+ ###==### +_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+ ###
############################################## Authenticating to Rackspace cloud ###########################################
### +_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+ ###==### +_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+ ###

### Authenticate to Rackspace Cloud ###
print "Authenticating to Rackspace Cloud..."
#Set identity type
pyrax.set_setting('identity_type', 'rackspace')
#Set credentials file used for auth
pyrax.set_credential_file(CREDS_FILE)
#Set default region
print "Setting up default region of DFW..."
pyrax.set_default_region("DFW")
print "Done!"
print "============================"

### Create connections to different regions and gather list of servers ###
print "Establishing connections to DFW and ORD and compiling list of servers.  This may take a few minutes..."
#Create generic cloud server object
cs = pyrax.cloudservers
#Connect to DFW cloud servers and authenticate
cs_dfw_conn = pyrax.connect_to_cloudservers(region="DFW")
#Save a list of DFW cloud servers
cs_dfw_servers = cs_dfw_conn.servers.list()
#Connect to ORD cloud servers and authenticate
cs_ord_conn = pyrax.connect_to_cloudservers(region="ORD")
#Save a list of ORD servers
cs_ord_servers = cs_ord_conn.servers.list()
Exemplo n.º 27
0
parser.add_argument('--loadbalancer', '-l', dest='loadbalancer', required=True,
                    help='loadbalancer to edit.')
parser.add_argument('--ip_address', '-i', dest="ip", required=True,
                    help='ip address to add.')
parser.add_argument('--region', '-r', dest="region", required=True,
                    help='The rackspace region for the the request.')
parser.add_argument('--username', '-u', dest="username", required=True,
                    help='Rackspace Username.')
parser.add_argument('--api-key', '-k', dest="api_key", required=True,
                    help='Rackspace API Key.')
parser.add_argument('--remove', '-d', dest="remove", action='store_true',
                    help='remove the specified node from the loadbalancer.')
args = parser.parse_args()

pyrax.set_setting("identity_type", "rackspace")
pyrax.set_default_region(args.region)
pyrax.set_credentials(
    args.username,
    args.api_key
)

clb = pyrax.connect_to_cloud_loadbalancers(args.region.upper())

lb = clb.get(args.loadbalancer)
if args.remove:
    try:
        node = [node for node in lb.nodes
                if node.address == args.ip]
        node.delete()
    except Exception as e:
        msg = "Failed to remove instance {0} from LB {1}: {2}"
Exemplo n.º 28
0
from __future__ import print_function

import os
import pyrax

pyrax.set_default_region("ORD")
pyrax.set_setting("identity_type", "rackspace")

creds_file = os.path.expanduser("C:\Python27\Scripts\credentials_file_Bob.py")
pyrax.set_credential_file(creds_file)

imgs = pyrax.images
cf = pyrax.cloudfiles

print("You will need an image file stored in a Cloud Files container.")
conts = cf.list()
print()
print("Select the container containing the image to import:")
for pos, cont in enumerate(conts):
    print("[%s] %s" % (pos, cont.name))
snum = raw_input("Enter the number of the container: ")
if not snum:
    exit()
try:
    num = int(snum)
except ValueError:
    print("'%s' is not a valid number." % snum)
    exit()
if not 0 <= num < len(conts):
    print("'%s' is not a valid container number." % snum)
    exit()
def main():

    # Parse the command line arguments
    parser = argparse.ArgumentParser(
        description="Create Multiple Webheads",
        prog='cf_create_multiple_webheads.py')
    parser.add_argument(
        '--image', help='image id or name (default: CentOS 6.3)',
        default='CentOS 6.3')
    parser.add_argument(
        '--flavor',
        help='flavor id or name (default: 512MB Standard Instance)',
        default='512MB Standard Instance')
    parser.add_argument(
        '--webhead_count', help='Number of webheads to create(default: 3)',
        default=3)
    parser.add_argument(
        '--webhead_prefix', help='webhead prefix(default: web)',
        default='web')
    parser.add_argument(
        '--region', help='Region(default: DFW)', default='DFW')
    args = parser.parse_args()

    # Set the region
    pyrax.set_default_region(args.region)

    # Server Data Dictionary
    server_data = dict()

    # Authenticate using a credentials file: "~/.rackspace_cloud_credentials"
    cred_file = "%s/.rackspace_cloud_credentials" % (os.environ['HOME'])
    print "Setting authentication file to %s" % (cred_file)
    pyrax.set_credential_file(cred_file)

    # Instantiate a cloudservers object
    print "Instantiating cloudservers object"
    csobj = pyrax.cloudservers

    # Get the flavor id
    flavor_id = get_flavor_id(csobj, args.flavor)

    # Get the image id
    image_id = get_image_id(csobj, args.image)

    # Create the servers by server_count
    for webhead_num in range(1, args.webhead_count + 1):
        webhead_name = "%s%d" % (args.webhead_prefix, webhead_num)
        new_server = create_webhead(csobj, webhead_name, flavor_id, image_id)
        try:
            new_server.adminPass
        except AttributeError:
            print "%s existed, so password can't be pulled" % (webhead_name)
            server_data[webhead_name] = {'password': '******',
                                         'ipaddr': '0',
                                         'id': new_server.id}
        else:
            print new_server.adminPass
            server_data[webhead_name] = {'password': new_server.adminPass,
                                         'ipaddr': '0',
                                         'id': new_server.id}

    # Call function to wait on ip addresses to be assigned and
    # update server_data
    updated_server_data = wait_and_update(csobj, server_data)

    # Print the data
    print_server_data(updated_server_data)
    def handle(self, *args, **options):
        pyrax.set_setting("identity_type", "rackspace")
        pyrax.set_default_region('DFW')
        account = options["account"] or get_config('rackspace', 'username')
        api_key = options["api_key"] or get_config('rackspace', 'api_key')

        if not account:
            print("Please provide your username by using --account or in DEPLOY_CONFIG['rackspace']['username']")
            return

        if not api_key:
            print("Please provide your username by using --api-key or in DEPLOY_CONFIG['rackspace']['api_key']")
            return

        pyrax.set_credentials(account, api_key)

        server_name = options["server"]
        if not server_name:
            print("Please provide a server name with --server")
            return

        print("Contacting Rackspace")
        cs = pyrax.cloudservers
        servers = cs.list()

        for server in servers:
            if server.name == server_name:
                print("Nothing to do, %s already exists" % server_name)
                return 

        # Create the server
        default_image = options["image"] or get_config('rackspace', 'default_image')
        default_flavor = options["flavor"] or get_config('rackspace', 'default_flavor')

        if not default_image:
            print "Select an image"
            images = sorted(cs.list_images(), key=lambda image: image.name)
            for i in range(len(images)):
                image = images[i]
                print " %s. %s (%s)" % (i+1, image.name, image.id)

            selected_image_index = input("Which image should we build? ")
            selected_image = images[selected_image_index - 1]

            print("")
            print("Will build image: %s" % selected_image.name)
            print("")
        else:
            selected_image = cs.images.get(default_image)

        if not default_flavor:
            print "Select flavor"
            flavors = sorted(cs.list_flavors(), key=lambda flavor: flavor.name)

            for i in range(len(flavors)):
                flavor = flavors[i]
                print " %s. %s (%s)" % (i+1, flavor.name, flavor.id)

            selected_flavor_index = input("Which flavor should we build? ")
            selected_flavor = flavors[selected_flavor_index - 1]

            print("")
            print("Will build flavor: %s" % selected_flavor.name)
            print("")
        else:
            selected_flavor = cs.flavors.get(default_flavor)


        confirmation = unicode(raw_input("Go ahead and build %s %s? [Y/n] " % (selected_image.name, selected_flavor.name))) or ""
        if confirmation.lower() in ["n", "no"]:
            print("Exiting ...")
            return

        print("")
        print("............................")
        print("Building the server")
        server = cs.servers.create(server_name, selected_image.id, selected_flavor.id, 
            key=api_key)
        admin_psw = server.adminPass
        pyrax.utils.wait_for_build(server)

        print("Server is ready!")
        server = cs.servers.get(server.id)
        ips = [ ip for ip in server.networks.get("public") if ip.count(".") == 3 ]
        ip = ips[0]

        print("Writing credentials file")
        # write it to a file 
        self.save_credentials(server_name, "root", admin_psw, ip)

        print("All done")
Exemplo n.º 31
0
                    required=True,
                    help='Rackspace Username.')
parser.add_argument('--api-key',
                    '-k',
                    dest="api_key",
                    required=True,
                    help='Rackspace API Key.')
parser.add_argument('--remove',
                    '-d',
                    dest="remove",
                    action='store_true',
                    help='remove the specified node from the loadbalancer.')
args = parser.parse_args()

pyrax.set_setting("identity_type", "rackspace")
pyrax.set_default_region(args.region)
pyrax.set_credentials(args.username, args.api_key)

clb = pyrax.connect_to_cloud_loadbalancers(args.region.upper())

lb = clb.get(args.loadbalancer)
if args.remove:
    try:
        node = [node for node in lb.nodes if node.address == args.ip]
        node.delete()
    except Exception as e:
        msg = "Failed to remove instance {0} from LB {1}: {2}"
        print(msg.format(args.instance, args.loadbalancer, e))
        sys.exit(1)
else:
    try:
Exemplo n.º 32
0
import pyrax
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_bootstrap import Bootstrap
from flask_github import GitHub

app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile('default.cfg')
app.config.from_pyfile('application.cfg', silent=True)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
github = GitHub(app)
Bootstrap(app)

pyrax.set_setting('identity_type', app.config['AUTH_SYSTEM'])
pyrax.set_default_region(app.config['AUTH_SYSTEM_REGION'])
pyrax.set_credentials(app.config['USERNAME'], app.config['API_KEY'])
nova = pyrax.cloudservers

from views import about  # noqa: E402, F401
from model import User, NodeRequest, Vm  # noqa: E402, F401

db.create_all()
Exemplo n.º 33
0
 def test_set_default_region(self):
     orig_region = pyrax.default_region
     new_region = "test"
     pyrax.set_default_region(new_region)
     self.assertEqual(pyrax.default_region, new_region)
     pyrax.default_region = orig_region
	print "\n"
	print "Please install Pyrax from 'https://github.com/rackspace/pyrax'."
import os
import sys
import multiprocessing

username = raw_input('Please enter your USERNAME: '******'Please enter your APIKEY: ')
my_region = raw_input("Please enter the container REGION: ")
my_container = raw_input("Please enter the name of the CONTAINER: ")

#Set identity
pyrax.set_setting('identity_type', 'rackspace')
pyrax.set_credentials(username, api_key, authenticate=True)
pyrax.set_http_debug(hDebug)
pyrax.set_default_region(my_region)
pyrax.settings.set("region",my_region)
cfiles = pyrax.connect_to_cloudfiles(region=my_region, public=isPublic)

cont = cfiles.get_container(my_container)
download_me = cont.get_object_names(full_listing=True)
#list_to_download = cont.get_objects(limit=100)
#download_me = [obj.name for obj in list_to_download]

#Create directory to represent top level container
if not os.path.exists(my_container):
	try:
		os.makedirs(my_container)
	except Exception as e:
		print e
		sys.exit(1)
Exemplo n.º 35
0
import pyrax, time, uuid

# RAX account info
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_default_region('IAD')
pyrax.set_credentials(os.environ['RAX_ID'], os.environ['RAX_KEY'])	

#assign generated client ID (see authentication section)
MY_CLIENT_ID = str(uuid.uuid4())

while True:
	# Connect to RAX Cloud Queues
	pyrax.queues.client_id = MY_CLIENT_ID
	queue = pyrax.queues.get("sample_queue")
	msg_body = "Generated at: %s" % time.strftime("%c")
	queue.post_message(msg_body, ttl=300)
	print msg_body
	time.sleep(5)
Exemplo n.º 36
0
#!/usr/bin/python
print "Build a Rackspace VM"

import time
print "CTRL + C to exit: sleep 10"
time.sleep(10)

import logging
logging.captureWarnings(True)

import pyrax
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_default_region('{region"') # replace {region} with the region of the Datacenter e.g. DFW
pyrax.set_credentials('{username}', '{apiKey}') # replace {username} & {apiKey} with your RS info

cs = pyrax.cloudservers

image = pyrax.images.get('{image#}') # replace {image#} with rs image number that you want to use
print "Server Image:"
print(image)

flavor = cs.flavors.get('2') # set the flavor variable
print "Server Flavor is ID:"
print(flavor) 
print "ENTER FLAVOR INFO IF YOU WANT e.g. 512MB Standard Instance | 512ram | 20memory | 1cpu"

server = cs.servers.create('{servername}', image.id, flavor.id) # replace {servername} with the name of the server # building server

print "building server:  please wait"
pyrax.utils.wait_for_build(server, verbose=True) # checking status of the build
Exemplo n.º 37
0
    # #Initialize the COUNTER variable and set to 1.
    COUNTER = 1
    #Initialize the ENDPOINT variable.  This will be assigned a value inside
    #the main() function
    ENDPOINT = ''

    #==========================================================================
    #SET UP CLOUD FILES ENVIRONMENT
    #==========================================================================
    ticks = 0
    max_ticks = 3
    loop = True
    while loop:
        try:
            pyrax.set_setting("identity_type", "rackspace")
            pyrax.set_default_region(REGION)
            pyrax.set_credentials(USERNAME, APIKEY)
            TOKEN = pyrax.identity.token
        except Exception as e:
            if ticks == max_ticks:
                print "\r\n\r%s\n" % e
                print "\rEXITING DUE TO ERROR DURING PYRAX AUTHENTICATION SETUP!"
                sys.exit(1)
            print "\rERROR!\n\r%s" % e
            print "\rSleeping 1 second and retrying..."
            time.sleep(1.0)
            ticks += 1
        finally:
            loop = False
            ticks = 0
    #Rackspace service catalog
Exemplo n.º 38
0
 def getregion():
   region = str(raw_input ("What region would you like to set? Please use capital letters and the following choices: ( DFW | ORD ) "))
   while region not in ["ORD", "DFW"]:
     print "Invalid region selection, please try again, hint: use capital letters."
     getregion()
   pyrax.set_default_region(region)
Exemplo n.º 39
0
 def test_set_default_region(self):
     orig_region = pyrax.default_region
     new_region = "test"
     pyrax.set_default_region(new_region)
     self.assertEqual(pyrax.default_region, new_region)
     pyrax.default_region = orig_region
Exemplo n.º 40
0
 def setUp(self):
     pyrax.set_setting('identity_type', 'rackspace')
     pyrax.set_default_region(RACKSPACE_REGION)
     pyrax.set_credentials(RACKSPACE_USERNAME, RACKSPACE_API_KEY)
     self.container = pyrax.cloudfiles.create_container(self.container_name)
     self.container.delete_all_objects()
Exemplo n.º 41
0
def main():
    custom_excepthook.original_excepthook = sys.excepthook
    sys.excepthook = custom_excepthook

    arguments = get_arguments()

    pyrax.set_default_region(arguments.rackzone)
    pyrax.set_setting('identity_type', 'rackspace')
    pyrax.set_credentials(arguments.rackuser, arguments.rackpass, region=arguments.rackzone)

    flavor_obj = pyrax.cloudservers.flavors.get(arguments.rackflavor)
    distro_obj = pyrax.cloudservers.images.get(arguments.rackdistro)

    load_balancer = None
    for balancer in pyrax.cloud_loadbalancers.list():
        if arguments.load_balancer in (str(balancer.id), balancer.name):
            load_balancer = balancer
            break

    arguments.load_balancer = load_balancer if load_balancer else None
    if not load_balancer:
        print (
            'WARNING: Load balancer "{load_balancer}" not found.' +
            'Continuing without registering any server in any load balancer'
        ).format(
            load_balancer=arguments.load_balancer,
        )

    watchers = []

    for index in xrange(arguments.count):
        # server_arguments = deepcopy(arguments)
        server_arguments = copy(arguments)
        server_arguments.hostname = arguments.hostname.format(hash=uuid4().hex,
            zone=server_arguments.rackzone.lower())
        server = pyrax.cloudservers.servers.create(
            name=server_arguments.hostname,
            image=distro_obj,
            flavor=flavor_obj,
            availability_zone=server_arguments.rackzone,
            key_name=server_arguments.sshkey,
            networks=[
                {'uuid': '11111111-1111-1111-1111-111111111111', },
                {'uuid': '00000000-0000-0000-0000-000000000000', },
            ]
        )
        watcher = ServerWatcherThread(
            server, initial_ip=server_public_addr(server))
        setattr(watcher, 'server_arguments', server_arguments)
        watcher.start()
        watchers.append(watcher)

    for watcher in watchers:
        try:
            watcher.join()
        except KeyboardInterrupt:
            ServerWatcherThread.stop_threads = True
            raise

    for watcher in watchers:
        run_deploy_script(watcher.server, watcher.server_arguments)
Exemplo n.º 42
0
# Create compute node
import pyrax

pyrax.set_setting("identity_type", "rackspace")
pyrax.set_default_region('{region}')
pyrax.set_credentials(file)

cs = pyrax.cloudservers

image = pyrax.images.get('88928a0a-f94c-47e3-ad7d-27b735af1a15')

flavor = cs.flavors.get('performance2-30')

server = cs.servers.create('transcoder', image.id, flavor.id)

pyrax.utils.wait_for_build(server, verbose=True)

# Build script to Install HandbrakeCLI

pacman -Sy handbrake-cli --no-prompt

# Delete node
Exemplo n.º 43
0
from __future__ import print_function

import os
import pyrax

pyrax.set_default_region("ORD")
pyrax.set_setting("identity_type", "rackspace")

creds_file = os.path.expanduser("C:\Python27\Scripts\credentials_file_Bob.py")
pyrax.set_credential_file(creds_file)

imgs = pyrax.images
cf = pyrax.cloudfiles

print("You will need an image file stored in a Cloud Files container.")
conts = cf.list()
print()
print("Select the container containing the image to import:")
for pos, cont in enumerate(conts):
    print("[%s] %s" % (pos, cont.name))
snum = raw_input("Enter the number of the container: ")
if not snum:
    exit()
try:
    num = int(snum)
except ValueError:
    print("'%s' is not a valid number." % snum)
    exit()
if not 0 <= num < len(conts):
    print("'%s' is not a valid container number." % snum)
    exit()
Exemplo n.º 44
0
+#Authentication
import os, os.path, pyrax, pyrax.exceptions as exc, time
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_default_region('select data center')
pyrax.set_credentials("rackspace_username", "apikey")
cf = pyrax.cloudfiles

#Container & StorageObject
cont = cf.get_container("container")
objs = cont.get_objects()

#Date & Time
now = time.time()
deltime = os.path.getmtime in objs
difftime = now - deltime

#Fetch File
for obj in objs:
    if difftime < (30 * 86400):
     cf.download_object("container",obj.name,"download_location",structure=False);
  
#Clean up
for obj in objs:
    if difftime > (30 * 86400):
        cont.delete_object(obj.name)
Exemplo n.º 45
0
import os
import time

import pyrax
import pyrax.exceptions as exc

pyrax.set_default_region("LON")
pyrax.set_setting("identity_type", "rackspace")

creds_file = os.path.expanduser("C:\Python27\Scripts\credentials_file.py")
pyrax.set_credential_file(creds_file)

cf = pyrax.cloudfiles

#Set which conatiner you are going to delete
cont = cf.get_container("cloudservers")
start = time.time()
objects = cont.get_objects()


#Below section has been commented out, you can add this back if you want to list all the objects in a container
for obj in objects:
    if "SMB" in obj.name:
        print obj.name

    
"""

cont.delete_all_objects()

#Check if there are any objects left, if there are provide an update
Exemplo n.º 46
0
import os
import pyrax
pyrax.set_default_region("SYD")
pyrax.set_setting("identity_type", "rackspace")

creds_file = os.path.expanduser("C:\Python27\Scripts\credentials_file.py")
pyrax.set_credential_file(creds_file)

cf = pyrax.cloudfiles

print "list_containers:", cf.list_containers()