Call GCE 'start on the instance.

    .. versionadded:: 2017.7.0

    CLI Example:

    .. code-block:: bash

        salt-cloud -a start myinstance
424397
def start(vm_name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The start action must be called with -a or --action.'
        )

    conn = get_conn()

    __utils__['cloud.fire_event'](
        'event',
        'start instance',
        'salt/cloud/{0}/starting'.format(vm_name),
        args={'name': vm_name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    result = conn.ex_start_node(
        conn.ex_get_node(vm_name)
    )

    __utils__['cloud.fire_event'](
        'event',
        'start instance',
        'salt/cloud/{0}/started'.format(vm_name),
        args={'name': vm_name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return result
217122
def start(self, on_exit_callback=None):
        
        # TODO: Support params for services by mapping {servicename: {class,
        # params}}?
        for service in self.services.keys():
            self.services[service] = self.services[service]()

        self.server.start(on_exit_callback)
1057414
def start
      FileUtils.mkdir_p(CloudCrowd.log_path) if @daemon && !File.exists?(CloudCrowd.log_path)
      @server          = Thin::Server.new('0.0.0.0', @port, self, :signals => false)
      @server.tag      = 'cloud-crowd-node'
      @server.pid_file = CloudCrowd.pid_path('node.pid')
      @server.log_file = CloudCrowd.log_path('node.log')
      @server.daemonize if @daemon
      trap_signals
      asset_store
      @server_thread   = Thread.new { @server.start }
      check_in(true)
      check_in_periodically
      monitor_system if @max_load || @min_memory
      @server_thread.join
    end
199981
def query_instance(vm_=None, call=None):
    '''
    
    '''
    if isinstance(vm_, six.string_types) and call == 'action':
        vm_ = {'name': vm_, 'provider': 'joyent'}

    if call == 'function':
        # Technically this function may be called other ways too, but it
        # definitely cannot be called with --function.
        raise SaltCloudSystemExit(
            'The query_instance action must be called with -a or --action.'
        )

    __utils__['cloud.fire_event'](
        'event',
        'querying instance',
        'salt/cloud/{0}/querying'.format(vm_['name']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    def _query_ip_address():
        data = show_instance(vm_['name'], call='action')
        if not data:
            log.error(
                'There was an error while querying Joyent. Empty response'
            )
            # Trigger a failure in the wait for IP function
            return False

        if isinstance(data, dict) and 'error' in data:
            log.warning('There was an error in the query %s', data.get('error'))
            # Trigger a failure in the wait for IP function
            return False

        log.debug('Returned query data: %s', data)

        if 'primaryIp' in data[1]:
            # Wait for SSH to be fully configured on the remote side
            if data[1]['state'] == 'running':
                return data[1]['primaryIp']
        return None

    try:
        data = salt.utils.cloud.wait_for_ip(
            _query_ip_address,
            timeout=config.get_cloud_config_value(
                'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=10),
            interval_multiplier=config.get_cloud_config_value(
                'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # destroy(vm_['name'])
            pass
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc))

    return data
863517
def salt_cloud():
    '''
    
    '''
    # Define 'salt' global so we may use it after ImportError. Otherwise,
    # UnboundLocalError will be raised.
    global salt  # pylint: disable=W0602

    try:
        # Late-imports for CLI performance
        import salt.cloud
        import salt.cloud.cli
    except ImportError as e:
        # No salt cloud on Windows
        log.error('Error importing salt cloud: %s', e)
        print('salt-cloud is not available in this system')
        sys.exit(salt.defaults.exitcodes.EX_UNAVAILABLE)
    if '' in sys.path:
        sys.path.remove('')

    client = salt.cloud.cli.SaltCloud()
    _install_signal_handlers(client)
    client.run()
1048817
def startup_gce_instance(instance_name, project, zone, username, machine_type,
                         image, public_key, disk_name=None):
    
    log_green("Started...")
    log_yellow("...Creating GCE Jenkins Slave Instance...")
    instance_config = get_gce_instance_config(
        instance_name, project, zone, machine_type, image,
        username, public_key, disk_name
    )
    operation = _get_gce_compute().instances().insert(
        project=project,
        zone=zone,
        body=instance_config
    ).execute()
    result = gce_wait_until_done(operation)
    if not result:
        raise RuntimeError("Creation of VM timed out or returned no result")
    log_green("Instance has booted")
979988
def show_instance(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.'
        )

    items = query(action='ve', command=name)

    ret = {}
    for item in items:
        if 'text' in item.__dict__:
            ret[item.tag] = item.text
        else:
            ret[item.tag] = item.attrib

        if item._children:
            ret[item.tag] = {}
            children = item._children
            for child in children:
                ret[item.tag][child.tag] = child.attrib

    __utils__['cloud.cache_node'](ret, __active_provider_name__, __opts__)
    return ret
452269
def launch_instance(instance_name,
                    command,
                    existing_ip=None,
                    cpu=1,
                    mem=4,
                    code_dir=None,
                    setup_command=None):
  """"""
  # Create instance
  ip = existing_ip or create_instance(instance_name, cpu=cpu, mem=mem)
  tf.logging.info("Waiting for SSH %s", instance_name)
  ready = wait_for_ssh(ip)
  if not ready:
    raise ValueError("Instance %s never ready for SSH" % instance_name)

  # Copy code
  if code_dir:
    shell_run_with_retry(COPY_CODE, retries=2,
                         local_dir=code_dir, instance_name=instance_name)

  # Run setup
  if setup_command:
    tf.logging.info("Running setup on %s", instance_name)
    remote_run(setup_command, instance_name)

  # Run command
  tf.logging.info("Running command on %s", instance_name)
  remote_run(command, instance_name, detach=True)
960795
def request_instance(vm_):
    '''
    
    '''
    if not GCE_VM_NAME_REGEX.match(vm_['name']):
        raise SaltCloudSystemExit(
            'VM names must start with a letter, only contain letters, numbers, or dashes '
            'and cannot end in a dash.'
        )

    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'gce',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    __utils__['cloud.fire_event'](
        'event',
        'create instance',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    conn = get_conn()

    kwargs = {
        'name': vm_['name'],
        'size': __get_size(conn, vm_),
        'image': __get_image(conn, vm_),
        'location': __get_location(conn, vm_),
        'ex_network': __get_network(conn, vm_),
        'ex_subnetwork': __get_subnetwork(vm_),
        'ex_tags': __get_tags(vm_),
        'ex_metadata': __get_metadata(vm_),
    }
    external_ip = config.get_cloud_config_value(
        'external_ip', vm_, __opts__, default='ephemeral'
    )

    if external_ip.lower() == 'ephemeral':
        external_ip = 'ephemeral'
        vm_['external_ip'] = external_ip
    elif external_ip == 'None':
        external_ip = None
        vm_['external_ip'] = external_ip
    else:
        region = __get_region(conn, vm_)
        external_ip = __create_orget_address(conn, external_ip, region)
        vm_['external_ip'] = {
            'name': external_ip.name,
            'address': external_ip.address,
            'region': external_ip.region.name
        }
    kwargs['external_ip'] = external_ip

    if LIBCLOUD_VERSION_INFO > (0, 15, 1):

        kwargs.update({
            'ex_disk_type': config.get_cloud_config_value(
                'ex_disk_type', vm_, __opts__, default='pd-standard'),
            'ex_disk_auto_delete': config.get_cloud_config_value(
                'ex_disk_auto_delete', vm_, __opts__, default=True),
            'ex_disks_gce_struct': config.get_cloud_config_value(
                'ex_disks_gce_struct', vm_, __opts__, default=None),
            'ex_service_accounts': config.get_cloud_config_value(
                'ex_service_accounts', vm_, __opts__, default=None),
            'ex_can_ip_forward': config.get_cloud_config_value(
                'ip_forwarding', vm_, __opts__, default=False),
            'ex_preemptible': config.get_cloud_config_value(
                'preemptible', vm_, __opts__, default=False)
        })
        if kwargs.get('ex_disk_type') not in ('pd-standard', 'pd-ssd'):
            raise SaltCloudSystemExit(
                'The value of \'ex_disk_type\' needs to be one of: '
                '\'pd-standard\', \'pd-ssd\''
            )

    # GCE accelerator options are only supported as of libcloud >= 2.3.0
    # and Python 3+ is required so that libcloud will detect a type of
    # 'string' rather than 'unicode'
    if LIBCLOUD_VERSION_INFO >= (2, 3, 0) and isinstance(u'test', str):

        kwargs.update({
            'ex_accelerator_type': config.get_cloud_config_value(
                'ex_accelerator_type', vm_, __opts__, default=None),
            'ex_accelerator_count': config.get_cloud_config_value(
                'ex_accelerator_count', vm_, __opts__, default=None)
        })
        if kwargs.get('ex_accelerator_type'):
            log.warning(
                'An accelerator is being attached to this instance, '
                'the ex_on_host_maintenance setting is being set to '
                '\'TERMINATE\' as a result'
            )
            kwargs.update({
                'ex_on_host_maintenance': 'TERMINATE'
            })

    log.info(
        'Creating GCE instance %s in %s',
        vm_['name'], kwargs['location'].name
    )
    log.debug('Create instance kwargs %s', kwargs)

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('requesting', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    try:
        node_data = conn.create_node(**kwargs)
    except Exception as exc:  # pylint: disable=W0703
        log.error(
            'Error creating %s on GCE\n\n'
            'The following exception was thrown by libcloud when trying to '
            'run the initial deployment: \n%s',
            vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
        )
        return False

    volumes = config.get_cloud_config_value(
        'volumes', vm_, __opts__, search_global=True
    )

    if volumes:
        __utils__['cloud.fire_event'](
            'event',
            'attaching volumes',
            'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
            args={'volumes': volumes},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )

        log.info('Create and attach volumes to node %s', vm_['name'])
        create_attach_volumes(
            vm_['name'],
            {
                'volumes': volumes,
                'node': node_data
            },
            call='action'
        )

    try:
        node_dict = show_instance(node_data['name'], 'action')
    except TypeError:
        # node_data is a libcloud Node which is unsubscriptable
        node_dict = show_instance(node_data.name, 'action')

    return node_dict, node_data
874578
def start(name):
    '''
    
    '''
    cmd = '/usr/sbin/svcadm enable -s -t {0}'.format(name)
    retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
    if not retcode:
        return True
    if retcode == 3:
        # Return code 3 means there was a problem with the service
        # A common case is being in the 'maintenance' state
        # Attempt a clear and try one more time
        clear_cmd = '/usr/sbin/svcadm clear {0}'.format(name)
        __salt__['cmd.retcode'](clear_cmd, python_shell=False)
        return not __salt__['cmd.retcode'](cmd, python_shell=False)
    return False
451355
def start_engines(opts, proc_mgr, proxy=None):
    '''
    
    '''
    utils = salt.loader.utils(opts, proxy=proxy)
    if opts['__role'] == 'master':
        runners = salt.loader.runner(opts, utils=utils)
    else:
        runners = []
    funcs = salt.loader.minion_mods(opts, utils=utils, proxy=proxy)
    engines = salt.loader.engines(opts, funcs, runners, utils, proxy=proxy)

    engines_opt = opts.get('engines', [])
    if isinstance(engines_opt, dict):
        engines_opt = [{k: v} for k, v in engines_opt.items()]

    # Function references are not picklable. Windows needs to pickle when
    # spawning processes. On Windows, these will need to be recalculated
    # in the spawned child process.
    if salt.utils.platform.is_windows():
        runners = None
        utils = None
        funcs = None

    for engine in engines_opt:
        if isinstance(engine, dict):
            engine, engine_opts = next(iter(engine.items()))
        else:
            engine_opts = None
        engine_name = None
        if engine_opts is not None and 'engine_module' in engine_opts:
            fun = '{0}.start'.format(engine_opts['engine_module'])
            engine_name = engine
            del engine_opts['engine_module']
        else:
            fun = '{0}.start'.format(engine)
        if fun in engines:
            start_func = engines[fun]
            if engine_name:
                name = '{0}.Engine({1}-{2})'.format(__name__,
                                                    start_func.__module__,
                                                    engine_name)
            else:
                name = '{0}.Engine({1})'.format(__name__,
                                                start_func.__module__)
            log.info('Starting Engine %s', name)
            proc_mgr.add_process(
                    Engine,
                    args=(
                        opts,
                        fun,
                        engine_opts,
                        funcs,
                        runners,
                        proxy
                        ),
                    name=name
                    )
217770
def reboot(name, call=None):
    '''
    
    '''

    if call != 'action':
        raise SaltCloudException(
            'The reboot action must be called with -a or --action.'
        )

    local = salt.client.LocalClient()
    return local.cmd(name, 'system.reboot')
603487
def show_instance(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.'
        )

    nodes = list_nodes_full()
    # Find under which cloud service the name is listed, if any
    if name not in nodes:
        return {}
    __utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
    return nodes[name]
795133
def init(runlevel):
    '''
    
    '''
    cmd = ['init', '{0}'.format(runlevel)]
    ret = __salt__['cmd.run'](cmd, python_shell=False)
    return ret
1034011
def action(func=None,
           cloudmap=None,
           instances=None,
           provider=None,
           instance=None,
           opts=None,
           **kwargs):
    '''
    
    '''
    info = {}
    client = _get_client()
    if isinstance(opts, dict):
        client.opts.update(opts)
    try:
        info = client.action(
            func,
            cloudmap,
            instances,
            provider,
            instance,
            salt.utils.args.clean_kwargs(**kwargs)
        )
    except SaltCloudConfigError as err:
        log.error(err)
    return info
193375
def setup_ci():
    # type: () -> None
    
    gcloud_path = shell.run('which gcloud', capture=True).stdout.strip()
    sdk_path = normpath(join(gcloud_path, '../../platform/google_appengine'))
    gcloud_cmd = gcloud_path + ' --quiet'

    if not exists(sdk_path):
        log.info("Installing AppEngine SDK")
        shell.run('sudo {} components install app-engine-python'.format(
            gcloud_cmd
        ))
    else:
        # Only initialise once. To reinitialise, just build without cache.
        log.info("AppEngine SDK already initialised")

    log.info("Using service account authentication")
    shell.run('{} auth activate-service-account --key-file {}'.format(
        gcloud_cmd,
        conf.proj_path('ops/client_secret.json')
    ))
814822
def query_instance(vm_=None, call=None):
    '''
    
    '''
    if call == 'function':
        # Technically this function may be called other ways too, but it
        # definitely cannot be called with --function.
        raise SaltCloudSystemExit(
            'The query_instance action must be called with -a or --action.'
        )

    instance_id = vm_['instance_id']
    location = vm_.get('location', get_location(vm_))
    __utils__['cloud.fire_event'](
        'event',
        'querying instance',
        'salt/cloud/{0}/querying'.format(vm_['name']),
        args={'instance_id': instance_id},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    log.debug('The new VM instance_id is %s', instance_id)

    params = {'Action': 'DescribeInstances',
              'InstanceId.1': instance_id}

    provider = get_provider(vm_)

    attempts = 0
    while attempts < aws.AWS_MAX_RETRIES:
        data, requesturl = aws.query(params,                # pylint: disable=unbalanced-tuple-unpacking
                                     location=location,
                                     provider=provider,
                                     opts=__opts__,
                                     return_url=True,
                                     sigver='4')
        log.debug('The query returned: %s', data)

        if isinstance(data, dict) and 'error' in data:
            log.warning(
                'There was an error in the query. %s attempts '
                'remaining: %s', attempts, data['error']
            )
        elif isinstance(data, list) and not data:
            log.warning(
                'Query returned an empty list. %s attempts '
                'remaining.', attempts
            )
        else:
            break

        aws.sleep_exponential_backoff(attempts)
        attempts += 1
        continue
    else:
        raise SaltCloudSystemExit(
            'An error occurred while creating VM: {0}'.format(data['error'])
        )

    def __query_ip_address(params, url):  # pylint: disable=W0613
        data = aws.query(params,
                         location=location,
                         provider=provider,
                         opts=__opts__,
                         sigver='4')
        if not data:
            log.error(
                'There was an error while querying EC2. Empty response'
            )
            # Trigger a failure in the wait for IP function
            return False

        if isinstance(data, dict) and 'error' in data:
            log.warning('There was an error in the query. %s', data['error'])
            # Trigger a failure in the wait for IP function
            return False

        log.debug('Returned query data: %s', data)

        if ssh_interface(vm_) == 'public_ips':
            if 'ipAddress' in data[0]['instancesSet']['item']:
                return data
            else:
                log.error(
                    'Public IP not detected.'
                )

        if ssh_interface(vm_) == 'private_ips':
            if 'privateIpAddress' in data[0]['instancesSet']['item']:
                return data
            else:
                log.error(
                    'Private IP not detected.'
                )

    try:
        data = salt.utils.cloud.wait_for_ip(
            __query_ip_address,
            update_args=(params, requesturl),
            timeout=config.get_cloud_config_value(
                'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=10),
            interval_multiplier=config.get_cloud_config_value(
                'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # It might be already up, let's destroy it!
            destroy(vm_['name'])
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc))

    if 'reactor' in vm_ and vm_['reactor'] is True:
        __utils__['cloud.fire_event'](
            'event',
            'instance queried',
            'salt/cloud/{0}/query_reactor'.format(vm_['name']),
            args={'data': data},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )

    return data