Create an Azure Container
@param {Object} cluster Azure Cluster Info
@param {Object} options Options passed to UploadFS library
@param {Function} callback Callback to be called when operation is terminated
@return {any} Returns the initialized service
173731
function createContainer(cluster, options, callback) {
  var blobSvc = azure.createBlobService(cluster.account, cluster.key);
  var container = cluster.container || options.container;
  blobSvc.createContainerIfNotExists(container, function(error, result, response) {
    if (error) {
      return callback(error);
    }
    return initializeContainer(blobSvc, container, options, callback);
  });
}
457173
function (options, callback) {
    var log = this.log;

    log('starting app server');
    if (this.startAppServerFunc) {
      // manual starting of app server
      this.startAppServerFunc(options, callback);
    } else {
      // let smocks-magellan-nightwatch automatically handle the work
      var appServer = this.appServer = new Hapi.Server();
      appServer.connection({ port: this.appPort });
      appServer.route([{
        method: 'GET',
        path: '/{path*}',
        handler: function (req, reply) {
          log('request made: ' + req.path);
          var requestPath = req.path;
          var artifactPath = Path.join(options.distPath, requestPath);
          if (requestPath.match(/\/[^\.]*$/i)) {
            log('handling response as container html file');
            // it's the main index file.  In order to re-use the transpiled files, we need to
            // ensure that the container html file represents the correct mock port so
            // we will replace that out when returning the file contents
            replyWithIndexFile(options, reply);
          } else {
            log('handling response: ' + requestPath);

            fs.exists(artifactPath, function (exists) {
              if (exists) {
                var mimeType = mimeTypes.lookup(artifactPath);
                fs.readFile(artifactPath, function (err, buffer) {
                  if (err) {
                    log('error loading file: ' + artifactPath + ': ' + e.message);
                    reply(err);
                  } else {
                    log('responding with ' + artifactPath);
                    reply(buffer).type(mimeType);
                  }
                });
              } else {
                log(artifactPath + ' does not exist... 404');
                reply({message: artifactPath + ' does not exist'}).code(404);
              }
            });
          }
        }
      }]);
      appServer.start(callback);
    }
  }
778153
def create(name, config_file=None, template=None, backing_store=None, template_options=None):
    '''
    
    
    '''
    if exists(name):
        raise ContainerAlreadyExists("The Container %s is already created!" % name)
    cmd = 'lxc-create -n %s' % name

    if config_file:
        cmd += ' -f %s' % config_file
    if template:
        cmd += ' -t %s' % template
    if backing_store:
        cmd += ' -B %s' % backing_store
    if template_options:
        cmd += '-- %s' % template_options

    if subprocess.check_call('%s >> /dev/null' % cmd, shell=True) == 0:
        if not exists(name):
            _logger.critical("The Container %s doesn't seem to be created! (options: %s)", name, cmd[3:])
            raise ContainerNotExists("The container (%s) does not exist!" % name)

        _logger.info("Container %s has been created with options %s", name, cmd[3:])
        return 0
    else:
        return 1
179261
private Completable initWithCallback(Action1<PartitionAndSeqno> callback) {
    sessionState().setToBeginningWithNoEnd(numPartitions());

    return getSeqnos()
        .doOnNext(callback)
        .reduce(new ArrayList<>(), new Func2<List<Short>, PartitionAndSeqno, List<Short>>() {
          @Override
          public List<Short> call(List<Short> partitions, PartitionAndSeqno partitionAndSeqno) {
            partitions.add(partitionAndSeqno.partition());
            return partitions;
          }
        })
        .flatMap(new Func1<List<Short>, Observable<ByteBuf>>() {
          @Override
          public Observable<ByteBuf> call(List<Short> partitions) {
            return failoverLogs(partitions.toArray(new Short[]{}));
          }
        })
        .map(new Func1<ByteBuf, Short>() {
          @Override
          public Short call(ByteBuf buf) {
            short partition = DcpFailoverLogResponse.vbucket(buf);
            handleFailoverLogResponse(buf);
            buf.release();
            return partition;
          }
        }).last().toCompletable();
  }
355908
function (options, cb) {
		let cluster = options.infra.stack;
		
		//Ref: https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.zones.clusters.nodePools/autoscaling
		let request = getConnector(options.infra.api);
		let project = request.project;
		delete request.project;
		request.clusterId = cluster.id;
		request.projectId = options.infra.api.project;
		request.zone = cluster.options.zone;
		v1Container().projects.zones.clusters.get(request, (err, clusterResponse) => {
			if (err) {
				return cb(err);
			}
			request.zone = [];
			request.name = `projects/${options.infra.api.project}/locations/${cluster.options.zone}/clusters/${cluster.id}`;
			request.nodePoolId = cluster.options.nodePoolId;
			request.resource = {
				"nodeCount": options.params.number, // get this from ui
			};
			v1Container().projects.zones.clusters.nodePools.setSize(request, (err, nodePoolsResponse) => {
				if (err) {
					return cb(err);
				}
				let maxCounter = 10;
				let counter = 0;
				
				function checkIfClusterisReady(type, miniCB) {
					setTimeout(function () {
						options.soajs.log.debug("Checking if Cluster is Ready.");
						//Ref: https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.zones.operations/get
						request.operationId = nodePoolsResponse.name;
						request.name = `projects/${options.infra.api.project}/locations/${cluster.options.zone}/operations/${nodePoolsResponse.name}`;
						delete request.resource;
						delete request.nodePoolId;
						delete request.clusterId;
						request.zone = cluster.options.zone;
						v1beta1container().projects[type].operations.get(request, function (err, response) {
							if (err) {
								return miniCB(err);
							} else if (response && response.operationType === "SET_NODE_POOL_SIZE" && response.status === "DONE") {
								return miniCB(null, true);
							} else if (counter > maxCounter) {
								return miniCB(new Error("cluster failed to update node pool size"));
							} else {
								counter++;
								checkIfClusterisReady(type, miniCB);
							}
						});
					}, (process.env.SOAJS_CLOOSTRO_TEST) ? 1 : 25 * 1000);
				}
				
				function updateMachineIps(cb) {
					driver.checkZoneRegion(options, cluster.options.zone, false, (err, type) => {
						if (err) {
							return cb(err);
						}
						checkIfClusterisReady(type, function (err) {
							if (err) {
								return cb(err);
							}
							options.soajs.log.debug("Updating Cluster IP Addresses");
							if (clusterResponse) {
								request.clusterId = cluster.id;
								request.filter = "name eq gke-" + cluster.id.substring(0, 19) + "-" + cluster.options.nodePoolId + "-.*";
								driver.checkZoneRegion(options, cluster.options.zone, true, (err, zones) => {
									if (err) {
										return cb(err);
									}
									//loop over all the zone ang get the ip of each location found in the zone
									//if zonal we only have to loop once
									let machineIPs = [];
									async.each(zones, function (oneZone, callback) {
										request.zone = oneZone;
										delete request.name;
										request.project = project;
										v1Compute().instances.list(request, (error, instances) => {
											if (error) {
												return callback(error);
											}
											if (instances && instances.items) {
												//extract name and ip from response
												instances.items.forEach((oneInstance) => {
													let mIP;
													oneInstance.networkInterfaces.forEach((oneNetInterface) => {
														if (oneNetInterface.accessConfigs) {
															oneNetInterface.accessConfigs.forEach((oneAC) => {
																if (oneAC.name === 'external-nat') {
																	mIP = oneAC.natIP;
																}
															});
														}
													});
													if (mIP) {
														machineIPs.push(mIP);
													}
												});
											}
											callback();
										});
									}, (err) => {
										if (err) {
											return cb(err);
										}
										let region;
										
										function getRegion(cb) {
											if (zones.length > 1) {
												region = cluster.options.zone;
												return cb();
											} else {
												request.region = cluster.options.zone;
												v1Compute().zones.get(request, function (err, response) {
													if (err) {
														return cb(err);
													}
													if (response && response.region){
														let regionUrl = response.region.split("/");
														region = regionUrl[regionUrl.length - 1];
													}
													return cb();
												});
											}
										}
										
										getRegion((err) => {
											if (err) {
												return cb(err);
											}
											delete request.region;
											delete request.filter;
											delete request.clusterId;
											request.region = region;
											v1Compute().addresses.list(request, (err, addresses) => {
												if (err) {
													return cb(err);
												}
												
												//remove ip address
												if (clusterResponse.currentNodeCount > options.params.number && addresses && addresses.items) {
													async.eachSeries(addresses.items, (oneAddress, callback) => {
														if (machineIPs.indexOf(oneAddress.address) === -1) {
															request.address = oneAddress.name;
															//release each address in series
															v1Compute().addresses.delete(request, (err) => {
																if (err) {
																	return callback(err);
																}
																options.soajs.log.debug("IP " + oneAddress.address + " is released!");
																return callback();
															});
														} else {
															return callback();
														}
													}, cb);
												}
												
												//add ip address
												else if (clusterResponse.currentNodeCount < options.params.number) {
													let addressArray = [];
													if (addresses && addresses.items) {
														addresses.items.forEach((oneItem) => {
															addressArray.push(oneItem.address);
														});
													}
													
													async.eachSeries(machineIPs, (oneMachineIP, callback) => {
														if (addressArray.indexOf(oneMachineIP) === -1) {
															let date = new Date();
															request.resource = {
																"name": "gke-" + cluster.id.substring(0, 19) + "-" + cluster.options.nodePoolId + "-" + date.getTime(),
																"address": oneMachineIP
															};
															v1Compute().addresses.insert(request, (err) => {
																if (err) {
																	return callback(err);
																}
																options.soajs.log.debug("IP " + oneMachineIP + " is now static!");
																return callback();
															});
														} else {
															return callback();
														}
													}, cb);
												}
											});
										});
									});
								});
							}
						});
					});
				}
				
				if (clusterResponse && clusterResponse.currentNodeCount === options.params.number) {
					return cb(null, true);
				} else {
					updateMachineIps((err) => {
						if (err) {
							options.soajs.log.error(err);
						}
					});
					return cb(null, true);
				}
			});
		});
	}
372527
private PlexusContainer createContainer() throws PlexusContainerException {
    ContainerConfiguration config = new DefaultContainerConfiguration()
        .setClassWorld(classWorld.get())
        .setName("plexus-runtime");

    DefaultPlexusContainer container = new DefaultPlexusContainer(config);
    container.setLoggerManager(new Slf4jLoggerManager());
    container.getLoggerManager().setThresholds(Logger.LEVEL_DEBUG);

    return container;
  }
919447
function (options, cb) {
		let cluster = options.infra.stack;
		let request = getConnector(options.infra.api);
		let project = request.project;
		delete request.project;
		request.zone = [];
		
		function checkIfClusterisReady(type, miniCB) {
			setTimeout(function () {
				options.soajs.log.debug("Checking if Cluster is Ready.");
				//Ref: https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.zones.operations/get
				request.operationId = cluster.options.operationId;
				request.name = `projects/${options.infra.api.project}/locations/${cluster.options.zone}/operations/${cluster.options.operationId}`;
				v1beta1container().projects[type].operations.get(request, function (err, response) {
					if (err) {
						return miniCB(err);
					} else {
						return miniCB(null, (response && response.operationType === "CREATE_CLUSTER" && response.status === "DONE"));
					}
				});
			}, (process.env.SOAJS_CLOOSTRO_TEST) ? 1 : 5 * 1000);
		}
		
		options.soajs.log.debug("Getting Environment Record:", options.soajs.registry.code.toUpperCase());
		
		//get the environment record
		if (options.soajs.registry.deployer.container.kubernetes.remote.nodes && options.soajs.registry.deployer.container.kubernetes.remote.nodes !== '') {
			let machineIp = options.soajs.registry.deployer.container.kubernetes.remote.nodes;
			return cb(null, machineIp);
		} else {
			if (!cluster || !cluster.options || !cluster.options.zone) {
				return cb(null, false);
			}
			driver.checkZoneRegion(options, cluster.options.zone, false, (err, type) => {
				if (err) {
					return cb(err)
				}
				checkIfClusterisReady(type, function (err, response) {
					if (err) {
						return cb(err);
					} else {
						if (!response) {
							options.soajs.log.debug("Cluster Not Ready Yet.");
							return cb(null, false);
						} else {
							//trigger get cluster & store the end point ip in the environment nodes entry
							//Ref https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1beta1/projects.locations.clusters/get
							let request = getConnector(options.infra.api);
							delete request.project;
							request.zone = [];
							request.name = `projects/${options.infra.api.project}/locations/${cluster.options.zone}/clusters/${cluster.id}`;
							request.clusterId = cluster.id;
							options.soajs.log.debug("Getting Cluster Information.");
							v1beta1container().projects[type].clusters.get(request, function (err, clusterInformation) {
								if (err) {
									return cb(err);
								}
								
								if (!clusterInformation || clusterInformation === '' || typeof clusterInformation !== 'object' || Object.keys(clusterInformation).length === 0) {
									options.soajs.log.debug("Cluster Not Ready Yet.");
									return cb(null, false);
								}
								
								let machineIp = clusterInformation.endpoint;
								let machineAuth = clusterInformation.masterAuth;
								let deployer = {};
								let deployerConfig = {
									url: `https://${machineIp}`,
									auth: {
										user: machineAuth.username,
										pass: machineAuth.password
									},
									request: {strictSSL: false}
								};
								let machineIPs = [];
								async.auto({
									"getKubernetesToken": function (fCb) {
										options.soajs.log.debug("Creating Kubernetes Token.");
										deployerConfig.version = 'v1';
										
										deployer.core = new K8Api.Core(deployerConfig);
										deployer.core.namespaces.secrets.get({}, (error, secretsList) => {
											if (error) {
												return fCb(error);
											}
											
											async.detect(secretsList.items, (oneSecret, callback) => {
												return callback(null, (oneSecret && oneSecret.metadata && oneSecret.metadata.name && oneSecret.metadata.name.match(/default-token-.*/g) && oneSecret.type === 'kubernetes.io/service-account-token'));
											}, (error, tokenSecret) => {
												if (tokenSecret && tokenSecret.metadata && tokenSecret.metadata.name && tokenSecret.data && tokenSecret.data.token) {
													return fCb(null, new Buffer(tokenSecret.data.token, 'base64').toString());
												} else {
													return fCb('Kubernetes api token not found!');
												}
											});
										});
									},
									"createNameSpace": ['getKubernetesToken', function (info, fCb) {
										options.soajs.log.debug("Creating new namespace for SOAJS.");
										deployerConfig.version = 'v1';
										deployerConfig.auth = {bearer: info.getKubernetesToken};
										let namespace = {
											kind: 'Namespace',
											apiVersion: 'v1',
											metadata: {
												name: options.soajs.registry.deployer.container.kubernetes.remote.namespace.default,
												labels: {'soajs.content': 'true'}
											}
										};
										deployer.core = new K8Api.Core(deployerConfig);
										deployer.core.namespaces.get({}, function (error, namespacesList) {
											if (error) {
												return fCb(error);
											}
											async.detect(namespacesList.items, function (oneNamespace, callback) {
												return callback(null, oneNamespace.metadata.name === namespace.metadata.name);
											}, function (error, foundNamespace) {
												if (foundNamespace) {
													return fCb(null, true);
												}
												deployer.core.namespace.post({body: namespace}, (error, response) => {
													if (error) {
														return fCb(error);
													}
													
													return fCb(null, true);
												});
											});
										});
									}],
									"updateEnvironment": ['getKubernetesToken', function (info, fCb) {
										options.soajs.log.debug("Updating Environment Record with Kubernetes configuration:", options.soajs.registry.code.toUpperCase());
										options.soajs.registry.deployer.container.kubernetes.remote.nodes = machineIp;
										options.soajs.registry.deployer.container.kubernetes.remote.apiPort = 443;
										options.soajs.registry.deployer.container.kubernetes.remote.auth.token = info.getKubernetesToken;
										return fCb();
									}],
									"updateStaticIps": ['updateEnvironment', function (info, fCb) {
										options.soajs.log.debug("Updating Cluster IP Addresses");
										request.clusterId = cluster.id;
										request.filter = "name eq gke-" + cluster.id.substring(0, 19) + "-" + cluster.options.nodePoolId + "-.*";
										
										driver.checkZoneRegion(options, cluster.options.zone, true, (err, zones) => {
											if (err) {
												return cb(err);
											}
											//loop over all the zone ang get the ip of each location found in the zone
											//if zonal we only have to loop once
											async.each(zones, function (oneZone, callback) {
												request.zone = oneZone;
												delete request.name;
												request.project = project;
												v1Compute().instances.list(request, (error, instances) => {
													if (error) {
														return callback(error);
													}
													if (instances && instances.items) {
														//extract name and ip from response
														instances.items.forEach((oneInstance) => {
															let mIP;
															oneInstance.networkInterfaces.forEach((oneNetInterface) => {
																if (oneNetInterface.accessConfigs) {
																	oneNetInterface.accessConfigs.forEach((oneAC) => {
																		if (oneAC.name === 'external-nat') {
																			mIP = oneAC.natIP;
																		}
																	});
																}
															});
															if (mIP) {
																machineIPs.push(mIP);
															}
														});
													}
													callback();
												});
											}, (err) => {
												if (err) {
													return fCb(err);
												}
												let region;
												
												function getRegion(cb) {
													if (zones.length > 1) {
														region = cluster.options.zone;
														return cb();
													} else {
														request.region = cluster.options.zone;
														v1Compute().zones.get(request, function (err, response) {
															if (err) {
																return cb(err);
															}
															if (response && response.region){
																let regionUrl = response.region.split("/");
																region = regionUrl[regionUrl.length - 1];
															}
															return cb();
														});
													}
												}
												
												getRegion((err) => {
													if (err) {
														return fCb(err);
													}
													delete request.region;
													delete request.filter;
													delete request.clusterId;
													request.region = region;
													async.eachSeries(machineIPs, function (oneIP, callback) {
														let date = new Date();
														request.resource = {
															"name": "gke-" + cluster.id.substring(0, 19) + "-" + cluster.options.nodePoolId + "-" + date.getTime(),
															"address": oneIP
														};
														v1Compute().addresses.insert(request, (err) => {
															if (err) {
																return callback(err);
															}
															options.soajs.log.debug("IP " + oneIP + " is now static!");
															return callback();
														});
													}, fCb);
												});
											});
										});
									}]
								}, (error) => {
									if (error) {
										return cb(error);
									}
									options.soajs.log.debug("Cluster " + cluster.id + " is now ready to use at:", machineIp);
									return cb(null, machineIp);
								});
							});
						}
					}
				});
			});
		}
	}
254290
public static Cluster getOrCreateCluster(String clusterName,
      CassandraHostConfigurator cassandraHostConfigurator) {
    return createCluster(clusterName, cassandraHostConfigurator, null);
  }
95800
def show_storage_container(kwargs=None, storage_conn=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The show_storage_container function must be called with -f or --function.'
        )

    if kwargs is None:
        kwargs = {}

    if 'name' not in kwargs:
        raise SaltCloudSystemExit('An storage container name must be specified as "name"')

    if not storage_conn:
        storage_conn = get_storage_conn(conn_kwargs=kwargs)

    data = storage_conn.get_container_properties(
        container_name=kwargs['name'],
        x_ms_lease_id=kwargs.get('lease_id', None),
    )
    return data
75955
def create(self, name, plugin_name, plugin_version,
               cluster_template_id=None, default_image_id=None,
               is_transient=None, description=None, cluster_configs=None,
               node_groups=None, user_keypair_id=None,
               anti_affinity=None, net_id=None, count=None,
               use_autoconfig=None, shares=None,
               is_public=None, is_protected=None):
        """"""

        data = {
            'name': name,
            'plugin_name': plugin_name,
            'plugin_version': plugin_version,
        }

        return self._do_create(data, cluster_template_id, default_image_id,
                               is_transient, description, cluster_configs,
                               node_groups, user_keypair_id, anti_affinity,
                               net_id, count, use_autoconfig, shares,
                               is_public, is_protected, api_ver=2)
31111
function deploy({
  containerName,
  containerRepository,
  clusterName,
  serviceName,
  accessKeyId,
  secretAccessKey,
  region = 'us-west-2',
}) {
  AWS.config.update({ accessKeyId, secretAccessKey, region });
  cd('C:\\Users\\janic\\Developer\\pikapik\\th3rdwave-api');
  const commitSHA = env.CIRCLE_SHA1 || safeExec('git rev-parse HEAD').stdout.trim();

  echo(`Deploying commit ${commitSHA}...`);

  echo('Loging in to docker registry...');
  const loginCmd = safeExec('aws ecr get-login', { silent: true }).stdout;
  safeExec(loginCmd);

  echo('Building docker image...');
  safeExec(`docker build -t ${containerName} .`);

  echo('Uploading docker image...');
  safeExec(`docker tag ${containerName} ${containerRepository}:${commitSHA}`);
  safeExec(`docker tag ${containerName} ${containerRepository}:latest`);
  safeExec(`docker push ${containerRepository}`);

  echo('Updating service...');

  const ecs = new AWS.ECS();

  ecs.describeServices({
    cluster: clusterName,
    services: [serviceName],
  }).promise()
    .then((data) => {
      const taskDefinition = data.services[0].taskDefinition;
      return ecs.describeTaskDefinition({
        taskDefinition,
      }).promise();
    })
    .then((data) => {
      const { taskDefinition } = data;

      return ecs.registerTaskDefinition({
        containerDefinitions: taskDefinition.containerDefinitions.map(def => {
          const newImage = `${def.image.split(':')[0]}:${commitSHA}`;
          return Object.assign({}, def, { image: newImage });
        }),
        family: taskDefinition.family,
        networkMode: taskDefinition.networkMode,
        taskRoleArn: taskDefinition.taskRoleArn,
        volumes: taskDefinition.volumes,
      }).promise();
    })
    .then((data) => {
      echo(`Created new revision ${data.taskDefinition.revision}.`);
      return ecs.updateService({
        service: serviceName,
        cluster: clusterName,
        taskDefinition: data.taskDefinition.taskDefinitionArn,
      }).promise();
    })
    .then(() => {
      echo('Service updated successfully.');
    })
    .catch((err) => {
      echo(err);
      exit(1);
    });
}
1348906
function(id, callback) {
        var self = this;

        var requestOptions = {
            uri: '/volumes/' + id,
            endpoint: rackspace.Endpoints.CloudBlockStorage
        };

        self.authorizedRequest(requestOptions, function(err, res, body) {
            if (err || !body.volume) {
                callback(err ? err : body);
                return;
            }

            callback(err, new rackspace.Volume(self, body.volume));
        });
    }
211135
function(containerID, options) {
        this.container = OpenLayers.Util.getElement(containerID);
        OpenLayers.Util.extend(this, options);
    }
21418
def create_in_cluster(self):
        
        try:
            self.api.create_namespaced_deployment(self.namespace, self.body)
        except ApiException as e:
            raise ConuException(
                "Exception when calling Kubernetes API - create_namespaced_deployment: %s\n" % e)

        logger.info("Creating Deployment %s in namespace: %s", self.name, self.namespace)
71222
function(options, callback) {
        var self = this;

        ['flavor', 'size'].forEach(function(required) {
            if (!options[required]) throw new Error('options.' +
                required + ' is a required argument.');
        });

        var requestOptions = {
            uri: '/instances',
            method: 'POST',
            data: {
                instance: {
                    flavorRef: options.flavor,
                    volume: {size: options.size},
                }
            },
            endpoint: rackspace.Endpoints.CloudDatabases
        };

        ['name', 'databases', 'users'].forEach(function(optional) {
            requestOptions.data.instance[optional] = options[optional];
        });

        self.authorizedRequest(requestOptions, function(err, res, body) {
            if (err || !body.instance) {
                callback(err ? err : body);
                return;
            }

            callback(err, new rackspace.DatabaseInstance(self, _.extend({}, body.instance, options)));
        });
    }
286249
function buildClusterState (opts) {
  // eslint-disable-next-line no-unused-vars
  const { makeRequest, ConfigurationError, handleError, snakeCaseKeys } = opts
  /**
   * Perform a [cluster.state](http://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-state.html) request
   *
   * @param {list} index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices
   * @param {list} metric - Limit the information returned to the specified metrics
   * @param {boolean} local - Return local information, do not retrieve the state from master node (default: false)
   * @param {time} master_timeout - Specify timeout for connection to master
   * @param {boolean} flat_settings - Return settings in flat format (default: false)
   * @param {number} wait_for_metadata_version - Wait for the metadata version to be equal or greater than the specified metadata version
   * @param {time} wait_for_timeout - The maximum time to wait for wait_for_metadata_version before timing out
   * @param {boolean} ignore_unavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
   * @param {boolean} allow_no_indices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
   * @param {enum} expand_wildcards - Whether to expand wildcard expression to concrete indices that are open, closed or both.
   */

  const acceptedQuerystring = [
    'local',
    'master_timeout',
    'flat_settings',
    'wait_for_metadata_version',
    'wait_for_timeout',
    'ignore_unavailable',
    'allow_no_indices',
    'expand_wildcards',
    'pretty',
    'human',
    'error_trace',
    'source',
    'filter_path'
  ]

  const snakeCase = {
    masterTimeout: 'master_timeout',
    flatSettings: 'flat_settings',
    waitForMetadataVersion: 'wait_for_metadata_version',
    waitForTimeout: 'wait_for_timeout',
    ignoreUnavailable: 'ignore_unavailable',
    allowNoIndices: 'allow_no_indices',
    expandWildcards: 'expand_wildcards',
    errorTrace: 'error_trace',
    filterPath: 'filter_path'
  }

  return function clusterState (params, options, callback) {
    options = options || {}
    if (typeof options === 'function') {
      callback = options
      options = {}
    }
    if (typeof params === 'function' || params == null) {
      callback = params
      params = {}
      options = {}
    }

    // check required parameters
    if (params.body != null) {
      const err = new ConfigurationError('This API does not require a body')
      return handleError(err, callback)
    }

    // check required url components
    if (params['index'] != null && (params['metric'] == null)) {
      const err = new ConfigurationError('Missing required parameter of the url: metric')
      return handleError(err, callback)
    }

    // validate headers object
    if (options.headers != null && typeof options.headers !== 'object') {
      const err = new ConfigurationError(`Headers should be an object, instead got: ${typeof options.headers}`)
      return handleError(err, callback)
    }

    var warnings = []
    var { method, body, index, metric, ...querystring } = params
    querystring = snakeCaseKeys(acceptedQuerystring, snakeCase, querystring, warnings)

    if (method == null) {
      method = 'GET'
    }

    var ignore = options.ignore
    if (typeof ignore === 'number') {
      options.ignore = [ignore]
    }

    var path = ''

    if ((metric) != null && (index) != null) {
      path = '/' + '_cluster' + '/' + 'state' + '/' + encodeURIComponent(metric) + '/' + encodeURIComponent(index)
    } else if ((metric) != null) {
      path = '/' + '_cluster' + '/' + 'state' + '/' + encodeURIComponent(metric)
    } else {
      path = '/' + '_cluster' + '/' + 'state'
    }

    // build request object
    const request = {
      method,
      path,
      body: null,
      querystring
    }

    options.warnings = warnings.length === 0 ? null : warnings
    return makeRequest(request, options, callback)
  }
}
563780
function (options, callbackFn) {
            var self = this;

            //compensate for optional options parm
            if (typeof options === 'function') {
                callbackFn = options;
                options = {};
            }

            //assign default port
            options.port = options.port || 1061;
            options.host = options.host || 'localhost';
            options.hostAndPort = 'http://' + options.host + ':' + options.port;
            options.eventStreamPath = require('path').normalize(__dirname + '/../temp/events.txt');
            options.phantomjsPath = options.phantomjsPath || 'phantomjs';

            options.debug && console.log('creating proxy to %s', options.hostAndPort);

            this.options = options;

            //try starting server
            createServer.call(self, options, function (proxy) {
                callbackFn.call(self, proxy);
            });

            return this;//return this to chain end
        }