Ejemplo n.º 1
0
def init_client(mist_uri, email, password):
    try:
        client = MistClient(mist_uri=mist_uri, email=email, password=password)

        # Ensures that GET requests are autheticated
        client.backends()
        return client
    except Exception as e:
        print e
        sys.exit(1)
Ejemplo n.º 2
0
def init_client(mist_uri, email, password):
    try:
        client = MistClient(mist_uri=mist_uri, email=email, password=password)

        #Ensures that GET requests are autheticated
        client.backends()
        return client
    except Exception as e:
        print e
        sys.exit(1)
Ejemplo n.º 3
0
def init_client():
    print ">>>Log in to mist.io"
    email = raw_input("Email: ")
    password = getpass.getpass("Password: ")
    print
    try:
        client = MistClient(email=email, password=password)
        client.backends
        return client
    except Exception as e:
        print e
        sys.exit(1)
Ejemplo n.º 4
0
 def client(self):
     """Represents the MistConnection Client
     """
     if self._client is None:
         if self.properties['mist_config'].get("mist_uri"):
             mist_uri = self.properties['mist_config']["mist_uri"]
             verify = False
         else:
             mist_uri = "https://mist.io"
             verify = True
         if self.properties['mist_config'].get("mist_token"):
             token = self.properties['mist_config']['mist_token']
             self._client = MistClient(mist_uri=mist_uri,
                                       api_token=token,
                                       verify=verify,
                                       job_id=get_job_id())
         else:
             self._client = MistClient(mist_uri=mist_uri,
                                       email=self.properties['mist_config']['mist_username'],
                                       password=self.properties['mist_config']['mist_password'],
                                       job_id=get_job_id())
     return self._client
Ejemplo n.º 5
0
 def _get_connection(self):
     """Return an authenticated MistClient connection instance"""
     return MistClient(mist_uri=self._uri,
                       verify=self._verify,
                       api_token=self._token,
                       job_id=self.job_id)
Ejemplo n.º 6
0
def init_client(mist_uri="https://mist.io", email=None, password=None):
    client = MistClient(mist_uri, email, password)
    return client
Ejemplo n.º 7
0
def main():
    # Handling arguments
    args = get_args()

    backend_name = None
    if args.backend_name:
        backend_name = args.backend_name

    basename = args.basename[0]
    image_id = args.image_id
    size_id = args.size_id

    monitoring = args.monitoring

    quantity = args.quantity[0]

    print_ips = args.ips
    print_macs = args.macs

    host = args.host.rstrip("/")

    username = None
    if args.username:
        username = args.username[0]

    password = None
    if args.password:
        password = args.password[0]

    log_file = None
    if args.logfile:
        log_file = args.logfile[0]

    post_script = None
    if args.post_script:
        post_script = args.post_script[0]
    script_params = ""
    if args.script_params:
        script_params = args.script_params[0]
    if args.networks:
        networks = args.networks

    debug = args.debug
    verbose = args.verbose
    maxwait = args.maxwait[0]

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    if log_file:
        logging.basicConfig(filename=log_file, format="%(asctime)s %(levelname)s %(message)s", level=log_level)
    else:
        logging.basicConfig(filename=log_file, format="%(asctime)s %(levelname)s %(message)s", level=log_level)
    logger = logging.getLogger(__name__)

    # Getting user password
    if username and password is None:
        logger.debug("No command line password received, requesting password " "from user")
        password = getpass.getpass(prompt="Enter mist.io password for user %s:" % (username))

    try:
        client = None
        try:
            logger.info("Connecting to mist.io with username %s" % (username))
            if username:
                client = MistClient(email=username, password=password, mist_uri=host, verify=False)
            else:
                credentials = parse_config()
                client = MistClient(
                    email=credentials["email"], password=credentials["password"], mist_uri=credentials["mist_uri"]
                )
        except IOError, e:
            pass

        if not client:
            logger.error("Could not connect to mist.io with user %s and " "specified password" % (username))
            return 1

        # Get the requested or first backend
        if backend_name:
            backends = client.backends(name=backend_name)
        else:
            backends = client.backends()

        if not backends:
            logger.critical("Backend unavailable")
            return 1
        else:
            backend = backends[0]

        # Create a new ssh keypair for this deployment
        private = client.generate_key()
        try:
            client.add_key(key_name=basename, private=private)
        except:
            logger.warn("Key %s already exists" % basename)

        res = backend.create_machine(
            name=basename,
            key=client.keys(search=basename)[0],
            image_id=image_id,
            location_id=backend.locations[0]["id"],
            size_id=size_id,
            networks=args.networks,
            async=True,
            fire_and_forget=False,
            quantity=quantity,
            monitoring=monitoring,
            verbose=True,
            timeout=maxwait,
        )

        if print_ips or post_script:
            try:
                logger.info("Updating VM list from backend")
                backend.update_machines()
            except:  # Retry in case of network glitch
                logger.warn("Backend unavailable. Retrying")
                backend.update_machines()

            probes = [p for p in res["logs"] if p["action"] == "probe" and not p["error"]]
            for p in probes:
                try:
                    machine = backend.machines(p["machine_id"])[0]
                except:
                    machine = None

                print "----------"
                if machine:
                    print "Machine:", machine.name
                    if print_ips:
                        print "Public ip addresses:"
                        for i in machine.info.get("public_ips", []):
                            print " - ", i
                        print "Private ip addresses:"
                        for i in machine.info.get("private_ips"):
                            print " - ", i
                else:
                    print "Machine:", p["machine_id"]

                if print_macs:
                    print "MACS:", json.dumps(p.get("result", {}).get("macs"))

                if post_script:
                    job = client.run_script(
                        backend.id, p["machine_id"], post_script, script_params=script_params, fire_and_forget=True
                    )
                    if job.get("job_id"):
                        print "Post deployment script queued: %s/jobs/%s" % (host, job.get("job_id"))

            print "----------"
Ejemplo n.º 8
0
def main():
    # Handling arguments
    args = get_args()

    backend_name = None
    if args.backend_name:
        backend_name = args.backend_name


    basename    = args.basename[0]
    image_id    = args.image_id
    tenantId    = args.tenantId
    size_id     = args.size_id
    networks     = args.networks

    monitoring  = args.monitoring

    quantity    = args.quantity[0]

    print_ips   = args.ips
    print_macs  = args.macs

    host        = args.host.rstrip('/')
    username    = args.username[0]
    password = None
    if args.password:
        password = args.password[0]

    log_file= None
    if args.logfile:
        log_file = args.logfile[0]

    post_script = None
    if args.post_script:
        post_script = args.post_script[0]
    script_params = ''
    if args.script_params:
        script_params = args.script_params[0]

    debug       = args.debug
    verbose     = args.verbose
    maxwait     = args.maxwait[0]

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    if log_file:
        logging.basicConfig(filename=log_file,format='%(asctime)s %(levelname)s %(message)s',level=log_level)
    else:
        logging.basicConfig(filename=log_file,format='%(asctime)s %(levelname)s %(message)s',level=log_level)
    logger = logging.getLogger(__name__)

    # Getting user password
    if password is None:
        logger.debug('No command line password received, requesting password from user')
        password = getpass.getpass(prompt='Enter mist.io password for user %s: ' % (username))

    try:
        client = None
        try:
            logger.info('Connecting to mist.io with username %s' % (username))
            client = MistClient(email=username, password=password, mist_uri=host)
        except IOError, e:
            pass

        if not client:
            logger.error('Could not connect to mist.io with user %s and specified password' % (username))
            return 1

        # Get the requested or first backend
        if backend_name:
            backends = client.backends(name=backend_name)
        else:
            backends = client.backends()

        if not backends:
            logger.critical('Backend unavailable')
            return 1
        else:
            backend = backends[0]

        # Create a new ssh keypair for this deployment
        private = client.generate_key()
        try:
            client.add_key(key_name=basename, private=private)
        except:
            logger.warn('Key %s already exists' % basename)

        res = backend.create_machine(name=basename,
                                     key=client.keys(search=basename)[0],
                                     image_id=image_id,
                                     tenantId=tenantId,
                                     location_id=backend.locations[0]['id'],
                                     size_id=size_id,
                                     networks=networks,
                                     async=True,
                                     fire_and_forget=False,
                                     quantity=quantity,
                                     monitoring=monitoring,
                                     verbose=True,
                                     timeout=maxwait
                                     )

        if print_ips or post_script:
            try:
                logger.info('Updating VM list from backend')
                backend.update_machines()
            except: # Retry in case of network glitch
                logger.warn('Backend unavailable. Retrying')
                backend.update_machines()

            probes = [p for p in res['logs'] if p['action'] == 'probe' and not p['error']]
            for p in probes:
                try:
                    machine = backend.machines(p['machine_id'])[0]
                except:
                    machine = None

                print '----------'
                if machine:
                    print 'Machine:', machine.name
                    if print_ips:
                        print 'Public ip addresses:'
                        for i in machine.info.get('public_ips',[]):
                            print " - ", i
                        print 'Private ip addresses:'
                        for i in machine.info.get('private_ips'):
                            print " - ", i
                else:
                    print 'Machine:', p['machine_id']

                if print_macs:
                    print 'MACS:', json.dumps(p.get('result', {}).get('macs'))

                if post_script:
                    job = client.run_script(backend.id, p['machine_id'],
                                     post_script, script_params=script_params,
                                     fire_and_forget=True)
                    if job.get('job_id'):
                        print 'Post deployment script queued: %s/jobs/%s' % (host, job.get('job_id'))

            print '----------'
Ejemplo n.º 9
0
def main():
    # Handling arguments
    args = get_args()

    backend_name = None
    if args.backend_name:
        backend_name = args.backend_name

    basename = args.basename[0]
    image_id = args.image_id
    size_id = args.size_id

    monitoring = args.monitoring

    quantity = args.quantity[0]

    print_ips = args.ips
    print_macs = args.macs

    host = args.host.rstrip('/')

    username = None
    if args.username:
        username = args.username[0]

    password = None
    if args.password:
        password = args.password[0]

    log_file = None
    if args.logfile:
        log_file = args.logfile[0]

    post_script = None
    if args.post_script:
        post_script = args.post_script[0]
    script_params = ''
    if args.script_params:
        script_params = args.script_params[0]
    if args.networks:
        networks = args.networks

    debug = args.debug
    verbose = args.verbose
    maxwait = args.maxwait[0]

    # Logging settings
    if debug:
        log_level = logging.DEBUG
    elif verbose:
        log_level = logging.INFO
    else:
        log_level = logging.WARNING

    if log_file:
        logging.basicConfig(filename=log_file,
                            format='%(asctime)s %(levelname)s %(message)s',
                            level=log_level)
    else:
        logging.basicConfig(filename=log_file,
                            format='%(asctime)s %(levelname)s %(message)s',
                            level=log_level)
    logger = logging.getLogger(__name__)

    # Getting user password
    if username and password is None:
        logger.debug('No command line password received, requesting password '
                     'from user')
        password = getpass.getpass(
            prompt='Enter mist.io password for user %s:' % (username))

    try:
        client = None
        try:
            logger.info('Connecting to mist.io with username %s' % (username))
            if username:
                client = MistClient(email=username,
                                    password=password,
                                    mist_uri=host,
                                    verify=False)
            else:
                credentials = parse_config()
                client = MistClient(email=credentials['email'],
                                    password=credentials['password'],
                                    mist_uri=credentials['mist_uri'])
        except IOError, e:
            pass

        if not client:
            logger.error('Could not connect to mist.io with user %s and '
                         'specified password' % (username))
            return 1

        # Get the requested or first backend
        if backend_name:
            backends = client.backends(name=backend_name)
        else:
            backends = client.backends()

        if not backends:
            logger.critical('Backend unavailable')
            return 1
        else:
            backend = backends[0]

        # Create a new ssh keypair for this deployment
        private = client.generate_key()
        try:
            client.add_key(key_name=basename, private=private)
        except:
            logger.warn('Key %s already exists' % basename)

        res = backend.create_machine(
            name=basename,
            key=client.keys(search=basename)[0],
            image_id=image_id,
            location_id=backend.locations[0]['id'],
            size_id=size_id,
            networks=args.networks,
            async=True,
            fire_and_forget=False,
            quantity=quantity,
            monitoring=monitoring,
            verbose=True,
            timeout=maxwait,
        )

        if print_ips or post_script:
            try:
                logger.info('Updating VM list from backend')
                backend.update_machines()
            except:  # Retry in case of network glitch
                logger.warn('Backend unavailable. Retrying')
                backend.update_machines()

            probes = [
                p for p in res['logs']
                if p['action'] == 'probe' and not p['error']
            ]
            for p in probes:
                try:
                    machine = backend.machines(p['machine_id'])[0]
                except:
                    machine = None

                print '----------'
                if machine:
                    print 'Machine:', machine.name
                    if print_ips:
                        print 'Public ip addresses:'
                        for i in machine.info.get('public_ips', []):
                            print " - ", i
                        print 'Private ip addresses:'
                        for i in machine.info.get('private_ips'):
                            print " - ", i
                else:
                    print 'Machine:', p['machine_id']

                if print_macs:
                    print 'MACS:', json.dumps(p.get('result', {}).get('macs'))

                if post_script:
                    job = client.run_script(backend.id,
                                            p['machine_id'],
                                            post_script,
                                            script_params=script_params,
                                            fire_and_forget=True)
                    if job.get('job_id'):
                        print 'Post deployment script queued: %s/jobs/%s' % \
                              (host, job.get('job_id'))

            print '----------'