Retrieves the Elasticsearch cluster name and version from the settings, or, if they should be missing,
creates a bootstrap client and obtains their values.
498781
public static ClusterInfo discoverClusterInfo(Settings settings, Log log) {
        ClusterName remoteClusterName = null;
        EsMajorVersion remoteVersion = null;
        String clusterName = settings.getProperty(InternalConfigurationOptions.INTERNAL_ES_CLUSTER_NAME);
        String clusterUUID = settings.getProperty(InternalConfigurationOptions.INTERNAL_ES_CLUSTER_UUID);
        String version = settings.getProperty(InternalConfigurationOptions.INTERNAL_ES_VERSION);
        if (StringUtils.hasText(clusterName) && StringUtils.hasText(version)) { // UUID is optional for now
            if (log.isDebugEnabled()) {
                log.debug(String.format("Elasticsearch cluster [NAME:%s][UUID:%s][VERSION:%s] already present in configuration; skipping discovery",
                        clusterName, clusterUUID, version));
            }
            remoteClusterName = new ClusterName(clusterName, clusterUUID);
            remoteVersion = EsMajorVersion.parse(version);
            return new ClusterInfo(remoteClusterName, remoteVersion);
        }

        RestClient bootstrap = new RestClient(settings);
        // first get ES main action info
        try {
            ClusterInfo mainInfo = bootstrap.mainInfo();
            if (log.isDebugEnabled()) {
                log.debug(String.format("Discovered Elasticsearch cluster [%s/%s], version [%s]",
                        mainInfo.getClusterName().getName(),
                        mainInfo.getClusterName().getUUID(),
                        mainInfo.getMajorVersion()));
            }
            settings.setInternalClusterInfo(mainInfo);
            return mainInfo;
        } catch (EsHadoopException ex) {
            throw new EsHadoopIllegalArgumentException(String.format("Cannot detect ES version - "
                    + "typically this happens if the network/Elasticsearch cluster is not accessible or when targeting "
                    + "a WAN/Cloud instance without the proper setting '%s'", ConfigurationOptions.ES_NODES_WAN_ONLY), ex);
        } finally {
            bootstrap.close();
        }
    }
655675
def _get_datacenter_name():
    '''
    
    '''

    proxy_type = __salt__['vsphere.get_proxy_type']()
    details = None
    if proxy_type == 'esxcluster':
        details = __salt__['esxcluster.get_details']()
    elif proxy_type == 'esxdatacenter':
        details = __salt__['esxdatacenter.get_details']()
    if not details:
        raise salt.exceptions.CommandExecutionError(
            'details for proxy type \'{0}\' not loaded'.format(proxy_type))
    return details['datacenter']
1210722
def get_vsan_cluster_config_system(service_instance):
    '''
    
    '''

    #TODO Replace when better connection mechanism is available

    #For python 2.7.9 and later, the defaul SSL conext has more strict
    #connection handshaking rule. We may need turn of the hostname checking
    #and client side cert verification
    context = None
    if sys.version_info[:3] > (2, 7, 8):
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE

    stub = service_instance._stub
    vc_mos = vsanapiutils.GetVsanVcMos(stub, context=context)
    return vc_mos['vsan-cluster-config-system']
1224137
def get_cluster_port_names(self, cluster_name):
        
        port_names = list()
        for host_name in self.get_hosts_by_clusters()[cluster_name]:
            port_names.extend(self.get_hosts_by_name(host_name))
        return port_names
865820
def get_cluster_info(host, port, ignore_cluster_errors=False):
    
    client = Telnet(host, int(port))
    client.write(b'version\n')
    res = client.read_until(b'\r\n').strip()
    version_list = res.split(b' ')
    if len(version_list) not in [2, 3] or version_list[0] != b'VERSION':
        raise WrongProtocolData('version', res)
    version = version_list[1]
    if StrictVersion(smart_text(version)) >= StrictVersion('1.4.14'):
        cmd = b'config get cluster\n'
    else:
        cmd = b'get AmazonElastiCache:cluster\n'
    client.write(cmd)
    regex_index, match_object, res = client.expect([
        re.compile(b'\n\r\nEND\r\n'),
        re.compile(b'ERROR\r\n')
    ])
    client.close()

    if res == b'ERROR\r\n' and ignore_cluster_errors:
        return {
            'version': version,
            'nodes': [
                '{0}:{1}'.format(smart_text(host),
                               smart_text(port))
            ]
        }

    ls = list(filter(None, re.compile(br'\r?\n').split(res)))
    if len(ls) != 4:
        raise WrongProtocolData(cmd, res)

    try:
        version = int(ls[1])
    except ValueError:
        raise WrongProtocolData(cmd, res)
    nodes = []
    try:
        for node in ls[2].split(b' '):
            host, ip, port = node.split(b'|')
            nodes.append('{0}:{1}'.format(smart_text(ip or host),
                                        smart_text(port)))
    except ValueError:
        raise WrongProtocolData(cmd, res)
    return {
        'version': version,
        'nodes': nodes
    }
115411
def get_clusters():
        
        LOGGER.debug("ClusterService.get_clusters")
        params = SessionService.complete_transactional_req(None)
        if MappingService.driver_type != DriverFactory.DRIVER_REST:
            if params is None:
                params = {}
            params['OPERATION'] = 'getClusters'
            args = {'properties': params}
        else:
            if params is None:
                args = {'http_operation': 'GET', 'operation_path': ''}
            else:
                args = {'http_operation': 'GET', 'operation_path': '', 'parameters': params}

        response = ClusterService.requester.call(args)

        if MappingService.driver_type != DriverFactory.DRIVER_REST:
            response = response.get()

        ret = None
        if response.rc == 0:
            ret = []
            for datacenter in response.response_content['clusters']:
                ret.append(Cluster.json_2_cluster(datacenter))
        elif response.rc != 404:
            err_msg = 'ClusterService.get_clusters - Problem while getting clusters. ' \
                      'Reason: ' + str(response.response_content) + ' - ' + str(response.error_message) + \
                      " (" + str(response.rc) + ")"
            LOGGER.warning(err_msg)
            if response.rc == 500 and ArianeMappingOverloadError.ERROR_MSG in response.error_message:
                raise ArianeMappingOverloadError("ClusterService.get_clusters", ArianeMappingOverloadError.ERROR_MSG)
            # traceback.print_stack()
        return ret
524219
public static ClientInterface getRestClientUtil(String elasticSearch){
		ElasticSearch elasticSearchSink = getElasticSearchSink( elasticSearch);
		return elasticSearchSink.getRestClientUtil();
	}
133913
def _get_version(name, results):
    '''
    
    '''
    for line in salt.utils.itertools.split(results, '\n'):
        if not line:
            continue
        try:
            pkgname, pkgver = line.rsplit('-', 1)
        except ValueError:
            continue
        if pkgname == name:
            return pkgver
    return None
402651
def get_settings(options = {}, request_options = {})
      options['getVersion'] = 2 if !options[:getVersion] && !options['getVersion']
      client.get(Protocol.settings_uri(name, options).to_s, :read, request_options)
    end
178716
def _readClusterSettings(self):
        
        metadata_server = "http://metadata/computeMetadata/v1/instance/"
        metadata_flavor = {'Metadata-Flavor': 'Google'}
        zone = requests.get(metadata_server + 'zone', headers = metadata_flavor).text
        self._zone = zone.split('/')[-1]

        project_metadata_server = "http://metadata/computeMetadata/v1/project/"
        self._projectId = requests.get(project_metadata_server + 'project-id', headers = metadata_flavor).text

        # From a GCE instance, these values can be blank. Only the projectId is needed
        self._googleJson = ''
        self._clientEmail = ''

        self._tags = requests.get(metadata_server + 'description', headers = metadata_flavor).text
        tags = json.loads(self._tags)
        self.clusterName = tags['clusterName']
        self._gceDriver = self._getDriver()
        self._instanceGroup = self._gceDriver.ex_get_instancegroup(self.clusterName, zone=self._zone)

        leader = self.getLeader()
        self._leaderPrivateIP = leader.privateIP

        # generate a public key for the leader, which is used to talk to workers
        self._masterPublicKey = self._setSSH()

        # The location of the Google credentials file on instances.
        self._credentialsPath = GoogleJobStore.nodeServiceAccountJson
        self._keyName = 'core' # key name leader users to communicate with works
        self._botoPath = self.NODE_BOTO_PATH
1077382
public ClusterInfo getClusterInfoOrThrow() {
        ClusterInfo clusterInfo = getClusterInfoOrNull();
        if (clusterInfo == null) {
            throw new IllegalArgumentException("Elasticsearch cluster name:[ " + InternalConfigurationOptions.INTERNAL_ES_CLUSTER_NAME +
                    "] not present in configuration");
        }
        return clusterInfo;
    }
197433
def get_swagger_versions(settings):
    
    swagger_versions = set(aslist(settings.get(
        'pyramid_swagger.swagger_versions', DEFAULT_SWAGGER_VERSIONS)))

    if len(swagger_versions) == 0:
        raise ValueError('pyramid_swagger.swagger_versions is empty')

    for swagger_version in swagger_versions:
        if swagger_version not in SUPPORTED_SWAGGER_VERSIONS:
            raise ValueError('Swagger version {0} is not supported.'
                             .format(swagger_version))
    return swagger_versions
1252562
def get_version():
    
    with open('sj.py') as source:
        for node in ast.walk(ast.parse(source.read(), 'sj.py')):
            if node.__class__.__name__ == 'Assign' and \
               node.targets[0].__class__.__name__ == 'Name' and \
               node.targets[0].id == '__version__':
                return node.value.s
295109
public IndexFormatVersion getIndexFormatVersion()
   {
      if (indexFormatVersion == null)
      {
         if (getContext().getParentHandler() instanceof SearchIndex)
         {
            SearchIndex parent = (SearchIndex)getContext().getParentHandler();
            if (parent.getIndexFormatVersion().getVersion() < indexRegister.getDefaultIndex().getIndexFormatVersion().getVersion())
            {
               indexFormatVersion = parent.getIndexFormatVersion();
            }
            else
            {
               indexFormatVersion = indexRegister.getDefaultIndex().getIndexFormatVersion();
            }
         }
         else
         {
            indexFormatVersion = indexRegister.getDefaultIndex().getIndexFormatVersion();
         }
      }
      return indexFormatVersion;
   }
1309048
def do_version(self, cluster=None):
        
        if not cluster:
            if not self.has_cluster():
                return None
            else:
                cluster = api.get_cluster(self.cluster)
        else:
            try:
                cluster = api.get_cluster(cluster)
            except ApiException:
                print("Error: Cluster not found")
                return None

        print("Version: %s" % (cluster.version))
1285176
private static void createIndexWithSettingsInElasticsearch(RestClient client, String index, String settings) throws Exception {
		logger.trace("createIndex([{}])", index);

		assert client != null;
		assert index != null;

        Request request = new Request("PUT", "/" + index);

		// If there are settings for this index, we use it. If not, using Elasticsearch defaults.
		if (settings != null) {
			logger.trace("Found settings for index [{}]: [{}]", index, settings);
			request.setJsonEntity(settings);
		}

        Response response = client.performRequest(request);
		if (response.getStatusLine().getStatusCode() != 200) {
			logger.warn("Could not create index [{}]", index);
			throw new Exception("Could not create index ["+index+"].");
		}

		logger.trace("/createIndex([{}])", index);
	}
1314980
function ElasticSearch () {
  var self = this;

  self.klass = ElasticSearch;
  self.klass.super_.apply(self, arguments);

  var auth = [
        self.options.server.username,
        self.options.server.password
      ].compact().join(':');

  self.options.server.auth = auth;
  self.options.server.protocol = undefined;
}