def main(args):    
    # Fetch a list of all the instances in these security groups.
    instances = {}
    for security_group in args.security_group:
        logging.info('Getting instances for %s.' % security_group)
        instances[security_group] = get_running_instances(access_key=args.access_key,
                                                          secret_key=args.secret_key,
                                                          security_group=security_group)

    # Generate the new config from the template.
    logging.info('Generating configuration for haproxy.')
    new_configuration = generate_haproxy_config(template=args.template,
                                                instances=instances)
    
    # See if this new config is different. If it is then restart using it.
    # Otherwise just delete the temporary file and do nothing.
    logging.info('Comparing to existing configuration.')
    old_configuration = file_contents(filename=args.output)
    
    if new_configuration != old_configuration:
        logging.info('Existing configuration is outdated.')
        
        # Overwite the existing config file.
        logging.info('Writing new configuration.')
        file_contents(filename=args.output,
                      content=generate_haproxy_config(template=args.template,
                                                      instances=instances    ))
        
        restart_haproxy(args)
        
    else:
        logging.info('Configuration unchanged. Skipping restart.')
示例#2
0
def main(args):
    # Fetch a list of all the instances in these security groups.
    instances = {}
    for security_group in args.security_group:
        logging.info('Getting instances for %s.' % security_group)
        instances[security_group] = get_running_instances(
            access_key=args.access_key,
            secret_key=args.secret_key,
            security_group=security_group,
            region=args.region)

    # Generate the new config from the template.
    logging.info('Generating configuration for haproxy.')
    new_configuration = generate_haproxy_config(template=args.template,
                                                instances=instances)

    # See if this new config is different. If it is then restart using it.
    # Otherwise just delete the temporary file and do nothing.
    logging.info('Comparing to existing configuration.')
    old_configuration = file_contents(filename=args.output)

    if new_configuration != old_configuration:
        logging.info('Existing configuration is outdated.')

        # Overwite the existing config file.
        logging.info('Writing new configuration.')
        file_contents(filename=args.output,
                      content=generate_haproxy_config(template=args.template,
                                                      instances=instances))

        restart_haproxy(args)

    else:
        logging.info('Configuration unchanged. Skipping restart.')
示例#3
0
def main():
    # Parse up the command line arguments.
    parser = argparse.ArgumentParser(
        description=
        'Update haproxy to use all instances running in a security group.')
    parser.add_argument('--autoscaling-group',
                        required=True,
                        nargs='+',
                        type=str)
    parser.add_argument('--output',
                        default='/etc/haproxy/haproxy.cfg',
                        help='Defaults to haproxy.cfg if not specified.')
    parser.add_argument('--template', default='templates/haproxy.tpl')
    parser.add_argument(
        '--haproxy',
        default='/usr/sbin/haproxy',
        help='The haproxy binary to call. Defaults to haproxy if not specified.'
    )
    parser.add_argument(
        '--pid',
        default='/run/haproxy.pid',
        help='The pid file for haproxy. Defaults to /run/haproxy.pid.')
    args = parser.parse_args()

    # Fetch a list of all the instances in these security groups.
    logging.info('Getting instances for %s.' % str(args.autoscaling_group))
    instances = get_running_instances(
        autoscaling_groups=args.autoscaling_group)

    # Generate the new config from the template.
    logging.info('Generating configuration for haproxy.')
    new_configuration = generate_haproxy_config(template=args.template,
                                                instances=instances)

    # See if this new config is different. If it is then restart using it.
    # Otherwise just delete the temporary file and do nothing.
    logging.info('Comparing to existing configuration.')
    old_configuration = file_contents(filename=args.output)
    if new_configuration != old_configuration:
        logging.info('Existing configuration is outdated.')

        # Overwite the existing config file.
        logging.info('Writing new configuration.')
        file_contents(filename=args.output,
                      content=generate_haproxy_config(template=args.template,
                                                      instances=instances))

        # Get PID if haproxy is already running.
        logging.info('Fetching PID from %s.' % args.pid)
        pid = file_contents(filename=args.pid)

        # Restart haproxy.
        logging.info('Restarting haproxy.')
        command = '''%s -p %s -f %s -sf %s''' % (args.haproxy, args.pid,
                                                 args.output, pid or '')
        logging.info('Executing: %s' % command)
        subprocess.call(command, shell=True)
    else:
        logging.info('Configuration unchanged. Skipping restart.')
def main():
    # Parse up the command line arguments.
    parser = argparse.ArgumentParser(description='Update haproxy to use all instances running in a security group.')
    parser.add_argument('--autoscaling-group', required=True, nargs='+', type=str)
    parser.add_argument('--output', default='/etc/haproxy/haproxy.cfg',
                        help='Defaults to haproxy.cfg if not specified.')
    parser.add_argument('--template', default='templates/haproxy.tpl')
    parser.add_argument('--haproxy', default='/usr/sbin/haproxy',
                        help='The haproxy binary to call. Defaults to haproxy if not specified.')
    parser.add_argument('--pid', default='/run/haproxy.pid',
                        help='The pid file for haproxy. Defaults to /run/haproxy.pid.')
    args = parser.parse_args()

    # Fetch a list of all the instances in these security groups.
    logging.info('Getting instances for %s.' % str(args.autoscaling_group))
    instances = get_running_instances(autoscaling_groups=args.autoscaling_group)
    
    # Generate the new config from the template.
    logging.info('Generating configuration for haproxy.')
    new_configuration = generate_haproxy_config(template=args.template,
                                                instances=instances)
    
    # See if this new config is different. If it is then restart using it.
    # Otherwise just delete the temporary file and do nothing.
    logging.info('Comparing to existing configuration.')
    old_configuration = file_contents(filename=args.output)
    if new_configuration != old_configuration:
        logging.info('Existing configuration is outdated.')
        
        # Overwite the existing config file.
        logging.info('Writing new configuration.')
        file_contents(filename=args.output,
                      content=generate_haproxy_config(template=args.template, instances=instances))
        
        # Get PID if haproxy is already running.
        logging.info('Fetching PID from %s.' % args.pid)
        pid = file_contents(filename=args.pid)
        
        # Restart haproxy.
        logging.info('Restarting haproxy.')
        command = '''%s -p %s -f %s -sf %s''' % (args.haproxy, args.pid, args.output, pid or '')
        logging.info('Executing: %s' % command)
        subprocess.call(command, shell=True)
    else:
        logging.info('Configuration unchanged. Skipping restart.')
 def test_autobackend_three_prefixes(self):
     template = os.path.join(self.data_dir_str, "autobackends_three_prefixes_example.tpl")
     self.test_conf_filepath = NamedTemporaryFile(delete=True).name
     haproxy_conf_str = haproxy_autoscale.generate_haproxy_config(
         template=template, instances=self.running_instances_mock
     )
     haproxy_autoscale.file_contents(filename=self.test_conf_filepath, content=haproxy_conf_str)
     test_conf_output = check_conf(conf_filepath=self.test_conf_filepath)
     self.assertEqual(test_conf_output[0], True, ("Configuration parsing failed:\n%s" % test_conf_output[1]))
示例#6
0
def main(args):
    # Fetch a list of all the instances in these security groups.
    instances = {}
    for security_group in args.security_group:
        logging.info('Getting instances for %s.', security_group)
        security_group_instances = get_running_instances(
            access_key=args.access_key,
            secret_key=args.secret_key,
            security_group=security_group,
            region=args.region,
            safe_mode=args.safe_mode,
            delay=args.delay)
        instances[security_group] = sorted(security_group_instances)

    # Generate the new config from the template.
    logging.info('Generating configuration for haproxy.')
    new_configuration = generate_haproxy_config(template=args.template,
                                                instances=instances)

    # See if this new config is different. If it is then reload using it.
    # Otherwise just delete the temporary file and do nothing.
    logging.info('Comparing to existing configuration.')
    old_configuration = file_contents(filename=args.output)

    if new_configuration != old_configuration:
        logging.info('Existing configuration is outdated.')

        # Overwite the existing config file.
        logging.info('Writing new configuration.')
        file_contents(filename=args.output,
                      content=generate_haproxy_config(template=args.template,
                                                      instances=instances))

        if args.safe_mode and exists_empty_security_group(instances):
            logging.info(
                'Safe mode enabled. haproxy conf generated but NOT reloaded, '
                'since at least one of the security groups is empty.')
            exit(1)

        reload_haproxy(args)

    else:
        logging.info('Configuration unchanged. Skipping reload.')
 def test_autobackend_config(self):
     template = os.path.join(self.data_dir_str, 'autobackends_example.tpl')
     self.test_conf_filepath = NamedTemporaryFile(delete=True).name
     haproxy_conf_str = haproxy_autoscale.generate_haproxy_config(
         template=template, instances=self.running_instances_mock)
     haproxy_autoscale.file_contents(filename=self.test_conf_filepath,
                                     content=haproxy_conf_str)
     test_conf_output = check_conf(conf_filepath=self.test_conf_filepath)
     self.assertEqual(
         test_conf_output[0], True,
         ("Configuration parsing failed:\n%s" % test_conf_output[1]))
def main():
    # Parse up the command line arguments.
    parser = argparse.ArgumentParser(description='Update haproxy to use all instances running in a security group.')
    parser.add_argument('--security-group', required=False, nargs='+', type=str)
    parser.add_argument('--access-key', required=True)
    parser.add_argument('--secret-key', required=True)
    parser.add_argument('--output', default='haproxy.cfg',
                        help='Defaults to haproxy.cfg if not specified.')
    parser.add_argument('--template', default='templates/haproxy.tpl')
    parser.add_argument('--haproxy', default='./haproxy',
                        help='The haproxy binary to call. Defaults to haproxy if not specified.')
    parser.add_argument('--pid', default='/var/run/haproxy.pid',
                        help='The pid file for haproxy. Defaults to /var/run/haproxy.pid.')
    parser.add_argument('--eip',
                        help='The Elastic IP to bind to when VIP seems unhealthy.')
    parser.add_argument('--health-check-url',
                        help='The URL to check. Assigns EIP to self if health check fails.')
    parser.add_argument('--autoscaling-group',
                        help='The AutoScaling Group that health instance located in.')
    parser.add_argument('--region',
                        help='The region that the SecurityGroup located in.')
    args = parser.parse_args()

    # Fetch a list of all the instances in these security groups.
    instances = {}
    if args.security_group:
	    for security_group in args.security_group:
		logging.info('Getting instances for %s.' % security_group)
		instances[security_group] = get_running_instances_in_security_group(access_key=args.access_key,
								  secret_key=args.secret_key,
								  security_group=security_group,
								  region=args.region)
    if args.autoscaling_group:
		autoscaling_group=args.autoscaling_group
		logging.info('Getting instances for %s.' % autoscaling_group)
		instances[autoscaling_group] = get_running_instances_in_autoscaling_group(access_key=args.access_key,
								  secret_key=args.secret_key,
								  autoscaling_group=autoscaling_group,
								  region=args.region)
    print(instances)
	    
    # Generate the new config from the template.
    logging.info('Generating configuration for haproxy.')
    new_configuration = generate_haproxy_config(template=args.template,
                                                instances=instances)
    
    # See if this new config is different. If it is then restart using it.
    # Otherwise just delete the temporary file and do nothing.
    logging.info('Comparing to existing configuration.')
    old_configuration = file_contents(filename=args.output)
    if new_configuration != old_configuration:
        logging.info('Existing configuration is outdated.')
        
        # Overwite the existing config file.
        logging.info('Writing new configuration.')
        file_contents(filename=args.output,
                      content=generate_haproxy_config(template=args.template,
                                                      instances=instances    ))
        
        # Get PID if haproxy is already running.
        logging.info('Fetching PID from %s.' % args.pid)
        pid = file_contents(filename=args.pid)
        
        # Restart haproxy.
        logging.info('Restarting haproxy.')
        command = '''%s -p %s -f %s -sf %s''' % (args.haproxy, args.pid, args.output, pid or '')
        logging.info('Executing: %s' % command)
        subprocess.call(command, shell=True)
    else:
        logging.info('Configuration unchanged. Skipping restart.')
    
    # Do a health check on the url if specified.
    try:
        if args.health_check_url and args.eip:
            logging.info('Performing health check.')
            try:
                logging.info('Checking %s' % args.health_check_url)
                response = urllib2.urlopen(args.health_check_url)
                logging.info('Response: %s' % response.read())
            except:
                # Assign the EIP to self.
                logging.warn('Health check failed. Assigning %s to self.' % args.eip)
                steal_elastic_ip(access_key=args.access_key,
                                 secret_key=args.secret_key,
                                 ip=args.eip,
				 region=args.region                )
    except:
        pass
示例#9
0
def main():
    # Parse up the command line arguments.
    parser = argparse.ArgumentParser(description='Update haproxy to use all instances running in a security group.')
    parser.add_argument('--security-group', required=True, nargs='+', type=str)
    parser.add_argument('--access-key', required=True)
    parser.add_argument('--secret-key', required=True)
    parser.add_argument('--output', default='haproxy.cfg',
                        help='Defaults to haproxy.cfg if not specified.')
    parser.add_argument('--template', default='templates/haproxy.tpl')
    parser.add_argument('--haproxy', default='./haproxy',
                        help='The haproxy binary to call. Defaults to haproxy if not specified.')
    parser.add_argument('--pid', default='/var/run/haproxy.pid',
                        help='The pid file for haproxy. Defaults to /var/run/haproxy.pid.')
    parser.add_argument('--eip',
                        help='The Elastic IP to bind to when VIP seems unhealthy.')
    parser.add_argument('--health-check-url',
                        help='The URL to check. Assigns EIP to self if health check fails.')
    args = parser.parse_args()

    # Fetch a list of all the instances in these security groups.
    instances = {}
    for security_group in args.security_group:
        logging.info('Getting instances for %s.' % security_group)
        instances[security_group] = get_running_instances(access_key=args.access_key,
                                                          secret_key=args.secret_key,
                                                          security_group=security_group)
    # Generate the new config from the template.
    logging.info('Generating configuration for haproxy.')
    new_configuration = generate_haproxy_config(template=args.template,
                                                instances=instances)
    
    # See if this new config is different. If it is then restart using it.
    # Otherwise just delete the temporary file and do nothing.
    logging.info('Comparing to existing configuration.')
    old_configuration = file_contents(filename=args.output)
    if new_configuration != old_configuration:
        logging.info('Existing configuration is outdated.')
        
        # Overwite the existing config file.
        logging.info('Writing new configuration.')
        file_contents(filename=args.output,
                      content=generate_haproxy_config(template=args.template,
                                                      instances=instances    ))
        
        # Get PID if haproxy is already running.
        logging.info('Fetching PID from %s.' % args.pid)
        pid = file_contents(filename=args.pid)
        
        # Restart haproxy.
        logging.info('Restarting haproxy.')
        command = '''%s -p %s -f %s -sf %s''' % (args.haproxy, args.pid, args.output, pid or '')
        logging.info('Executing: %s' % command)
        subprocess.call(command, shell=True)
    else:
        logging.info('Configuration unchanged. Skipping restart.')
    
    # Do a health check on the url if specified.
    try:
        if args.health_check_url and args.eip:
            logging.info('Performing health check.')
            try:
                logging.info('Checking %s' % args.health_check_url)
                response = urllib2.urlopen(args.health_check_url)
                logging.info('Response: %s' % response.read())
            except:
                # Assign the EIP to self.
                logging.warn('Health check failed. Assigning %s to self.' % args.eip)
                steal_elastic_ip(access_key=args.access_key,
                                 secret_key=args.secret_key,
                                 ip=args.eip                )
    except:
        pass
def main():
    # Parse up the command line arguments.
    parser = argparse.ArgumentParser(
        description="Update haproxy to use all instances running with an aws:autoscaling:groupName tag of the given value."
    )
    parser.add_argument("--tag", required=True, nargs="+", type=str)
    parser.add_argument("--access-key", required=True)
    parser.add_argument("--secret-key", required=True)
    parser.add_argument("--output", default="haproxy.cfg", help="Defaults to haproxy.cfg if not specified.")
    parser.add_argument("--template", default="templates/haproxy.tpl")
    parser.add_argument(
        "--haproxy", default="./haproxy", help="The haproxy binary to call. Defaults to haproxy if not specified."
    )
    parser.add_argument(
        "--pid", default="/var/run/haproxy.pid", help="The pid file for haproxy. Defaults to /var/run/haproxy.pid."
    )
    parser.add_argument("--eip", help="The Elastic IP to bind to when VIP seems unhealthy.")
    parser.add_argument("--health-check-url", help="The URL to check. Assigns EIP to self if health check fails.")
    args = parser.parse_args()

    FORMAT = "%(asctime)-15s %(message)s"
    logging.basicConfig(format=FORMAT)

    # Fetch a list of all the instances in these security groups.
    instances = {}
    for tag in args.tag:
        #        logging.info('Getting instances for %s.' % tag)
        instances[tag] = get_running_instances_by_tag(
            access_key=args.access_key, secret_key=args.secret_key, tag_key="aws:autoscaling:groupName", tag_value=tag
        )
    # Generate the new config from the template.
    #    logging.info('Generating configuration for haproxy.')
    new_configuration = generate_haproxy_config(template=args.template, instances=instances)

    # See if this new config is different. If it is then restart using it.
    # Otherwise just delete the temporary file and do nothing.
    #    logging.info('Comparing to existing configuration.')
    old_configuration = file_contents(filename=args.output)
    if new_configuration != old_configuration:
        logging.info("Existing configuration is outdated.")

        # Overwite the existing config file.
        logging.info("Writing new configuration.")
        file_contents(
            filename=args.output, content=generate_haproxy_config(template=args.template, instances=instances)
        )

        # Get PID if haproxy is already running.
    #        logging.info('Fetching PID from %s.' % args.pid)
    #        pid = file_contents(filename=args.pid)

    # Letting Monit handle the actual restarting
    #        logging.info('Restarting haproxy.')
    #        command = '''%s -p %s -f %s -sf %s''' % (args.haproxy, args.pid, args.output, pid or '')
    #        logging.info('Executing: %s' % command)
    #        subprocess.call(command, shell=True)
    else:
        logging.info("Configuration unchanged. ")

    # Do a health check on the url if specified.
    try:
        if args.health_check_url and args.eip:
            logging.info("Performing health check.")
            try:
                logging.info("Checking %s" % args.health_check_url)
                response = urllib2.urlopen(args.health_check_url)
                logging.info("Response: %s" % response.read())
            except:
                # Assign the EIP to self.
                logging.warn("Health check failed. Assigning %s to self." % args.eip)
                steal_elastic_ip(access_key=args.access_key, secret_key=args.secret_key, ip=args.eip)
    except:
        pass
def main():
    # Parse up the command line arguments.
    parser = argparse.ArgumentParser(description='Update haproxy to use all instances running in a security group.')
    parser.add_argument('--config', default="/etc/haproxy-autoscale/haproxy-autoscale.conf",
                        help='Path to the config file.')
    parser.add_argument('--autoscaling-group', required=True, nargs='+', type=str)
    parser.add_argument('--region', default="us-east-1", help="AWS region name")
    parser.add_argument('--output', default='/etc/haproxy/haproxy.cfg',
                        help='Defaults to haproxy.cfg if not specified.')
    parser.add_argument('--template', default='/etc/haproxy-autoscale/haproxy.tpl')
    parser.add_argument('--haproxy', default='/usr/sbin/haproxy',
                        help='The haproxy binary to call. Defaults to haproxy if not specified.')
    parser.add_argument('--pid', default='/var/run/haproxy.pid',
                        help='The pid file for haproxy. Defaults to /var/run/haproxy.pid.')
    parser.add_argument('--eip',
                        help='The Elastic IP to bind to when VIP seems unhealthy.')
    parser.add_argument('--health-check-url',
                        help='The URL to check. Assigns EIP to self if health check fails.')
    args = parser.parse_args()

    # haproxy-autoscale config file
    config_fh = open(args.config, "ro")
    config = configparser.RawConfigParser()
    config.read_file(config_fh)
    config_fh.close()

    access_key = config.get("credential", "access_key")
    secret_key = config.get("credential", "secret_key")

    # Fetch a list of all the instances in these security groups.
    instances = {}
    for autoscaling_group in args.autoscaling_group:
        logging.info('Getting instances for %s.' % autoscaling_group)
        instances[autoscaling_group] = list_as_instances(access_key, secret_key, args.region,
                                                         autoscaling_group)
    # Generate the new config from the template.
    logging.info('Generating configuration for haproxy.')
    new_configuration = generate_haproxy_config(args.template, instances)
    
    # See if this new config is different. If it is then restart using it.
    # Otherwise just delete the temporary file and do nothing.
    logging.info('Comparing to existing configuration.')
    old_configuration = file_contents(args.output)
    if new_configuration != old_configuration:
        logging.info('Existing configuration is outdated.')
        
        # Overwite the existing config file.
        logging.info('Writing new configuration.')
        file_contents(args.output, generate_haproxy_config(args.template, instances))
        
        # Get PID if haproxy is already running.
        logging.info('Fetching PID from %s.' % args.pid)
        pid = file_contents(args.pid)
        
        # Restart haproxy.
        logging.info('Restarting haproxy.')
        command = '''%s -p %s -f %s -sf %s''' % (args.haproxy, args.pid, args.output, pid or '')
        logging.info('Executing: %s' % command)
        subprocess.call(command, shell=True)
    else:
        logging.info('Configuration unchanged. Skipping restart.')
    
    # Do a health check on the url if specified.
    try:
        if args.health_check_url and args.eip:
            logging.info('Performing health check.')
            try:
                logging.info('Checking %s' % args.health_check_url)
                response = urllib2.urlopen(args.health_check_url)
                logging.info('Response: %s' % response.read())
            except:
                # Assign the EIP to self.
                logging.warn('Health check failed. Assigning %s to self.' % args.eip)
                steal_elastic_ip(access_key, secret_key, args.eip)
    except:
        pass