def check_usage(instance_id, threshold, region):
    pyrax.set_credential_file(
        os.path.expanduser("~/.rackspace_cloud_credentials"))
    cdb = pyrax.connect_to_cloud_databases(region=region)

    matched_instance = None
    for instance in cdb.list():
        if instance.id == instance_id:
            matched_instance = instance
    if not matched_instance:
        print 'status error Unable to find instance', instance_id
        sys.exit(1)

    # Force usage lookup
    matched_instance.get()
    database_size = matched_instance.volume['size']
    database_usage = matched_instance.volume['used']
    percentage_used = database_usage / database_size

    if percentage_used >= threshold:
        print 'status error usage over threshold'
    else:
        print 'status ok usage within threshold'

    print "metric database_GB_container_size float", database_size
    print "metric database_GB_used float", database_usage
    print "metric percentage_used float", percentage_used
Ejemplo n.º 2
0
def delete_rax_cdb(args):
    """Function for deleting Cloud Databases"""
    print("--- Cleaning Cloud Databases matching '%s'" % args.match_re)
    for region in pyrax.identity.services.database.regions:
        cdb = pyrax.connect_to_cloud_databases(region=region)
        for db in rax_list_iterator(cdb):
            if re.search(args.match_re, db.name):
                prompt_and_delete(db, 'Delete matching %s? [y/n]: ' % db,
                                  args.assumeyes)
Ejemplo n.º 3
0
def delete_rax_cdb(args):
    """Function for deleting Cloud Databases"""
    print ("--- Cleaning Cloud Databases matching '%s'" % args.match_re)
    for region in pyrax.identity.services.database.regions:
        cdb = pyrax.connect_to_cloud_databases(region=region)
        for db in rax_list_iterator(cdb):
            if re.search(args.match_re, db.name):
                prompt_and_delete(db,
                                  'Delete matching %s? [y/n]: ' % db,
                                  args.assumeyes)
Ejemplo n.º 4
0
def _get_driver(driver_type, region='ORD'):
    """
    Returns the appropriate diver for the specified rackspace product.

    Available options include::
        lb: Cloud Load Balancers
        db: Cloud Databases
        dns: Cloud DNS
        bs: Cloud Block Storage
        mon: Cloud Monitoring
        net: Cloud Networks
        cf: Cloud Files
        cs: Cloud Servers

    :param driver_type: A str or unicode object for the appropriate type of
    driver above.
    :param region: A str or unicode object specify which region the driver
    should be initialized for.
    :return: A driver object initialized to the specified region
    :raise TypeError:
    :raise KeyError: If no valid drivers are found
    """
    _auth()
    if not isinstance(driver_type, six.string_types):
        raise TypeError("driver_type must be str or unicode object")
    if not isinstance(region, six.string_types):
        raise TypeError("region must be str or unicode object")
    region = region.upper()

    if driver_type == "lb":
        return pyrax.connect_to_cloud_loadbalancers(region)

    if driver_type == "db":
        return pyrax.connect_to_cloud_databases(region)

    if driver_type == "dns":
        return pyrax.connect_to_cloud_dns()

    if driver_type == "bs":
        return pyrax.connect_to_cloud_blockstorage(region)

    if driver_type == "mon":
        return pyrax.connect_to_cloud_monitoring(region)

    if driver_type == "net":
        return pyrax.connect_to_cloud_networks(region)

    if driver_type == 'cf':
        return pyrax.connect_to_cloudfiles(region)

    if driver_type == 'cs':
        return pyrax.connect_to_cloudservers(region)

    raise KeyError(u"No Driver found by: {}".format(driver_type))
Ejemplo n.º 5
0
def _get_driver(driver_type, region='ORD'):
    """
    Returns the appropriate diver for the specified rackspace product.

    Available options include::
        lb: Cloud Load Balancers
        db: Cloud Databases
        dns: Cloud DNS
        bs: Cloud Block Storage
        mon: Cloud Monitoring
        net: Cloud Networks
        cf: Cloud Files
        cs: Cloud Servers

    :param driver_type: A str or unicode object for the appropriate type of
    driver above.
    :param region: A str or unicode object specify which region the driver
    should be initialized for.
    :return: A driver object initialized to the specified region
    :raise TypeError:
    :raise KeyError: If no valid drivers are found
    """
    _auth()
    if not isinstance(driver_type, six.string_types):
        raise TypeError("driver_type must be str or unicode object")
    if not isinstance(region, six.string_types):
        raise TypeError("region must be str or unicode object")
    region = region.upper()

    if driver_type == "lb":
        return pyrax.connect_to_cloud_loadbalancers(region)

    if driver_type == "db":
        return pyrax.connect_to_cloud_databases(region)

    if driver_type == "dns":
        return pyrax.connect_to_cloud_dns()

    if driver_type == "bs":
        return pyrax.connect_to_cloud_blockstorage(region)

    if driver_type == "mon":
        return pyrax.connect_to_cloud_monitoring(region)

    if driver_type == "net":
        return pyrax.connect_to_cloud_networks(region)

    if driver_type == 'cf':
        return pyrax.connect_to_cloudfiles(region)

    if driver_type == 'cs':
        return pyrax.connect_to_cloudservers(region)

    raise KeyError(u"No Driver found by: {}".format(driver_type))
Ejemplo n.º 6
0
def main():

    default_creds_file = os.path.join(os.path.expanduser("~"), 
        ".rackspace_cloud_credentials")

    parser = argparse.ArgumentParser(description = "Create a Cloud Database"
        " instance with a database and a user.", 
        epilog = "{} -r DFW -f 1024 -s 1 -i mysql1 -d db1 -u user1 -p passw0rd"
        "\nCreate a 1GB RAM, 1GB disk space instance with the given names.".format(__file__))
    parser.add_argument('-r', '--region', choices = ['DFW', 'ORD', 
        'LON'], help = "Region to connect to", required = True)
    parser.add_argument('-f', '--flavor_ram', type = int, 
        help = "RAM amount for instance in MB", required = True)
    parser.add_argument('-s', '--disk_space', type = int, 
        help = "Amount of disk space to allocate in GB", required = True)
    parser.add_argument('-i', '--instance_name', 
        help = "Name of MySQL instance to create", required = True)
    parser.add_argument('-d', '--db_name', 
        help = "Name of database to create", required = True)
    parser.add_argument('-u', '--user_name', 
        help = "User to create", required = True)
    parser.add_argument('-p', '--password', 
        help = "Password for user", required = True)
    parser.add_argument('-c', '--creds_file', default = default_creds_file, 
        help = "Location of credentials file; defaults to {}".format(default_creds_file))

    args = parser.parse_args()

    pyrax.set_setting("identity_type", "rackspace")
    creds_file = os.path.abspath(os.path.expanduser(args.creds_file)) 
    pyrax.set_credential_file(creds_file)

    cdb = pyrax.connect_to_cloud_databases(region = args.region)
    flavor = choose_db_instance_flavor(cdb, 
        "Chosen flavor RAM invalid, choose a valid amount: ", str(args.flavor_ram))
    
    instance = create_clouddb_instance(cdb, args.instance_name, 
        flavor, args.disk_space)

    db = create_clouddb_database(cdb, instance, args.db_name)
    user = create_db_user(cdb, instance, args.user_name, args.password, [db.name])
    print
Ejemplo n.º 7
0
def main():

    default_creds_file = os.path.join(os.path.expanduser("~"), 
        ".rackspace_cloud_credentials")

    parser = argparse.ArgumentParser(description = "Deletes all objects in "
        "various cloud resource categories.", 
        epilog = "Ex: {} -r ORD --servers --images --load_balancers - delete "
        "all cloud servers, custom images, and load balancers in ORD "
        "region".format(__file__))
    parser.add_argument('-r', '--region', required = True, 
        choices = ['DFW', 'ORD', 'LON'], 
        help = "Cloud Servers region to delete from")
    parser.add_argument('-a', '--all', action = 'store_true', 
        help = "Delete all items in region; equiv to setting all option args")
    parser.add_argument('-s', '--servers', action = 'store_true', 
        help = "Delete all Cloud Servers")
    parser.add_argument('-i', '--images', action = 'store_true', 
        help = "Delete all custom Cloud Server images")
    parser.add_argument('-l', '--load_balancers', action = 'store_true', 
        help = "Delete all Cloud Load Balancers")
    parser.add_argument('-f', '--files', action = 'store_true', 
        help = "Delete all Cloud Files containers and objects")
    parser.add_argument('-d', '--databases', action = 'store_true', 
        help = "Delete all Cloud Database databases and instances")
    parser.add_argument('-n', '--networks', action = 'store_true', 
        help = "Delete all custom Cloud Networks")
    parser.add_argument('-b', '--block_storage', action = 'store_true', 
        help = "Delete all Cloud Block Storage volumes")
    parser.add_argument('-c', '--creds_file', default = default_creds_file, 
        help = "Location of credentials file; defaults to {}".format(default_creds_file))

    args = parser.parse_args()

    pyrax.set_setting("identity_type", "rackspace")
    creds_file = os.path.abspath(os.path.expanduser(args.creds_file)) 
    pyrax.set_credential_file(creds_file)

    if(args.all):
        args.servers = True
        args.images = True
        args.load_balancers = True
        args.files = True
        args.databases = True
        args.networks = True
        args.block_storage = True

    if(args.servers):
        cs = pyrax.connect_to_cloudservers(region = args.region)
        servers = cs.servers.list()
        print "Deleting {} Cloud Servers...".format(len(servers))
        delete_resources(servers)

    if(args.images):
        custom_images = []
        cs = pyrax.connect_to_cloudservers(region = args.region)
        images = cs.images.list()
        for image in images:
            if not image.metadata['image_type'] == 'base':
                custom_images.append(image)
        print "Deleting {} custom server images...".format(len(custom_images))
        delete_resources(custom_images)

    if(args.load_balancers):
        clb = pyrax.connect_to_cloud_loadbalancers(region = args.region)
        lbs = clb.list()
        print "Deleting {} Cloud Load Balancers...".format(len(lbs))
        delete_resources(lbs)

    if(args.files):
        cf = pyrax.connect_to_cloudfiles(region = args.region)
        for container in cf.get_all_containers():
            print "Emptying Cloud Files container '{}'...".format(container.name)
            delete_resources(container.get_objects(full_listing = True))
            while len(container.get_objects(limit = 1)) > 0:
                time.sleep(5)
            print "Deleting container '{}'...".format(container.name)
            container.delete()

    if(args.databases):
        cdb = pyrax.connect_to_cloud_databases(region = args.region)
        instances = cdb.list()
        print "Deleting {} Cloud Database instances...".format(len(instances))
        delete_resources(instances)

    if(args.networks):
        custom_networks = []
        cnw = pyrax.connect_to_cloud_networks(region = args.region)
        networks = cnw.list()
        for network in networks:
            if not network.label == 'public' and not network.label == 'private':
                custom_networks.append(network)
        print "Deleting {} custom Cloud Networks...".format(len(custom_networks))
        delete_resources(custom_networks)

    if(args.block_storage):
        cbs = pyrax.connect_to_cloud_blockstorage(region = args.region)
        volumes = cbs.list()
        print "Deleting {} Cloud Block Storage volumes...".format(len(volumes))
        delete_resources(volumes)
Ejemplo n.º 8
0
  parser.add_argument("Instance", 
                      help="Name of CloudDatabase Instance to create")
  parser.add_argument("Schema", help="Name of database schema to create") 
  parser.add_argument("User", help="Username for database access")
  parser.add_argument("--flavor", default=1, 
                      help="Flavor of CloudDatabase to create")
  parser.add_argument("--volumesize", default=1, type=int,
                      help="Size of database volume (GB)")
  parser.add_argument("--region", default='DFW',
                      help="Region in which to create database (DFW or ORD)")
  args = parser.parse_args()

  credential_file = os.path.expanduser("~/.rackspace_cloud_credentials")
  pyrax.set_credential_file(credential_file)
  if c1.is_valid_region(args.region, 'database'):
    cdb = pyrax.connect_to_cloud_databases(region=args.region)
  else:
    print "The region you requested is not valid: %s" % args.region
    sys.exit(2)

  if not is_valid_db_flavor(cdb, args.flavor):
    print "This is not a valid CloudDatabase flavor-id: %s" % args.flavor
    sys.exit(3)

  if args.volumesize < 1 or args.volumesize > 150:
    print "The requested volume size is not valid: %d" % args.volumesize
    sys.exit(4)

  # unbuffer stdout for pretty output
  sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
Ejemplo n.º 9
0
 def test_connect_to_cloud_databases(self):
     pyrax.cloud_databases = None
     pyrax.connect_to_cloud_databases = self.orig_connect_to_cloud_databases
     pyrax.cloud_databases = pyrax.connect_to_cloud_databases()
     self.assertIsNotNone(pyrax.cloud_databases)
Ejemplo n.º 10
0
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import os
import sys
import time
import pyrax

creds_file = os.path.expanduser("~/.rackspace_cloud_credentials")
pyrax.set_credential_file(creds_file)

region = int(raw_input ("Select 1 for ORD, 2 for DFW, 3 for LON: "))

if region == 1:
  cdb = pyrax.connect_to_cloud_databases(region="ORD")
elif region == 2:
  cdb = pyrax.connect_to_cloud_databases(region="ORD")
elif region == 3:
  cdb = pyrax.connect_to_cloud_databases(region="LON")
else:
  print "Invalid region...  exiting"
  quit()

instname = str(raw_input("What should the Cloud DB Instance be named? "))
print

dbname = str(raw_input("What database name should be created? " ))
print

username = str(raw_input("What username name should be created? " ))
Ejemplo n.º 11
0
    parser.add_argument('--apikey',
                        '-k',
                        required=True,
                        help='Set\'s the account API key')
    parser.add_argument('--region',
                        '-r',
                        required=True,
                        help='Set\'s the account region')
    args = parser.parse_args()

    pyrax.set_credentials(username=args.user,
                          api_key=args.apikey,
                          region=args.region)
    if args.region == 'ORD':
        cs = pyrax.connect_to_cloudservers("ORD")
        cdb = pyrax.connect_to_cloud_databases("ORD")
        cnw = pyrax.connect_to_cloud_networks("ORD")
        cbs = pyrax.connect_to_cloud_blockstorage("ORD")
        dns = pyrax.connect_to_cloud_dns("ORD")
        lbs = pyrax.connect_to_cloud_loadbalancers("ORD")
    elif args.region == 'DFW':
        cs = pyrax.connect_to_cloudservers("DFW")
        cdb = pyrax.connect_to_cloud_databases("DFW")
        cnw = pyrax.connect_to_cloud_networks("DFW")
        cbs = pyrax.connect_to_cloud_blockstorage("DFW")
        dns = pyrax.connect_to_cloud_dns("DFW")
        lbs = pyrax.connect_to_cloud_loadbalancers("DFW")
    elif args.region == 'LON':
        cs = pyrax.connect_to_cloudservers("LON")
        cdb = pyrax.connect_to_cloud_databases("LON")
        cnw = pyrax.connect_to_cloud_networks("LON")
Ejemplo n.º 12
0
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Builds servers')
    parser.add_argument(
        '--user', '-u', required=True, help='Set\'s the account user')
    parser.add_argument(
        '--apikey', '-k', required=True, help='Set\'s the account API key')
    parser.add_argument(
        '--region', '-r', required=True, help='Set\'s the account region')
    args = parser.parse_args()

    pyrax.set_credentials(
        username=args.user, api_key=args.apikey, region=args.region)
    if args.region == 'ORD':
        cs = pyrax.connect_to_cloudservers("ORD")
        cdb = pyrax.connect_to_cloud_databases("ORD")
        cnw = pyrax.connect_to_cloud_networks("ORD")
        cbs = pyrax.connect_to_cloud_blockstorage("ORD")
        dns = pyrax.connect_to_cloud_dns("ORD")
        lbs = pyrax.connect_to_cloud_loadbalancers("ORD")
    elif args.region == 'DFW':
        cs = pyrax.connect_to_cloudservers("DFW")
        cdb = pyrax.connect_to_cloud_databases("DFW")
        cnw = pyrax.connect_to_cloud_networks("DFW")
        cbs = pyrax.connect_to_cloud_blockstorage("DFW")
        dns = pyrax.connect_to_cloud_dns("DFW")
        lbs = pyrax.connect_to_cloud_loadbalancers("DFW")
    elif args.region == 'LON':
        cs = pyrax.connect_to_cloudservers("LON")
        cdb = pyrax.connect_to_cloud_databases("LON")
        cnw = pyrax.connect_to_cloud_networks("LON")
 Worth 3 points
"""

from __future__ import print_function
import pyrax
from os.path import expanduser
from time import sleep


if __name__ == "__main__":
    pyrax.set_credential_file(expanduser("~/.rackspace_cloud_credentials"))
    cs_ord = pyrax.connect_to_cloudservers("ORD")
    cs_dfw = pyrax.connect_to_cloudservers("DFW")
    cf_ord = pyrax.connect_to_cloudfiles("ORD")
    cf_dfw = pyrax.connect_to_cloudfiles("DFW")
    cdb_ord = pyrax.connect_to_cloud_databases("ORD")
    cdb_dfw = pyrax.connect_to_cloud_databases("DFW")
    cnw_ord = pyrax.connect_to_cloud_networks("ORD")
    cnw_dfw = pyrax.connect_to_cloud_networks("DFW")
    cbs_ord = pyrax.connect_to_cloud_blockstorage("ORD")
    cbs_dfw = pyrax.connect_to_cloud_blockstorage("DFW")
    dns_ord = pyrax.connect_to_cloud_dns("ORD")
    dns_dfw = pyrax.connect_to_cloud_dns("DFW")
    lbs_ord = pyrax.connect_to_cloud_loadbalancers("ORD")
    lbs_dfw = pyrax.connect_to_cloud_loadbalancers("DFW")

    print("deleting servers")
    for server in cs_ord.servers.list():
        server.delete()
    for server in cs_dfw.servers.list():
        server.delete()
Ejemplo n.º 14
0
 def test_connect_to_cloud_databases(self):
     pyrax.cloud_databases = None
     pyrax.connect_to_cloud_databases = self.orig_connect_to_cloud_databases
     pyrax.cloud_databases = pyrax.connect_to_cloud_databases()
     self.assertIsNotNone(pyrax.cloud_databases)
Ejemplo n.º 15
0
                    dest="interval",
                    type=int,
                    default=5,
                    help="wait INTERVAL seconds between status checks",
                    metavar="INTERVAL")
parser.add_argument("-d",
                    dest="dc",
                    default="DFW",
                    help="use data center DC",
                    metavar="DC")

args = parser.parse_args()

pyrax.set_credential_file(os.path.expanduser("~/.rackspace_cloud_credentials"))

cs = pyrax.connect_to_cloud_databases(region=args.dc)

# check for valid flavor
flavors = cs.list_flavors()
flavor = None
for f in flavors:
    if f.id == args.flavor:
        flavor = f
if flavor is None:
    print "Flavor %s not found.  Please specify an existing flavor ID:" % (
        args.flavor)
    for f in flavors:
        print "ID: %s  Name: %s" % (f.id, f.name)
    exit(1)

# create database instance
Ejemplo n.º 16
0
import pyrax
import sys

#credentials
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_credential_file(".rackspace_cloud_credentials")
#services 
cdb = pyrax.cloud_databases
cdb = pyrax.connect_to_cloud_databases(region="IAD")

instances = cdb.list()
if not instances:
    print "There are no cloud database instances."
    print "Please create one and re-run this script."
    sys.exit()

print
print "Available Instances:"
for pos, inst in enumerate(instances):
    print "%s: %s (%s, RAM=%s, volume=%s) Status=%s" % (pos, inst.name,
            inst.flavor.name, inst.flavor.ram, inst.volume.size, inst.status)
Ejemplo n.º 17
0
import getpass

pyrax.set_credential_file(os.path.expanduser("~/.rackspace_cloud_credentials"))

#set variables
dbName= ""
while len(dbName) < 1:
	dbName = raw_input("Enter a name for your new Cloud Database: ")

dbRegion = ""
while dbRegion != "DFW" and dbRegion != "ORD":
	dbRegion = raw_input("Enter the region you want the Cloud Database instance built in (DFW or ORD): ")
dbFlavor = 1
dbVolume = 1

dbEndpoint = pyrax.connect_to_cloud_databases(dbRegion)
newDb = dbEndpoint.create(dbName, dbFlavor, dbVolume)
time.sleep(2)
newDbId = ""
while newDbId == "":
	for i in dbEndpoint.list():
		if i.name == dbName:
			newDbId = i.id
			# could 'break' here to match first occurrence, but actually want last / most recent, in case there are several
	time.sleep(1)
newDb = dbEndpoint.get(newDbId)
print "Waiting for new Cloud Database instance to finish building, this may take a few minutes..."
while newDb.status != "ACTIVE":
	if newDb.status == "ERROR":
		print "Unfortunately, your build has gone into an error state."
		print "If it cannot be deleted from the Control Panel, contact Rackspace Cloud Support"