Beispiel #1
0
def pi(x):
    v = []
    d = choose(x[0].shape[1], 2)  ##
    for i in x:
        s = i.sum(axis=1)
        k = []
        for j in s:
            n = choose(j, 2) + choose(i.shape[1] - j, 2)
            k.append((d - n) * d**-1)
        v.append(sum(k))
    return np.array(v)
Beispiel #2
0
def start_module():
    """
    Starts this module and displays its menu.
    User can access default special features from here.
    User can go back to main menu from here.

    Returns:
        None
    """
    table = data_manager.get_table_from_file(FILE_NAME)
    options = [
        ('Display table', lambda: display_table(table)),
        ('Add transaction', lambda: add(table)),
        ("Modify transaction data", lambda: update(table)),
        ("Remove transaction data", lambda: remove(table)),
        ("Display cheapest item", lambda: display_cheapest_item(table)),
        ("Display items sold between the dates", lambda: display_items(table)),
    ]
    stay = True
    while stay:
        ui.print_menu('Sales', options, 'Back to main menu')
        try:
            stay = common.choose(options, table)
        except KeyError as err:
            ui.print_error_message(err)
    data_manager.write_table_to_file(FILE_NAME, table)
Beispiel #3
0
def start_module():
    """
    Starts this module and displays its menu.
    User can access default special features from here.
    User can go back to main menu from here.
    Returns:
        None
    """
    table = data_manager.get_table_from_file(FILE_NAME)

    options = [
        ('Display', lambda: display_table(table)),
        ('Add', lambda: add(table)),
        ("Modify", lambda: update(table)),
        ("Delete", lambda: remove(table)),
        ("Availability", lambda: display_available_items(table)),
        ("Average durability",
         lambda: display_average_durability_by_manufacturers(table)),
    ]
    stay = True
    while stay:
        ui.print_menu('Inventories', options, 'Back to main menu')
        try:
            stay = common.choose(options, table)
        except KeyError as err:
            ui.print_error_message(err)
    data_manager.write_table_to_file(FILE_NAME, table)
Beispiel #4
0
def start_module():
    """
    Starts this module and displays its menu.
    User can access default special features from here.
    User can go back to main menu from here.
    Returns:
        None
    """
    table = data_manager.get_table_from_file(FILE_NAME)
    options = [
        ('Display games data', lambda: display_table(table)),
        ('Add new game data', lambda: add(table)),
        ("Modify games data", lambda: update(table)),
        ("Remove games data", lambda: remove(table)),
        ("Display number of types of games each manufacturer has", lambda: display_counts_by_manufacturers(table)),
        ("Display the average amount of games in stock of a given manufacturer",
         lambda: display_average_by_manufacturer(table)),
        ]
    stay = True
    while stay:
        ui.print_menu('Store manager', options, 'Back to main menu')
        try:
            stay = common.choose(options, table)
        except KeyError as err:
            ui.print_error_message(err)
    data_manager.write_table_to_file(FILE_NAME, table)
def terminate_cluster(aws_access_key_id, aws_secret_access_key, placement, search_term, prompt_continuation=False):

    # Grab all the infomation for clusters spawn by this tool that are still alive
    ds_reservations = {}
    conn = boto.ec2.connect_to_region(
        placement[:-1], aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key
    )

    try:
        reservations = conn.get_all_instances()
    except boto.exception.EC2ResponseError:
        print_boto_error()

    for reservation in reservations:
        if (
            "Initializer" in reservation.instances[0].tags
            and reservation.instances[0].tags["Initializer"] == "DataStax"
            and reservation.instances[0].update() == "running"
        ):
            if (
                "Name" in reservation.instances[0].tags
                and not reservation.instances[0].tags["Name"] in ds_reservations
                and search_term.lower() in reservation.instances[0].tags["Name"].lower()
            ):

                ds_reservations[reservation.instances[0].tags["Name"]] = {"Reservation": reservation}

    if not ds_reservations.keys():
        print "No existing clusters currently running!"
        print
        return

    # Prompt for cluster to destroy
    selection = common.choose("Choose the cluster to destroy (if you wish):", ds_reservations.keys(), noneOption=True)

    # Return if you do not with to kill a cluster
    if selection == "None":
        return

    # Confirm cluster termination
    print "Confirm you wish to terminate {0} by pressing 'y'.".format(selection)
    if raw_input().lower() != "y":
        print "Cluster was not terminated."
        print
        sys.exit()
    print

    # The actual termination command
    for instance in ds_reservations[selection]["Reservation"].instances:
        conn.terminate_instances([instance.id])

    print "Termination command complete."
    print

    if prompt_continuation:
        if raw_input("Do you wish to launch another cluster? [Y/n] ").lower() == "n":
            sys.exit(0)
        print
Beispiel #6
0
def check_cascading_options(option,
                            type_check=False,
                            choices=False,
                            password=False,
                            optional=False,
                            ignore_command_line=False):
    """Reads from the command line arguments, then configuration file, then prompts
    the user for program options."""
    section = options_tree[option]['Section']

    # Read from sys.argv
    if not ignore_command_line:
        read_option = cli_options['{0}_{1}'.format(section, option)]
        read_option = basic_option_checker(read_option, option, type_check,
                                           choices)
        if read_option != None:
            return read_option

    # Read from configfile
    if config.has_option(section, option):
        read_option = config.get(section, option)
        read_option = basic_option_checker(read_option, option, type_check,
                                           choices)
        if read_option != None:
            return read_option

    if optional:
        return False

    # Exit(1) if you asked for --noprompts and didn't fill in all variables
    if cli_options['CLI_noprompts']:
        sys.stderr.write('Prompt occurred after specifying --noprompts.\n')
        sys.stderr.write(
            'Missing/Invalid configuration for "--{0}".\n'.format(option))
        sys.exit(1)

    # Prompt for password if special case
    if password:
        return getpass.getpass()

    # Prompt the user with raw_input or common.choose
    while True:
        prompt = options_tree[option]['Prompt']
        if choices:
            response = common.choose(prompt, choices)
        else:
            response = raw_input('{0}: '.format(prompt))
        response = type_checker(option, response, type_check, passive=True)
        if response != None:
            break

    # Set config to avoid double prompting later (doesn't actually write to disk)
    config.set(section, option, response)
    return response
Beispiel #7
0
def terminate_cluster(aws_access_key_id, aws_secret_access_key, placement, search_term, prompt_continuation=False):

    # Grab all the infomation for clusters spawn by this tool that are still alive
    ds_reservations = {}
    conn = boto.ec2.connect_to_region(placement[:-1], aws_access_key_id=aws_access_key_id,
                                      aws_secret_access_key=aws_secret_access_key)

    try:
        reservations = conn.get_all_instances()
    except boto.exception.EC2ResponseError:
        print_boto_error()

    for reservation in reservations:
        if 'Initializer' in reservation.instances[0].tags and reservation.instances[0].tags['Initializer'] == 'DataStax' and reservation.instances[0].update() == 'running':
            if not reservation.instances[0].tags['Name'] in ds_reservations and search_term.lower() in reservation.instances[0].tags['Name'].lower():
                ds_reservations[reservation.instances[0].tags['Name']] = {
                    'Reservation': reservation
                }

    if not ds_reservations.keys():
        print "No existing clusters currently running!"
        print
        return

    # Prompt for cluster to destroy
    selection = common.choose("Choose the cluster to destroy (if you wish):", ds_reservations.keys(), noneOption=True)

    # Return if you do not with to kill a cluster
    if selection == 'None':
        return

    # Confirm cluster termination
    print "Confirm you wish to terminate {0} by pressing 'y'.".format(selection)
    if raw_input().lower() != 'y':
        print "Cluster was not terminated."
        print
        sys.exit()
    print

    # The actual termination command
    for instance in ds_reservations[selection]['Reservation'].instances:
        conn.terminate_instances([instance.id])

    print "Termination command complete."
    print

    if prompt_continuation:
        if raw_input('Do you wish to launch another cluster? [Y/n] ').lower() == 'n':
            sys.exit(0)
        print
Beispiel #8
0
def terminate_cluster(aws_access_key_id, aws_secret_access_key, search_term, prompt_continuation=False):

    # Grab all the infomation for clusters spawn by this tool that are still alive
    ds_reservations = {}
    conn = boto.connect_ec2(aws_access_key_id, aws_secret_access_key)

    try:
        reservations = conn.get_all_instances()
    except boto.exception.EC2ResponseError:
        print_boto_error()

    for reservation in reservations:
        if 'Initializer' in reservation.instances[0].tags and reservation.instances[0].tags['Initializer'] == 'DataStax' and reservation.instances[0].update() == 'running':
            if not reservation.instances[0].tags['Name'] in ds_reservations and search_term.lower() in reservation.instances[0].tags['Name'].lower():
                ds_reservations[reservation.instances[0].tags['Name']] = {
                    'Reservation': reservation
                }

    if not ds_reservations.keys():
        print "No existing clusters currently running!"
        print
        return

    # Prompt for cluster to destroy
    selection = common.choose("Choose the cluster to destroy (if you wish):", ds_reservations.keys(), noneOption=True)

    # Return if you do not with to kill a cluster
    if selection == 'None':
        return

    # Confirm cluster termination
    print "Confirm you wish to terminate {0} by pressing 'y'.".format(selection)
    if raw_input().lower() != 'y':
        print "Cluster was not terminated."
        print
        sys.exit()
    print

    # The actual termination command
    for instance in ds_reservations[selection]['Reservation'].instances:
        conn.terminate_instances([instance.id])

    print "Termination command complete."
    print

    if prompt_continuation:
        if raw_input('Do you wish to launch another cluster? [Y/n] ').lower() == 'n':
            sys.exit(0)
        print
def check_cascading_options(
    option, type_check=False, choices=False, password=False, optional=False, ignore_command_line=False
):
    """Reads from the command line arguments, then configuration file, then prompts
    the user for program options."""
    section = options_tree[option]["Section"]

    # Read from sys.argv
    if not ignore_command_line:
        read_option = cli_options["{0}_{1}".format(section, option)]
        read_option = basic_option_checker(read_option, option, type_check, choices)
        if read_option != None:
            return read_option

    # Read from configfile
    if config.has_option(section, option):
        read_option = config.get(section, option)
        read_option = basic_option_checker(read_option, option, type_check, choices)
        if read_option != None:
            return read_option

    if optional:
        return False

    # Exit(1) if you asked for --noprompts and didn't fill in all variables
    if cli_options["CLI_noprompts"]:
        sys.stderr.write("Prompt occurred after specifying --noprompts.\n")
        sys.stderr.write('Missing/Invalid configuration for "--{0}".\n'.format(option))
        sys.exit(1)

    # Prompt for password if special case
    if password:
        return getpass.getpass()

    # Prompt the user with raw_input or common.choose
    while True:
        prompt = options_tree[option]["Prompt"]
        if choices:
            response = common.choose(prompt, choices)
        else:
            response = raw_input("{0}: ".format(prompt))
        response = type_checker(option, response, type_check, passive=True)
        if response != None:
            break

    # Set config to avoid double prompting later (doesn't actually write to disk)
    config.set(section, option, response)
    return response
Beispiel #10
0
def terminate_cluster(rax_user, rax_api_key, search_term):

    # Grab all the infomation for clusters spawn by this tool that are still alive
    ds_reservations = {}
    cloudservers = CloudServers(rax_user, rax_api_key)
    try:
        serverlist = cloudservers.servers.list()
    except:
        sys.stderr.write('Rackspace authentication failed. Please check your Rackspace authentication and try again.\n')
        sys.exit(1)

    p = re.compile("{0}.*".format(search_term))

    for server in serverlist:
        if p.match(server.name):
            try:
                if cloudservers.servers.get(server.id).status == "ACTIVE":
                    if not server.name in ds_reservations:
                        ds_reservations[server.name] = {
                            'Servers': []
                        }
                    ds_reservations[server.name]['Servers'].append(server)
            except:
                # Server was recently shut down
                pass

    # Prompt for cluster to destroy
    selection = common.choose("Choose the cluster to destroy:", ds_reservations.keys())

    # Confirm cluster termination
    print "Confirm you wish to terminate {0} by pressing 'y'.".format(selection)
    if raw_input().lower() != 'y':
        print "Cluster was not terminated."
        print
        sys.exit()
    print

    # The actual termination command
    for server in ds_reservations[selection]['Servers']:
        try:
            server.delete()
        except:
            print "This server appears to have already been shut down. Please give it some time for the API to adjust."

    print "Termination command complete."
    print
Beispiel #11
0
def start_module():
    options = ['Display customers data',
                'Add new customer data',
                'Modify customers data',
                'Remove customers data',
                'Display id of the customer with the longest name',
                'Display email and name of customers that subscribed to the newsletter']
    stay = True
    while stay:
        ui.print_menu('Customer Relationship Management (CRM)', options, 'Back to main menu')
        try:
            stay = choose()
        except KeyError as err:
            ui.print_error_message(err)


    """
    Starts this module and displays its menu.
    User can access default special features from here.
    User can go back to main menu from here.

    Returns:
        None
    """
    table = data_manager.get_table_from_file(FILE_NAME)
    options = [
        ('Display customers data', lambda: display_table(table)),
        ('Add new customer data', lambda: add(table)),
        ("Modify customers data", lambda: update(table)),
        ("Remove customers data", lambda: remove(table)),
        ("Display id of the customer with the longest name", lambda: display_longest_name_id(table)),
        ("Display email and name of customers that subscribed to the newsletter",
         lambda: display_subscribed_emails(table)),
        ]
    stay = True
    while stay:
        ui.print_menu('Customer Relationship Management (CRM)', options, 'Back to main menu')
        try:
            stay = common.choose(options, table)
        except KeyError as err:
            ui.print_error_message(err)
    data_manager.write_table_to_file(FILE_NAME, table)
def main():
    print "Using configuration file: %s" % config.get('Internal', 'last_location')
    print
    print "Welcome to the Plain Image Launcher!"
    print "    The easiest way to interface with Amazon's EC2 and Rackspace's CloudServers"
    print "    and produce a plain instance (or cluster) in under 5 minutes!"
    print

    if not config.get('Shared', 'handle'):
        sys.stderr.write("Ensure {0} is appropriately set.\n".format(config.get('Internal', 'last_location')))
        sys.stderr.write("    'Shared:handle' is missing.\n")
        sys.exit(1)

    cloud = common.choose("Choose your Cloud Testing Host: ", clusterChoices.keys())

    # Ensure access keys are setup
    if cloud == 'EC2':
        if not config.get('EC2', 'aws_access_key_id') or not config.get('EC2', 'aws_secret_access_key'):
            sys.stderr.write("Ensure {0} is appropriately set.\n".format(config.get('Internal', 'last_location')))
            sys.stderr.write("    'EC2:aws_access_key_id|aws_secret_access_key' are missing.\n")
            sys.exit(1)
        if (config.get('EC2', 'aws_access_key_id')[0] == '"' or config.get('EC2', 'aws_secret_access_key')[0] == '"' or
            config.get('EC2', 'aws_access_key_id')[0] == "'" or config.get('EC2', 'aws_secret_access_key')[0] == "'"):
            sys.stderr.write("None of the configurations should be wrapped in quotes.\n")
            sys.stderr.write("    EC2:aws_access_key_id or EC2:aws_secret_access_key appears to be.\n")
            sys.exit(1)
    if cloud == 'Rackspace':
        if not config.get('Rax', 'rax_user') or not config.get('Rax', 'rax_api_key'):
            sys.stderr.write("Ensure {0} is appropriately set.\n".format(config.get('Internal', 'last_location')))
            sys.stderr.write("    'Rax:rax_user|rax_api_key' are missing.\n")
            sys.exit(1)
        if (config.get('Rax', 'rax_user')[0] == '"' or config.get('Rax', 'rax_api_key')[0] == '"' or
            config.get('Rax', 'rax_user')[0] == "'" or config.get('Rax', 'rax_api_key')[0] == "'"):
            sys.stderr.write("None of the configurations should be wrapped in quotes.\n")
            sys.stderr.write("    Rax:rax_user or Rax:rax_api_key appears to be.\n")
            sys.exit(1)

    action = common.choose("Choose your Cloud Command: ", ['Create', 'Destroy'])

    if action == 'Destroy':
        if cloud == 'EC2':
            ec2.terminate_cluster(config.get('EC2', 'aws_access_key_id'), config.get('EC2', 'aws_secret_access_key'), config.get('EC2', 'placement'), config.get('Shared', 'handle'))
        if cloud == 'Rackspace':
            rax.terminate_cluster(config.get('Rax', 'rax_user'), config.get('Rax', 'rax_api_key'), config.get('Shared', 'handle'))
        sys.exit()

    reservation_size = common.typed_input(int, "Choose your Cluster Size: ")
    print

    operating_system = common.choose("Choose your Testing Operating System: " , clusterChoices[cloud].keys())

    if cloud == 'EC2':
        if operating_system == '~Custom AMI':
            image = raw_input("Enter the AMI ID: ")
            user = raw_input("Enter the AMI's default user: "******"{3} - Time: {2} {0} Size: {1}".format(image, reservation_size, time.strftime("%m-%d-%y %H:%M", time.localtime()), config.get('Shared', 'handle'))
        else:
            provider = common.choose("Choose your Image Provider: ", clusterChoices[cloud][operating_system].keys())
            version = common.choose("Choose your Operating System Version: ", clusterChoices[cloud][operating_system][provider].keys())

            image = clusterChoices[cloud][operating_system][provider][version]['AMI']
            user = clusterChoices[cloud][operating_system][provider][version]['User']

            tag = "{5} - {0} Time: {4} {1} {2} Size: {3}".format(provider, operating_system, version, reservation_size, time.strftime("%m-%d-%y %H:%M", time.localtime()), config.get('Shared', 'handle'))

        user_data = raw_input("Enter EC2 user data: ")
        print

        instance_type = config.get('EC2', 'instance_type')
        if not instance_type:
            instance_type = common.choose('Choose your Instance Size:', ['m1.large', 'm1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge'])

        clusterinfo = ec2.create_cluster(config.get('EC2', 'aws_access_key_id'), config.get('EC2', 'aws_secret_access_key'),
                                        reservation_size, image, tag, KEY_PAIR,
                                        instance_type, config.get('EC2', 'placement'), PEM_HOME, user_data)
        private_ips, public_ips, reservation = clusterinfo

        printConnections(user, private_ips, public_ips, PEM_FILE)
    
    if cloud == 'Rackspace':
        version = common.choose("Choose your Operating System Version: ", clusterChoices[cloud][operating_system].keys())

        image = clusterChoices[cloud][operating_system][version]['Image']
        tag = "{0} Time {4} {1} {2} Size {3}".format(config.get('Shared', 'handle'), operating_system, version, reservation_size, time.strftime("%m-%d-%y %H:%M", time.localtime())).replace(' ', '-').replace(':', '_').replace('.', '_')

        flavor_array = ['256', '512', '1GB', '2GB', '4GB', '8GB', '15.5GB', '30GB']
        flavor_choice = config.get('Rax', 'flavor')
        if not flavor_choice:
            flavor_choice = common.choose("Choose your Instance Size: ", flavor_array, sort=False)

        flavor_dict = {}
        for i, flavor in enumerate(flavor_array):
            flavor_dict[flavor] = i + 1
            flavor_dict[str(i + 1)] = i + 1 # For backward compliance
        flavor = flavor_dict[flavor_choice]

        private_ips, public_ips = rax.create_cluster(config.get('Rax', 'rax_user'), config.get('Rax', 'rax_api_key'),
                                                  reservation_size, image, tag, flavor)

        printConnections(config.get('Rax', 'user'), private_ips, public_ips)
def main():
    print "Using configuration file: %s" % config.get("Internal", "last_location")
    print
    print "Welcome to the Plain Image Launcher!"
    print "    The easiest way to interface with Amazon's EC2 and Rackspace's CloudServers"
    print "    and produce a plain instance (or cluster) in under 5 minutes!"
    print

    if not config.get("Shared", "handle"):
        sys.stderr.write("Ensure {0} is appropriately set.\n".format(config.get("Internal", "last_location")))
        sys.stderr.write("    'Shared:handle' is missing.\n")
        sys.exit(1)

    cloud = common.choose("Choose your Cloud Testing Host: ", clusterChoices.keys())

    # Ensure access keys are setup
    if cloud == "EC2":
        if not config.get("EC2", "aws_access_key_id") or not config.get("EC2", "aws_secret_access_key"):
            sys.stderr.write("Ensure {0} is appropriately set.\n".format(config.get("Internal", "last_location")))
            sys.stderr.write("    'EC2:aws_access_key_id|aws_secret_access_key' are missing.\n")
            sys.exit(1)
        if (
            config.get("EC2", "aws_access_key_id")[0] == '"'
            or config.get("EC2", "aws_secret_access_key")[0] == '"'
            or config.get("EC2", "aws_access_key_id")[0] == "'"
            or config.get("EC2", "aws_secret_access_key")[0] == "'"
        ):
            sys.stderr.write("None of the configurations should be wrapped in quotes.\n")
            sys.stderr.write("    EC2:aws_access_key_id or EC2:aws_secret_access_key appears to be.\n")
            sys.exit(1)
    if cloud == "Rackspace":
        if not config.get("Rax", "rax_user") or not config.get("Rax", "rax_api_key"):
            sys.stderr.write("Ensure {0} is appropriately set.\n".format(config.get("Internal", "last_location")))
            sys.stderr.write("    'Rax:rax_user|rax_api_key' are missing.\n")
            sys.exit(1)
        if (
            config.get("Rax", "rax_user")[0] == '"'
            or config.get("Rax", "rax_api_key")[0] == '"'
            or config.get("Rax", "rax_user")[0] == "'"
            or config.get("Rax", "rax_api_key")[0] == "'"
        ):
            sys.stderr.write("None of the configurations should be wrapped in quotes.\n")
            sys.stderr.write("    Rax:rax_user or Rax:rax_api_key appears to be.\n")
            sys.exit(1)

    action = common.choose("Choose your Cloud Command: ", ["Create", "Destroy"])

    if action == "Destroy":
        if cloud == "EC2":
            ec2.terminate_cluster(
                config.get("EC2", "aws_access_key_id"),
                config.get("EC2", "aws_secret_access_key"),
                config.get("EC2", "placement"),
                config.get("Shared", "handle"),
            )
        if cloud == "Rackspace":
            rax.terminate_cluster(
                config.get("Rax", "rax_user"), config.get("Rax", "rax_api_key"), config.get("Shared", "handle")
            )
        sys.exit()

    reservation_size = common.typed_input(int, "Choose your Cluster Size: ")
    print

    operating_system = common.choose("Choose your Testing Operating System: ", clusterChoices[cloud].keys())

    if cloud == "EC2":
        if operating_system == "~Custom AMI":
            image = raw_input("Enter the AMI ID: ")
            user = raw_input("Enter the AMI's default user: "******"{3} - Time: {2} {0} Size: {1}".format(
                image,
                reservation_size,
                time.strftime("%m-%d-%y %H:%M", time.localtime()),
                config.get("Shared", "handle"),
            )
        else:
            provider = common.choose("Choose your Image Provider: ", clusterChoices[cloud][operating_system].keys())
            version = common.choose(
                "Choose your Operating System Version: ", clusterChoices[cloud][operating_system][provider].keys()
            )

            image = clusterChoices[cloud][operating_system][provider][version]["AMI"]
            user = clusterChoices[cloud][operating_system][provider][version]["User"]

            tag = "{5} - {0} Time: {4} {1} {2} Size: {3}".format(
                provider,
                operating_system,
                version,
                reservation_size,
                time.strftime("%m-%d-%y %H:%M", time.localtime()),
                config.get("Shared", "handle"),
            )

        user_data = raw_input("Enter EC2 user data: ")
        print

        instance_type = config.get("EC2", "instance_type")
        if not instance_type:
            instance_type = common.choose(
                "Choose your Instance Size:", ["m1.large", "m1.xlarge", "m2.xlarge", "m2.2xlarge", "m2.4xlarge"]
            )

        clusterinfo = ec2.create_cluster(
            config.get("EC2", "aws_access_key_id"),
            config.get("EC2", "aws_secret_access_key"),
            reservation_size,
            image,
            "imagelauncher",
            tag,
            KEY_PAIR,
            instance_type,
            config.get("EC2", "placement"),
            PEM_HOME,
            user_data,
        )
        private_ips, public_ips, reservation = clusterinfo

        printConnections(user, private_ips, public_ips, PEM_FILE)

    if cloud == "Rackspace":
        version = common.choose(
            "Choose your Operating System Version: ", clusterChoices[cloud][operating_system].keys()
        )

        image = clusterChoices[cloud][operating_system][version]["Image"]
        tag = (
            "{0} Time {4} {1} {2} Size {3}".format(
                config.get("Shared", "handle"),
                operating_system,
                version,
                reservation_size,
                time.strftime("%m-%d-%y %H:%M", time.localtime()),
            )
            .replace(" ", "-")
            .replace(":", "_")
            .replace(".", "_")
        )

        flavor_array = ["256", "512", "1GB", "2GB", "4GB", "8GB", "15.5GB", "30GB"]
        flavor_choice = config.get("Rax", "flavor")
        if not flavor_choice:
            flavor_choice = common.choose("Choose your Instance Size: ", flavor_array, sort=False)

        flavor_dict = {}
        for i, flavor in enumerate(flavor_array):
            flavor_dict[flavor] = i + 1
            flavor_dict[str(i + 1)] = i + 1  # For backward compliance
        flavor = flavor_dict[flavor_choice]

        private_ips, public_ips = rax.create_cluster(
            config.get("Rax", "rax_user"), config.get("Rax", "rax_api_key"), reservation_size, image, tag, flavor
        )

        printConnections(config.get("Rax", "user"), private_ips, public_ips)
Beispiel #14
0
def main():
    print "Using configuration file: %s" % config.get('Internal',
                                                      'last_location')
    print
    print "Welcome to the Plain Image Launcher!"
    print "    The easiest way to interface with Amazon's EC2 and Rackspace's CloudServers"
    print "    and produce a plain instance (or cluster) in under 5 minutes!"
    print

    if not config.get('Shared', 'handle'):
        sys.stderr.write("Ensure {0} is appropriately set.\n".format(
            config.get('Internal', 'last_location')))
        sys.stderr.write("    'Shared:handle' is missing.\n")
        sys.exit(1)

    cloud = common.choose("Choose your Cloud Testing Host: ",
                          clusterChoices.keys())

    # Ensure access keys are setup
    if cloud == 'EC2':
        if not config.get('EC2', 'aws_access_key_id') or not config.get(
                'EC2', 'aws_secret_access_key'):
            sys.stderr.write("Ensure {0} is appropriately set.\n".format(
                config.get('Internal', 'last_location')))
            sys.stderr.write(
                "    'EC2:aws_access_key_id|aws_secret_access_key' are missing.\n"
            )
            sys.exit(1)
        if (config.get('EC2', 'aws_access_key_id')[0] == '"'
                or config.get('EC2', 'aws_secret_access_key')[0] == '"'
                or config.get('EC2', 'aws_access_key_id')[0] == "'"
                or config.get('EC2', 'aws_secret_access_key')[0] == "'"):
            sys.stderr.write(
                "None of the configurations should be wrapped in quotes.\n")
            sys.stderr.write(
                "    EC2:aws_access_key_id or EC2:aws_secret_access_key appears to be.\n"
            )
            sys.exit(1)
    if cloud == 'Rackspace':
        if not config.get('Rax', 'rax_user') or not config.get(
                'Rax', 'rax_api_key'):
            sys.stderr.write("Ensure {0} is appropriately set.\n".format(
                config.get('Internal', 'last_location')))
            sys.stderr.write("    'Rax:rax_user|rax_api_key' are missing.\n")
            sys.exit(1)
        if (config.get('Rax', 'rax_user')[0] == '"'
                or config.get('Rax', 'rax_api_key')[0] == '"'
                or config.get('Rax', 'rax_user')[0] == "'"
                or config.get('Rax', 'rax_api_key')[0] == "'"):
            sys.stderr.write(
                "None of the configurations should be wrapped in quotes.\n")
            sys.stderr.write(
                "    Rax:rax_user or Rax:rax_api_key appears to be.\n")
            sys.exit(1)

    action = common.choose("Choose your Cloud Command: ",
                           ['Create', 'Destroy'])

    if action == 'Destroy':
        if cloud == 'EC2':
            ec2.terminate_cluster(config.get('EC2', 'aws_access_key_id'),
                                  config.get('EC2', 'aws_secret_access_key'),
                                  config.get('EC2', 'placement'),
                                  config.get('Shared', 'handle'))
        if cloud == 'Rackspace':
            rax.terminate_cluster(config.get('Rax', 'rax_user'),
                                  config.get('Rax', 'rax_api_key'),
                                  config.get('Shared', 'handle'))
        sys.exit()

    reservation_size = common.typed_input(int, "Choose your Cluster Size: ")
    print

    operating_system = common.choose("Choose your Testing Operating System: ",
                                     clusterChoices[cloud].keys())

    if cloud == 'EC2':
        if operating_system == '~Custom AMI':
            image = raw_input("Enter the AMI ID: ")
            user = raw_input("Enter the AMI's default user: "******"{3} - Time: {2} {0} Size: {1}".format(
                image, reservation_size,
                time.strftime("%m-%d-%y %H:%M", time.localtime()),
                config.get('Shared', 'handle'))
        else:
            provider = common.choose(
                "Choose your Image Provider: ",
                clusterChoices[cloud][operating_system].keys())
            version = common.choose(
                "Choose your Operating System Version: ",
                clusterChoices[cloud][operating_system][provider].keys())

            image = clusterChoices[cloud][operating_system][provider][version][
                'AMI']
            user = clusterChoices[cloud][operating_system][provider][version][
                'User']

            tag = "{5} - {0} Time: {4} {1} {2} Size: {3}".format(
                provider, operating_system, version, reservation_size,
                time.strftime("%m-%d-%y %H:%M", time.localtime()),
                config.get('Shared', 'handle'))

        user_data = raw_input("Enter EC2 user data: ")
        print

        instance_type = config.get('EC2', 'instance_type')
        if not instance_type:
            instance_type = common.choose('Choose your Instance Size:', [
                'm1.large', 'm1.xlarge', 'm2.xlarge', 'm2.2xlarge',
                'm2.4xlarge'
            ])

        clusterinfo = ec2.create_cluster(
            config.get('EC2', 'aws_access_key_id'),
            config.get('EC2', 'aws_secret_access_key'),
            reservation_size, image, tag, KEY_PAIR, instance_type,
            config.get('EC2', 'placement'), PEM_HOME, user_data)
        private_ips, public_ips, reservation = clusterinfo

        printConnections(user, private_ips, public_ips, PEM_FILE)

    if cloud == 'Rackspace':
        version = common.choose("Choose your Operating System Version: ",
                                clusterChoices[cloud][operating_system].keys())

        image = clusterChoices[cloud][operating_system][version]['Image']
        tag = "{0} Time {4} {1} {2} Size {3}".format(
            config.get('Shared', 'handle'), operating_system,
            version, reservation_size,
            time.strftime("%m-%d-%y %H:%M", time.localtime())).replace(
                ' ', '-').replace(':', '_').replace('.', '_')

        flavor_array = [
            '256', '512', '1GB', '2GB', '4GB', '8GB', '15.5GB', '30GB'
        ]
        flavor_choice = config.get('Rax', 'flavor')
        if not flavor_choice:
            flavor_choice = common.choose("Choose your Instance Size: ",
                                          flavor_array,
                                          sort=False)

        flavor_dict = {}
        for i, flavor in enumerate(flavor_array):
            flavor_dict[flavor] = i + 1
            flavor_dict[str(i + 1)] = i + 1  # For backward compliance
        flavor = flavor_dict[flavor_choice]

        private_ips, public_ips = rax.create_cluster(
            config.get('Rax', 'rax_user'), config.get('Rax', 'rax_api_key'),
            reservation_size, image, tag, flavor)

        printConnections(config.get('Rax', 'user'), private_ips, public_ips)