Compare commits
12 Commits
v9.0.0-alp
...
drop-body-
| Author | SHA1 | Date | |
|---|---|---|---|
| 70aae3b44f | |||
| 444975b4e6 | |||
| 341168d2a1 | |||
| f835fa3b12 | |||
| e688f36396 | |||
| b8c3ac446e | |||
| 3a288cf86b | |||
| 100be27ad1 | |||
| c490dd0821 | |||
| e992c329c3 | |||
| bfdae66333 | |||
| ed3cace127 |
@ -25,7 +25,7 @@ steps:
|
||||
provider: "gcp"
|
||||
image: family/core-ubuntu-2204
|
||||
plugins:
|
||||
- junit-annotate#v2.5.0:
|
||||
- junit-annotate#v2.6.0:
|
||||
artifacts: "junit-output/junit-*.xml"
|
||||
job-uuid-file-pattern: "junit-(.*).xml"
|
||||
fail-build-on-error: true
|
||||
|
||||
4
.github/make.sh
vendored
4
.github/make.sh
vendored
@ -65,7 +65,7 @@ codegen)
|
||||
if [ -v "$VERSION" ] || [[ -z "$VERSION" ]]; then
|
||||
# fall back to branch name or `main` if no VERSION is set
|
||||
branch_name=$(git rev-parse --abbrev-ref HEAD)
|
||||
if [[ "$branch_name" =~ ^[0-9]+\.[0-9]+ ]]; then
|
||||
if [[ "$branch_name" =~ ^[0-9]+\.([0-9]+|x) ]]; then
|
||||
echo -e "\033[36;1mTARGET: codegen -> No VERSION argument found, using branch name: \`$branch_name\`\033[0m"
|
||||
VERSION="$branch_name"
|
||||
else
|
||||
@ -176,7 +176,7 @@ else
|
||||
--rm \
|
||||
$product \
|
||||
/bin/bash -c "cd /usr/src && \
|
||||
git clone https://$CLIENTS_GITHUB_TOKEN@github.com/elastic/elastic-client-generator-js.git && \
|
||||
git clone --branch $GENERATOR_BRANCH https://$CLIENTS_GITHUB_TOKEN@github.com/elastic/elastic-client-generator-js.git && \
|
||||
mkdir -p /usr/src/elastic-client-generator-js/output && \
|
||||
cd /usr/src/elasticsearch-js && \
|
||||
node .buildkite/make.mjs --task $TASK ${TASK_ARGS[*]}"
|
||||
|
||||
2
.github/workflows/serverless-patch.yml
vendored
2
.github/workflows/serverless-patch.yml
vendored
@ -42,7 +42,7 @@ jobs:
|
||||
- name: Apply patch from stack to serverless
|
||||
id: apply-patch
|
||||
run: $GITHUB_WORKSPACE/stack/.github/workflows/serverless-patch.sh
|
||||
- uses: peter-evans/create-pull-request@5e914681df9dc83aa4e4905692ca88beb2f9e91f # v7
|
||||
- uses: peter-evans/create-pull-request@67ccf781d68cd99b580ae25a5c18a1cc84ffff1f # v7
|
||||
with:
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
path: serverless
|
||||
|
||||
@ -12,6 +12,29 @@
|
||||
|
||||
In 8.0, the top-level `body` parameter that was available on all API functions <<remove-body-key,was deprecated>>. In 9.0 this property is completely removed.
|
||||
|
||||
[discrete]
|
||||
=== 8.17.0
|
||||
|
||||
[discrete]
|
||||
==== Features
|
||||
|
||||
[discrete]
|
||||
===== Support for Elasticsearch `v8.17`
|
||||
|
||||
You can find all the API changes
|
||||
https://www.elastic.co/guide/en/elasticsearch/reference/8.17/release-notes-8.17.0.html[here].
|
||||
|
||||
[discrete]
|
||||
=== 8.16.3
|
||||
|
||||
[discrete]
|
||||
==== Fixes
|
||||
|
||||
[discrete]
|
||||
===== Improved support for Elasticsearch `v8.16`
|
||||
|
||||
Updated TypeScript types based on fixes and improvements to the Elasticsearch specification.
|
||||
|
||||
[discrete]
|
||||
=== 8.16.2
|
||||
|
||||
|
||||
18
docs/doc_examples/53d9d2ec9cb8d211772d764e76fe6890.asciidoc
Normal file
18
docs/doc_examples/53d9d2ec9cb8d211772d764e76fe6890.asciidoc
Normal file
@ -0,0 +1,18 @@
|
||||
// This file is autogenerated, DO NOT EDIT
|
||||
// Use `node scripts/generate-docs-examples.js` to generate the docs examples
|
||||
|
||||
[source, js]
|
||||
----
|
||||
const response = await client.ingest.simulate({
|
||||
id: "query_helper_pipeline",
|
||||
docs: [
|
||||
{
|
||||
_source: {
|
||||
content:
|
||||
"artificial intelligence in medicine articles published in the last 12 months",
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
console.log(response);
|
||||
----
|
||||
32
docs/doc_examples/931817b168e055ecf738785c721125dd.asciidoc
Normal file
32
docs/doc_examples/931817b168e055ecf738785c721125dd.asciidoc
Normal file
@ -0,0 +1,32 @@
|
||||
// This file is autogenerated, DO NOT EDIT
|
||||
// Use `node scripts/generate-docs-examples.js` to generate the docs examples
|
||||
|
||||
[source, js]
|
||||
----
|
||||
const response = await client.ingest.putPipeline({
|
||||
id: "query_helper_pipeline",
|
||||
processors: [
|
||||
{
|
||||
script: {
|
||||
source:
|
||||
"ctx.prompt = 'Please generate an elasticsearch search query on index `articles_index` for the following natural language query. Dates are in the field `@timestamp`, document types are in the field `type` (options are `news`, `publication`), categories in the field `category` and can be multiple (options are `medicine`, `pharmaceuticals`, `technology`), and document names are in the field `title` which should use a fuzzy match. Ignore fields which cannot be determined from the natural language query context: ' + ctx.content",
|
||||
},
|
||||
},
|
||||
{
|
||||
inference: {
|
||||
model_id: "openai_chat_completions",
|
||||
input_output: {
|
||||
input_field: "prompt",
|
||||
output_field: "query",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
remove: {
|
||||
field: "prompt",
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
console.log(response);
|
||||
----
|
||||
24
docs/doc_examples/d29031409016b2b798148ef173a196ae.asciidoc
Normal file
24
docs/doc_examples/d29031409016b2b798148ef173a196ae.asciidoc
Normal file
@ -0,0 +1,24 @@
|
||||
// This file is autogenerated, DO NOT EDIT
|
||||
// Use `node scripts/generate-docs-examples.js` to generate the docs examples
|
||||
|
||||
[source, js]
|
||||
----
|
||||
const response = await client.indices.create({
|
||||
index: "test-index",
|
||||
query: {
|
||||
semantic: {
|
||||
field: "my_semantic_field",
|
||||
},
|
||||
},
|
||||
highlight: {
|
||||
fields: {
|
||||
my_semantic_field: {
|
||||
type: "semantic",
|
||||
number_of_fragments: 2,
|
||||
order: "score",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
console.log(response);
|
||||
----
|
||||
@ -531,7 +531,24 @@ client.getSource({ id, index })
|
||||
|
||||
[discrete]
|
||||
=== health_report
|
||||
Returns the health of the cluster.
|
||||
Get the cluster health.
|
||||
Get a report with the health status of an Elasticsearch cluster.
|
||||
The report contains a list of indicators that compose Elasticsearch functionality.
|
||||
|
||||
Each indicator has a health status of: green, unknown, yellow or red.
|
||||
The indicator will provide an explanation and metadata describing the reason for its current health status.
|
||||
|
||||
The cluster’s status is controlled by the worst indicator status.
|
||||
|
||||
In the event that an indicator’s status is non-green, a list of impacts may be present in the indicator result which detail the functionalities that are negatively affected by the health issue.
|
||||
Each impact carries with it a severity level, an area of the system that is affected, and a simple description of the impact on the system.
|
||||
|
||||
Some health indicators can determine the root cause of a health problem and prescribe a set of steps that can be performed in order to improve the health of the system.
|
||||
The root cause and remediation steps are encapsulated in a diagnosis.
|
||||
A diagnosis contains a cause detailing a root cause analysis, an action containing a brief description of the steps to take to fix the problem, the list of affected resources (if applicable), and a detailed step-by-step troubleshooting guide to fix the diagnosed problem.
|
||||
|
||||
NOTE: The health indicators perform root cause analysis of non-green health statuses. This can be computationally expensive when called frequently.
|
||||
When setting up automated polling of the API for health status, set verbose to false to disable the more expensive analysis logic.
|
||||
|
||||
{ref}/health-api.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -825,7 +842,7 @@ If `true`, the point in time will contain all the shards that are available at t
|
||||
[discrete]
|
||||
=== ping
|
||||
Ping the cluster.
|
||||
Returns whether the cluster is running.
|
||||
Get information about whether the cluster is running.
|
||||
|
||||
{ref}/index.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -2658,7 +2675,11 @@ client.ccr.unfollow({ index })
|
||||
=== cluster
|
||||
[discrete]
|
||||
==== allocation_explain
|
||||
Provides explanations for shard allocations in the cluster.
|
||||
Explain the shard allocations.
|
||||
Get explanations for shard allocations in the cluster.
|
||||
For unassigned shards, it provides an explanation for why the shard is unassigned.
|
||||
For assigned shards, it provides an explanation for why the shard is remaining on its current node and has not moved or rebalanced to another node.
|
||||
This API can be very useful when attempting to diagnose why a shard is unassigned or why a shard continues to remain on its current node when you might expect otherwise.
|
||||
|
||||
{ref}/cluster-allocation-explain.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -2701,7 +2722,8 @@ If no response is received before the timeout expires, the request fails and ret
|
||||
|
||||
[discrete]
|
||||
==== delete_voting_config_exclusions
|
||||
Clears cluster voting config exclusions.
|
||||
Clear cluster voting config exclusions.
|
||||
Remove master-eligible nodes from the voting configuration exclusion list.
|
||||
|
||||
{ref}/voting-config-exclusions.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -2769,7 +2791,7 @@ If no response is received before the timeout expires, the request fails and ret
|
||||
|
||||
[discrete]
|
||||
==== get_settings
|
||||
Returns cluster-wide settings.
|
||||
Get cluster-wide settings.
|
||||
By default, it returns only settings that have been explicitly defined.
|
||||
|
||||
{ref}/cluster-get-settings.html[Endpoint documentation]
|
||||
@ -2791,8 +2813,16 @@ If no response is received before the timeout expires, the request fails and ret
|
||||
|
||||
[discrete]
|
||||
==== health
|
||||
The cluster health API returns a simple status on the health of the cluster. You can also use the API to get the health status of only specified data streams and indices. For data streams, the API retrieves the health status of the stream’s backing indices.
|
||||
The cluster health status is: green, yellow or red. On the shard level, a red status indicates that the specific shard is not allocated in the cluster, yellow means that the primary shard is allocated but replicas are not, and green means that all shards are allocated. The index level status is controlled by the worst shard status. The cluster status is controlled by the worst index status.
|
||||
Get the cluster health status.
|
||||
You can also use the API to get the health status of only specified data streams and indices.
|
||||
For data streams, the API retrieves the health status of the stream’s backing indices.
|
||||
|
||||
The cluster health status is: green, yellow or red.
|
||||
On the shard level, a red status indicates that the specific shard is not allocated in the cluster. Yellow means that the primary shard is allocated but replicas are not. Green means that all shards are allocated.
|
||||
The index level status is controlled by the worst shard status.
|
||||
|
||||
One of the main benefits of the API is the ability to wait until the cluster reaches a certain high watermark health level.
|
||||
The cluster status is controlled by the worst index status.
|
||||
|
||||
{ref}/cluster-health.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -2836,9 +2866,11 @@ client.cluster.info({ target })
|
||||
|
||||
[discrete]
|
||||
==== pending_tasks
|
||||
Returns cluster-level changes (such as create index, update mapping, allocate or fail shard) that have not yet been executed.
|
||||
Get the pending cluster tasks.
|
||||
Get information about cluster-level changes (such as create index, update mapping, allocate or fail shard) that have not yet taken effect.
|
||||
|
||||
NOTE: This API returns a list of any pending updates to the cluster state.
|
||||
These are distinct from the tasks reported by the Task Management API which include periodic tasks and tasks initiated by the user, such as node stats, search queries, or create index requests.
|
||||
These are distinct from the tasks reported by the task management API which include periodic tasks and tasks initiated by the user, such as node stats, search queries, or create index requests.
|
||||
However, if a user-initiated task such as a create index command causes a cluster state update, the activity of this task might be reported by both task api and pending cluster tasks API.
|
||||
|
||||
{ref}/cluster-pending.html[Endpoint documentation]
|
||||
@ -2858,7 +2890,24 @@ If no response is received before the timeout expires, the request fails and ret
|
||||
|
||||
[discrete]
|
||||
==== post_voting_config_exclusions
|
||||
Updates the cluster voting config exclusions by node ids or node names.
|
||||
Update voting configuration exclusions.
|
||||
Update the cluster voting config exclusions by node IDs or node names.
|
||||
By default, if there are more than three master-eligible nodes in the cluster and you remove fewer than half of the master-eligible nodes in the cluster at once, the voting configuration automatically shrinks.
|
||||
If you want to shrink the voting configuration to contain fewer than three nodes or to remove half or more of the master-eligible nodes in the cluster at once, use this API to remove departing nodes from the voting configuration manually.
|
||||
The API adds an entry for each specified node to the cluster’s voting configuration exclusions list.
|
||||
It then waits until the cluster has reconfigured its voting configuration to exclude the specified nodes.
|
||||
|
||||
Clusters should have no voting configuration exclusions in normal operation.
|
||||
Once the excluded nodes have stopped, clear the voting configuration exclusions with `DELETE /_cluster/voting_config_exclusions`.
|
||||
This API waits for the nodes to be fully removed from the cluster before it returns.
|
||||
If your cluster has voting configuration exclusions for nodes that you no longer intend to remove, use `DELETE /_cluster/voting_config_exclusions?wait_for_removal=false` to clear the voting configuration exclusions without waiting for the nodes to leave the cluster.
|
||||
|
||||
A response to `POST /_cluster/voting_config_exclusions` with an HTTP status code of 200 OK guarantees that the node has been removed from the voting configuration and will not be reinstated until the voting configuration exclusions are cleared by calling `DELETE /_cluster/voting_config_exclusions`.
|
||||
If the call to `POST /_cluster/voting_config_exclusions` fails or returns a response with an HTTP status code other than 200 OK then the node may not have been removed from the voting configuration.
|
||||
In that case, you may safely retry the call.
|
||||
|
||||
NOTE: Voting exclusions are required only when you remove at least half of the master-eligible nodes from a cluster in a short time period.
|
||||
They are not required when removing master-ineligible nodes or when removing fewer than half of the master-eligible nodes.
|
||||
|
||||
{ref}/voting-config-exclusions.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -2929,7 +2978,24 @@ If no response is received before the timeout expires, the request fails and ret
|
||||
|
||||
[discrete]
|
||||
==== put_settings
|
||||
Updates the cluster settings.
|
||||
Update the cluster settings.
|
||||
Configure and update dynamic settings on a running cluster.
|
||||
You can also configure dynamic settings locally on an unstarted or shut down node in `elasticsearch.yml`.
|
||||
|
||||
Updates made with this API can be persistent, which apply across cluster restarts, or transient, which reset after a cluster restart.
|
||||
You can also reset transient or persistent settings by assigning them a null value.
|
||||
|
||||
If you configure the same setting using multiple methods, Elasticsearch applies the settings in following order of precedence: 1) Transient setting; 2) Persistent setting; 3) `elasticsearch.yml` setting; 4) Default setting value.
|
||||
For example, you can apply a transient setting to override a persistent setting or `elasticsearch.yml` setting.
|
||||
However, a change to an `elasticsearch.yml` setting will not override a defined transient or persistent setting.
|
||||
|
||||
TIP: In Elastic Cloud, use the user settings feature to configure all cluster settings. This method automatically rejects unsafe settings that could break your cluster.
|
||||
If you run Elasticsearch on your own hardware, use this API to configure dynamic cluster settings.
|
||||
Only use `elasticsearch.yml` for static cluster settings and node settings.
|
||||
The API doesn’t require a restart and ensures a setting’s value is the same on all nodes.
|
||||
|
||||
WARNING: Transient cluster settings are no longer recommended. Use persistent cluster settings instead.
|
||||
If a cluster becomes unstable, transient settings can clear unexpectedly, resulting in a potentially undesired cluster configuration.
|
||||
|
||||
{ref}/cluster-update-settings.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -2949,9 +3015,9 @@ client.cluster.putSettings({ ... })
|
||||
|
||||
[discrete]
|
||||
==== remote_info
|
||||
The cluster remote info API allows you to retrieve all of the configured
|
||||
remote cluster information. It returns connection and endpoint information
|
||||
keyed by the configured remote cluster alias.
|
||||
Get remote cluster information.
|
||||
Get all of the configured remote cluster information.
|
||||
This API returns connection and endpoint information keyed by the configured remote cluster alias.
|
||||
|
||||
{ref}/cluster-remote-info.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -2962,7 +3028,20 @@ client.cluster.remoteInfo()
|
||||
|
||||
[discrete]
|
||||
==== reroute
|
||||
Allows to manually change the allocation of individual shards in the cluster.
|
||||
Reroute the cluster.
|
||||
Manually change the allocation of individual shards in the cluster.
|
||||
For example, a shard can be moved from one node to another explicitly, an allocation can be canceled, and an unassigned shard can be explicitly allocated to a specific node.
|
||||
|
||||
It is important to note that after processing any reroute commands Elasticsearch will perform rebalancing as normal (respecting the values of settings such as `cluster.routing.rebalance.enable`) in order to remain in a balanced state.
|
||||
For example, if the requested allocation includes moving a shard from node1 to node2 then this may cause a shard to be moved from node2 back to node1 to even things out.
|
||||
|
||||
The cluster can be set to disable allocations using the `cluster.routing.allocation.enable` setting.
|
||||
If allocations are disabled then the only allocations that will be performed are explicit ones given using the reroute command, and consequent allocations due to rebalancing.
|
||||
|
||||
The cluster will attempt to allocate a shard a maximum of `index.allocation.max_retries` times in a row (defaults to `5`), before giving up and leaving the shard unallocated.
|
||||
This scenario can be caused by structural problems such as having an analyzer which refers to a stopwords file which doesn’t exist on all nodes.
|
||||
|
||||
Once the problem has been corrected, allocation can be manually retried by calling the reroute API with the `?retry_failed` URI query parameter, which will attempt a single retry round for these shards.
|
||||
|
||||
{ref}/cluster-reroute.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -2975,8 +3054,9 @@ client.cluster.reroute({ ... })
|
||||
|
||||
* *Request (object):*
|
||||
** *`commands` (Optional, { cancel, move, allocate_replica, allocate_stale_primary, allocate_empty_primary }[])*: Defines the commands to perform.
|
||||
** *`dry_run` (Optional, boolean)*: If true, then the request simulates the operation only and returns the resulting state.
|
||||
** *`explain` (Optional, boolean)*: If true, then the response contains an explanation of why the commands can or cannot be executed.
|
||||
** *`dry_run` (Optional, boolean)*: If true, then the request simulates the operation.
|
||||
It will calculate the result of applying the commands to the current cluster state and return the resulting cluster state after the commands (and rebalancing) have been applied; it will not actually perform the requested changes.
|
||||
** *`explain` (Optional, boolean)*: If true, then the response contains an explanation of why the commands can or cannot run.
|
||||
** *`metric` (Optional, string | string[])*: Limits the information returned to the specified metrics.
|
||||
** *`retry_failed` (Optional, boolean)*: If true, then retries allocation of shards that are blocked due to too many subsequent allocation failures.
|
||||
** *`master_timeout` (Optional, string | -1 | 0)*: Period to wait for a connection to the master node. If no response is received before the timeout expires, the request fails and returns an error.
|
||||
@ -2984,7 +3064,25 @@ client.cluster.reroute({ ... })
|
||||
|
||||
[discrete]
|
||||
==== state
|
||||
Returns a comprehensive information about the state of the cluster.
|
||||
Get the cluster state.
|
||||
Get comprehensive information about the state of the cluster.
|
||||
|
||||
The cluster state is an internal data structure which keeps track of a variety of information needed by every node, including the identity and attributes of the other nodes in the cluster; cluster-wide settings; index metadata, including the mapping and settings for each index; the location and status of every shard copy in the cluster.
|
||||
|
||||
The elected master node ensures that every node in the cluster has a copy of the same cluster state.
|
||||
This API lets you retrieve a representation of this internal state for debugging or diagnostic purposes.
|
||||
You may need to consult the Elasticsearch source code to determine the precise meaning of the response.
|
||||
|
||||
By default the API will route requests to the elected master node since this node is the authoritative source of cluster states.
|
||||
You can also retrieve the cluster state held on the node handling the API request by adding the `?local=true` query parameter.
|
||||
|
||||
Elasticsearch may need to expend significant effort to compute a response to this API in larger clusters, and the response may comprise a very large quantity of data.
|
||||
If you use this API repeatedly, your cluster may become unstable.
|
||||
|
||||
WARNING: The response is a representation of an internal data structure.
|
||||
Its format is not subject to the same compatibility guarantees as other more stable APIs and may change from version to version.
|
||||
Do not query this API using external monitoring tools.
|
||||
Instead, obtain the information you require using other more stable cluster APIs.
|
||||
|
||||
{ref}/cluster-state.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -3009,8 +3107,8 @@ client.cluster.state({ ... })
|
||||
|
||||
[discrete]
|
||||
==== stats
|
||||
Returns cluster statistics.
|
||||
It returns basic index metrics (shard numbers, store size, memory usage) and information about the current nodes that form the cluster (number, roles, os, jvm versions, memory usage, cpu and installed plugins).
|
||||
Get cluster statistics.
|
||||
Get basic index metrics (shard numbers, store size, memory usage) and information about the current nodes that form the cluster (number, roles, os, jvm versions, memory usage, cpu and installed plugins).
|
||||
|
||||
{ref}/cluster-stats.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -8487,7 +8585,8 @@ client.monitoring.bulk({ system_id, system_api_version, interval })
|
||||
=== nodes
|
||||
[discrete]
|
||||
==== clear_repositories_metering_archive
|
||||
You can use this API to clear the archived repositories metering information in the cluster.
|
||||
Clear the archived repositories metering.
|
||||
Clear the archived repositories metering information in the cluster.
|
||||
|
||||
{ref}/clear-repositories-metering-archive-api.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -8505,10 +8604,10 @@ All the nodes selective options are explained [here](https://www.elastic.co/guid
|
||||
|
||||
[discrete]
|
||||
==== get_repositories_metering_info
|
||||
You can use the cluster repositories metering API to retrieve repositories metering information in a cluster.
|
||||
This API exposes monotonically non-decreasing counters and it’s expected that clients would durably store the
|
||||
information needed to compute aggregations over a period of time. Additionally, the information exposed by this
|
||||
API is volatile, meaning that it won’t be present after node restarts.
|
||||
Get cluster repositories metering.
|
||||
Get repositories metering information for a cluster.
|
||||
This API exposes monotonically non-decreasing counters and it is expected that clients would durably store the information needed to compute aggregations over a period of time.
|
||||
Additionally, the information exposed by this API is volatile, meaning that it will not be present after node restarts.
|
||||
|
||||
{ref}/get-repositories-metering-api.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -8525,8 +8624,9 @@ All the nodes selective options are explained [here](https://www.elastic.co/guid
|
||||
|
||||
[discrete]
|
||||
==== hot_threads
|
||||
This API yields a breakdown of the hot threads on each selected node in the cluster.
|
||||
The output is plain text with a breakdown of each node’s top hot threads.
|
||||
Get the hot threads for nodes.
|
||||
Get a breakdown of the hot threads on each selected node in the cluster.
|
||||
The output is plain text with a breakdown of the top hot threads for each node.
|
||||
|
||||
{ref}/cluster-nodes-hot-threads.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -8554,7 +8654,8 @@ before the timeout expires, the request fails and returns an error.
|
||||
|
||||
[discrete]
|
||||
==== info
|
||||
Returns cluster nodes information.
|
||||
Get node information.
|
||||
By default, the API returns all attributes and core settings for cluster nodes.
|
||||
|
||||
{ref}/cluster-nodes-info.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -8574,7 +8675,15 @@ client.nodes.info({ ... })
|
||||
|
||||
[discrete]
|
||||
==== reload_secure_settings
|
||||
Reloads the keystore on nodes in the cluster.
|
||||
Reload the keystore on nodes in the cluster.
|
||||
|
||||
Secure settings are stored in an on-disk keystore. Certain of these settings are reloadable.
|
||||
That is, you can change them on disk and reload them without restarting any nodes in the cluster.
|
||||
When you have updated reloadable secure settings in your keystore, you can use this API to reload those settings on each node.
|
||||
|
||||
When the Elasticsearch keystore is password protected and not simply obfuscated, you must provide the password for the keystore when you reload the secure settings.
|
||||
Reloading the settings for the whole cluster assumes that the keystores for all nodes are protected with the same password; this method is allowed only when inter-node communications are encrypted.
|
||||
Alternatively, you can reload the secure settings on each node by locally accessing the API and passing the node-specific Elasticsearch keystore password.
|
||||
|
||||
{ref}/secure-settings.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -8593,7 +8702,9 @@ If no response is received before the timeout expires, the request fails and ret
|
||||
|
||||
[discrete]
|
||||
==== stats
|
||||
Returns cluster nodes statistics.
|
||||
Get node statistics.
|
||||
Get statistics for nodes in a cluster.
|
||||
By default, all stats are returned. You can limit the returned information by using metrics.
|
||||
|
||||
{ref}/cluster-nodes-stats.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
@ -8621,7 +8732,7 @@ client.nodes.stats({ ... })
|
||||
|
||||
[discrete]
|
||||
==== usage
|
||||
Returns information on the usage of features.
|
||||
Get feature usage information.
|
||||
|
||||
{ref}/cluster-nodes-usage.html[Endpoint documentation]
|
||||
[source,ts]
|
||||
|
||||
@ -56,8 +56,8 @@
|
||||
"node": ">=18"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@elastic/request-converter": "8.16.2",
|
||||
"@sinonjs/fake-timers": "github:sinonjs/fake-timers#0bfffc1",
|
||||
"@elastic/request-converter": "8.17.0",
|
||||
"@sinonjs/fake-timers": "github:sinonjs/fake-timers#48f089f",
|
||||
"@types/debug": "4.1.12",
|
||||
"@types/ms": "0.7.34",
|
||||
"@types/node": "22.10.1",
|
||||
|
||||
54
scripts/codemod/drop-body.test.ts
Normal file
54
scripts/codemod/drop-body.test.ts
Normal file
@ -0,0 +1,54 @@
|
||||
import { Client } from '../..'
|
||||
|
||||
const client = new Client({
|
||||
node: 'http://localhost:9200',
|
||||
auth: { username: 'elastic', password: 'changeme' }
|
||||
})
|
||||
|
||||
async function doThings () {
|
||||
// should get fixed by codemod
|
||||
await client.closePointInTime({
|
||||
body: {
|
||||
id: 'foobar'
|
||||
}
|
||||
})
|
||||
|
||||
await client.asyncSearch.get({
|
||||
// @ts-expect-error should get fixed by codemod
|
||||
body: {
|
||||
id: 'foo'
|
||||
}
|
||||
})
|
||||
|
||||
// @ts-expect-error should get fixed by codemod
|
||||
await client.create({
|
||||
id: 'foo',
|
||||
body: { index: 'my-index' }
|
||||
})
|
||||
|
||||
await client.watcher.putWatch({
|
||||
id: 'foo',
|
||||
active: true
|
||||
})
|
||||
|
||||
const body = { id: 'foo' }
|
||||
// @ts-expect-error should get fixed by codemod
|
||||
await client.asyncSearch.get({ body })
|
||||
await client.asyncSearch.get(body)
|
||||
|
||||
const request = { body }
|
||||
// @ts-expect-error should get fixed by codemod
|
||||
await client.asyncSearch.get(request)
|
||||
|
||||
const request2 = body
|
||||
await client.closePointInTime(request2)
|
||||
|
||||
// some non-client calls
|
||||
const x = Math.random()
|
||||
console.log(x)
|
||||
console.log({ body: 'foo' })
|
||||
}
|
||||
|
||||
doThings()
|
||||
.then(() => console.log('done'))
|
||||
.catch(() => console.error('uh oh'))
|
||||
172
scripts/codemod/drop-body.ts
Normal file
172
scripts/codemod/drop-body.ts
Normal file
@ -0,0 +1,172 @@
|
||||
/*
|
||||
* Licensed to Elasticsearch B.V. under one or more contributor
|
||||
* license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright
|
||||
* ownership. Elasticsearch B.V. licenses this file to you under
|
||||
* the Apache License, Version 2.0 (the "License") you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import ts from 'typescript'
|
||||
import path from 'node:path'
|
||||
import minimist from 'minimist'
|
||||
|
||||
const apis = [
|
||||
'asyncSearch',
|
||||
'autoscaling',
|
||||
'bulk',
|
||||
'capabilities',
|
||||
'cat',
|
||||
'ccr',
|
||||
'clearScroll',
|
||||
'closePointInTime',
|
||||
'cluster',
|
||||
'connector',
|
||||
'count',
|
||||
'create',
|
||||
'danglingIndices',
|
||||
'delete',
|
||||
'deleteByQuery',
|
||||
'deleteByQueryRethrottle',
|
||||
'deleteScript',
|
||||
'enrich',
|
||||
'eql',
|
||||
'esql',
|
||||
'exists',
|
||||
'existsSource',
|
||||
'explain',
|
||||
'features',
|
||||
'fieldCaps',
|
||||
]
|
||||
|
||||
/**
|
||||
* Detects whether a node is a `Client` instance identifier
|
||||
* @remarks Uses duck-typing by checking that several Elasticsearch APIs exist as members on the identifier
|
||||
*/
|
||||
function isClient(node: ts.Identifier) {
|
||||
const type = checker.getTypeAtLocation(node)
|
||||
const properties = type.getProperties().map(prop => prop.escapedName.toString())
|
||||
|
||||
for (const api of apis) {
|
||||
if (!properties.includes(api)) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the call expression node is running a client API function, otherwise false
|
||||
*/
|
||||
function isClientExpression(node: ts.CallExpression): boolean {
|
||||
let flag = false
|
||||
function visitIdentifiers(node: ts.Node) {
|
||||
if (ts.isIdentifier(node) && isClient(node)) {
|
||||
flag = true
|
||||
return
|
||||
}
|
||||
ts.forEachChild(node, visitIdentifiers)
|
||||
}
|
||||
visitIdentifiers(node)
|
||||
return flag
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of all call expressions to `Client` functions
|
||||
*/
|
||||
function collectClientCallExpressions(node: ts.SourceFile): ts.CallExpression[] {
|
||||
const clientExpressions: ts.CallExpression[] = []
|
||||
|
||||
// recurse through all child nodes looking for `Client` call expressions
|
||||
function collect(node: ts.Node) {
|
||||
if (ts.isCallExpression(node)) {
|
||||
// look for client identifier
|
||||
if (isClientExpression(node)) {
|
||||
clientExpressions.push(node)
|
||||
}
|
||||
}
|
||||
|
||||
ts.forEachChild(node, collect)
|
||||
}
|
||||
|
||||
ts.forEachChild(node, collect)
|
||||
|
||||
return clientExpressions
|
||||
}
|
||||
|
||||
function fixBodyProp(sourceFile: ts.SourceFile, node: ts.Node) {
|
||||
if (ts.isObjectLiteralExpression(node)) {
|
||||
// @ts-expect-error need to cast `prop` to a more specific type
|
||||
const prop = node.properties.find(prop => prop.name.escapedText === 'body')
|
||||
if (prop != null) {
|
||||
console.log('// needs fix:')
|
||||
console.log(sourceFile?.text.slice(node.pos, node.end))
|
||||
|
||||
// TODO: fix { body: value }
|
||||
// TODO: fix { body: { ... } }
|
||||
// TODO: fix { body }
|
||||
}
|
||||
} else if (ts.isIdentifier(node)) {
|
||||
// @ts-expect-error
|
||||
if (node.flowNode.antecedent?.node != null) {
|
||||
// @ts-expect-error
|
||||
fixBodyProp(sourceFile, node.flowNode.antecedent.node)
|
||||
} else {
|
||||
// console.log('uh oh')
|
||||
// console.log(sourceFile?.text.slice(node.pos, node.end))
|
||||
}
|
||||
} else {
|
||||
// @ts-expect-error
|
||||
if (node.flowNode?.antecedent?.node != null) {
|
||||
// console.log('two')
|
||||
// @ts-expect-error
|
||||
fixBodyProp(sourceFile, node.flowNode.antecedent.node)
|
||||
} else {
|
||||
// console.log('something else')
|
||||
// console.log(node.kind)
|
||||
// console.log(sourceFile?.text.slice(node.pos, node.end))
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function lookForBodyProp(sourceFile: ts.SourceFile, node: ts.CallExpression) {
|
||||
if (node.arguments.length === 0) return
|
||||
const first = node.arguments[0]
|
||||
fixBodyProp(sourceFile, first)
|
||||
}
|
||||
|
||||
// build TS project from provided file names
|
||||
const args = minimist(process.argv.slice(2))
|
||||
const cwd = process.cwd()
|
||||
const files = args._.map(file => path.join(cwd, file))
|
||||
const program = ts.createProgram(files, {})
|
||||
const checker = program.getTypeChecker()
|
||||
|
||||
let processed = 0
|
||||
program.getSourceFiles().forEach(sourceFile => {
|
||||
if (program.isSourceFileFromExternalLibrary(sourceFile)) return
|
||||
const { fileName } = sourceFile
|
||||
|
||||
try {
|
||||
// get all `Client` call expressions
|
||||
const exprs = collectClientCallExpressions(sourceFile)
|
||||
if (exprs.length > 0) {
|
||||
console.log(`found ${exprs.length} Client expressions in ${fileName}`)
|
||||
}
|
||||
// for each call expression, get the first function argument, determine if it's an object and whether it has a `body` key
|
||||
exprs.forEach(expr => lookForBodyProp(sourceFile, expr))
|
||||
} catch (e) {
|
||||
// continue
|
||||
console.error(`Could not process ${fileName}: ${e}`)
|
||||
}
|
||||
processed++
|
||||
})
|
||||
console.log(`Done scanning ${processed} files`)
|
||||
@ -1,143 +0,0 @@
|
||||
/*
|
||||
* Licensed to Elasticsearch B.V. under one or more contributor
|
||||
* license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright
|
||||
* ownership. Elasticsearch B.V. licenses this file to you under
|
||||
* the Apache License, Version 2.0 (the "License"); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
const { join } = require('path')
|
||||
const { readdirSync, writeFileSync, readFileSync } = require('fs')
|
||||
const minimist = require('minimist')
|
||||
const ora = require('ora')
|
||||
const rimraf = require('rimraf')
|
||||
const standard = require('standard')
|
||||
const downloadArtifacts = require('./download-artifacts')
|
||||
const {
|
||||
generate,
|
||||
genFactory,
|
||||
generateDocs,
|
||||
generateRequestTypes
|
||||
} = require('./utils')
|
||||
|
||||
start(minimist(process.argv.slice(2), {
|
||||
string: ['version', 'hash']
|
||||
}))
|
||||
|
||||
function start (opts) {
|
||||
if (opts.version == null) {
|
||||
console.error('Missing version parameter')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const packageFolder = join(__dirname, '..', 'api')
|
||||
const apiOutputFolder = join(packageFolder, 'api')
|
||||
const mainOutputFile = join(packageFolder, 'index.js')
|
||||
const docOutputFile = join(__dirname, '..', 'docs', 'reference.asciidoc')
|
||||
const typeDefFile = join(__dirname, '..', 'index.d.ts')
|
||||
const requestParamsOutputFile = join(packageFolder, 'requestParams.d.ts')
|
||||
|
||||
let log
|
||||
downloadArtifacts({ version: opts.version, hash: opts.hash })
|
||||
.then(onArtifactsDownloaded)
|
||||
.catch(err => {
|
||||
console.log(err)
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
function onArtifactsDownloaded () {
|
||||
log = ora('Generating APIs').start()
|
||||
|
||||
log.text = 'Cleaning API folder...'
|
||||
rimraf.sync(join(apiOutputFolder, '*.js'))
|
||||
|
||||
const allSpec = readdirSync(downloadArtifacts.locations.specFolder)
|
||||
.filter(file => file !== '_common.json')
|
||||
.filter(file => !file.includes('deprecated'))
|
||||
.sort()
|
||||
.map(file => require(join(downloadArtifacts.locations.specFolder, file)))
|
||||
|
||||
const namespaces = namespacify(readdirSync(downloadArtifacts.locations.specFolder))
|
||||
for (const namespace in namespaces) {
|
||||
if (namespace === '_common') continue
|
||||
const code = generate(namespace, namespaces[namespace], downloadArtifacts.locations.specFolder, opts.version)
|
||||
const filePath = join(apiOutputFolder, `${namespace}.js`)
|
||||
writeFileSync(filePath, code, { encoding: 'utf8' })
|
||||
}
|
||||
|
||||
writeFileSync(
|
||||
requestParamsOutputFile,
|
||||
generateRequestTypes(opts.version, allSpec),
|
||||
{ encoding: 'utf8' }
|
||||
)
|
||||
|
||||
const { fn: factory, types } = genFactory(apiOutputFolder, downloadArtifacts.locations.specFolder, namespaces)
|
||||
writeFileSync(
|
||||
mainOutputFile,
|
||||
factory,
|
||||
{ encoding: 'utf8' }
|
||||
)
|
||||
|
||||
const oldTypeDefString = readFileSync(typeDefFile, 'utf8')
|
||||
const start = oldTypeDefString.indexOf('/* GENERATED */')
|
||||
const end = oldTypeDefString.indexOf('/* /GENERATED */')
|
||||
const newTypeDefString = oldTypeDefString.slice(0, start + 15) + '\n' + types + '\n ' + oldTypeDefString.slice(end)
|
||||
writeFileSync(
|
||||
typeDefFile,
|
||||
newTypeDefString,
|
||||
{ encoding: 'utf8' }
|
||||
)
|
||||
|
||||
lintFiles(log, () => {
|
||||
log.text = 'Generating documentation'
|
||||
writeFileSync(
|
||||
docOutputFile,
|
||||
generateDocs(require(join(downloadArtifacts.locations.specFolder, '_common.json')), allSpec),
|
||||
{ encoding: 'utf8' }
|
||||
)
|
||||
|
||||
log.succeed('Done!')
|
||||
})
|
||||
}
|
||||
|
||||
function lintFiles (log, cb) {
|
||||
log.text = 'Linting...'
|
||||
const files = [join(packageFolder, '*.js'), join(apiOutputFolder, '*.js')]
|
||||
standard.lintFiles(files, { fix: true }, err => {
|
||||
if (err) {
|
||||
return log.fail(err.message)
|
||||
}
|
||||
cb()
|
||||
})
|
||||
}
|
||||
|
||||
function namespacify (apis) {
|
||||
return apis
|
||||
.map(api => api.slice(0, -5))
|
||||
.filter(api => api !== '_common')
|
||||
.filter(api => !api.includes('deprecated'))
|
||||
.reduce((acc, val) => {
|
||||
if (val.includes('.')) {
|
||||
val = val.split('.')
|
||||
acc[val[0]] = acc[val[0]] || []
|
||||
acc[val[0]].push(val[1])
|
||||
} else {
|
||||
acc[val] = []
|
||||
}
|
||||
return acc
|
||||
}, {})
|
||||
}
|
||||
}
|
||||
@ -1,8 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
exec docker run \
|
||||
--rm \
|
||||
-e ELASTICSEARCH_URL="http://elasticsearch:9200" \
|
||||
-p 5601:5601 \
|
||||
--network=elastic \
|
||||
docker.elastic.co/kibana/kibana:7.0.0-beta1
|
||||
@ -1,139 +0,0 @@
|
||||
/*
|
||||
* Licensed to Elasticsearch B.V. under one or more contributor
|
||||
* license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright
|
||||
* ownership. Elasticsearch B.V. licenses this file to you under
|
||||
* the Apache License, Version 2.0 (the "License"); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
const { accessSync, mkdirSync } = require('fs')
|
||||
const { join } = require('path')
|
||||
const Git = require('simple-git')
|
||||
|
||||
const esRepo = 'https://github.com/elastic/elasticsearch.git'
|
||||
const esFolder = join(__dirname, '..', '..', 'elasticsearch')
|
||||
const apiFolder = join(esFolder, 'rest-api-spec', 'src', 'main', 'resources', 'rest-api-spec', 'api')
|
||||
const xPackFolder = join(esFolder, 'x-pack', 'plugin', 'src', 'test', 'resources', 'rest-api-spec', 'api')
|
||||
|
||||
function cloneAndCheckout (opts, callback) {
|
||||
const { log, tag, branch } = opts
|
||||
withTag(tag, callback)
|
||||
|
||||
/**
|
||||
* Sets the elasticsearch repository to the given tag.
|
||||
* If the repository is not present in `esFolder` it will
|
||||
* clone the repository and the checkout the tag.
|
||||
* If the repository is already present but it cannot checkout to
|
||||
* the given tag, it will perform a pull and then try again.
|
||||
* @param {string} tag
|
||||
* @param {function} callback
|
||||
*/
|
||||
function withTag (tag, callback) {
|
||||
let fresh = false
|
||||
let retry = 0
|
||||
|
||||
if (!pathExist(esFolder)) {
|
||||
if (!createFolder(esFolder)) {
|
||||
log.fail('Failed folder creation')
|
||||
return
|
||||
}
|
||||
fresh = true
|
||||
}
|
||||
|
||||
const git = Git(esFolder)
|
||||
|
||||
if (fresh) {
|
||||
clone(checkout)
|
||||
} else if (opts.branch) {
|
||||
checkout(true)
|
||||
} else {
|
||||
checkout()
|
||||
}
|
||||
|
||||
function checkout (alsoPull = false) {
|
||||
if (branch) {
|
||||
log.text = `Checking out branch '${branch}'`
|
||||
} else {
|
||||
log.text = `Checking out tag '${tag}'`
|
||||
}
|
||||
git.checkout(branch || tag, err => {
|
||||
if (err) {
|
||||
if (retry++ > 0) {
|
||||
callback(new Error(`Cannot checkout tag '${tag}'`), { apiFolder, xPackFolder })
|
||||
return
|
||||
}
|
||||
return pull(checkout)
|
||||
}
|
||||
if (alsoPull) {
|
||||
return pull(checkout)
|
||||
}
|
||||
callback(null, { apiFolder, xPackFolder })
|
||||
})
|
||||
}
|
||||
|
||||
function pull (cb) {
|
||||
log.text = 'Pulling elasticsearch repository...'
|
||||
git.pull(err => {
|
||||
if (err) {
|
||||
callback(err, { apiFolder, xPackFolder })
|
||||
return
|
||||
}
|
||||
cb()
|
||||
})
|
||||
}
|
||||
|
||||
function clone (cb) {
|
||||
log.text = 'Cloning elasticsearch repository...'
|
||||
git.clone(esRepo, esFolder, err => {
|
||||
if (err) {
|
||||
callback(err, { apiFolder, xPackFolder })
|
||||
return
|
||||
}
|
||||
cb()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given path exists
|
||||
* @param {string} path
|
||||
* @returns {boolean} true if exists, false if not
|
||||
*/
|
||||
function pathExist (path) {
|
||||
try {
|
||||
accessSync(path)
|
||||
return true
|
||||
} catch (err) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the given folder
|
||||
* @param {string} name
|
||||
* @returns {boolean} true on success, false on failure
|
||||
*/
|
||||
function createFolder (name) {
|
||||
try {
|
||||
mkdirSync(name)
|
||||
return true
|
||||
} catch (err) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = cloneAndCheckout
|
||||
@ -1,553 +0,0 @@
|
||||
/*
|
||||
* Licensed to Elasticsearch B.V. under one or more contributor
|
||||
* license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright
|
||||
* ownership. Elasticsearch B.V. licenses this file to you under
|
||||
* the Apache License, Version 2.0 (the "License"); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/* eslint camelcase: 0 */
|
||||
|
||||
'use strict'
|
||||
|
||||
const { join } = require('path')
|
||||
const dedent = require('dedent')
|
||||
const allowedMethods = {
|
||||
noBody: ['GET', 'HEAD', 'DELETE'],
|
||||
body: ['POST', 'PUT', 'DELETE']
|
||||
}
|
||||
|
||||
// if a parameter is depracted in a minor release
|
||||
// we should be able to support it until the next major
|
||||
const deprecatedParameters = require('./patch.json')
|
||||
|
||||
// list of apis that does not need any kind of validation
|
||||
// because of how the url is built or the `type` handling in ES7
|
||||
const noPathValidation = [
|
||||
'create',
|
||||
'exists',
|
||||
'explain',
|
||||
'get',
|
||||
'get_source',
|
||||
'index',
|
||||
'indices.get_alias',
|
||||
'indices.exists_alias',
|
||||
'indices.get_field_mapping',
|
||||
'indices.get_mapping',
|
||||
'indices.get_settings',
|
||||
'indices.put_mapping',
|
||||
'indices.stats',
|
||||
'delete',
|
||||
'nodes.info',
|
||||
'nodes.stats',
|
||||
'nodes.usage',
|
||||
'tasks.cancel',
|
||||
'termvectors',
|
||||
'update'
|
||||
]
|
||||
|
||||
function generateNamespace (namespace, nested, specFolder, version) {
|
||||
const common = require(join(specFolder, '_common.json'))
|
||||
let code = dedent`
|
||||
/*
|
||||
* Licensed to Elasticsearch B.V. under one or more contributor
|
||||
* license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright
|
||||
* ownership. Elasticsearch B.V. licenses this file to you under
|
||||
* the Apache License, Version 2.0 (the "License"); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/* eslint camelcase: 0 */
|
||||
/* eslint no-unused-vars: 0 */
|
||||
|
||||
const { handleError, snakeCaseKeys, normalizeArguments, kConfigurationError } = require('../utils')
|
||||
`
|
||||
if (nested.length > 0) {
|
||||
let getters = ''
|
||||
for (const n of nested) {
|
||||
if (n.includes('_')) {
|
||||
const nameSnaked = n
|
||||
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
|
||||
.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
getters += `${n}: { get () { return this.${nameSnaked} } },\n`
|
||||
}
|
||||
}
|
||||
const api = generateMultiApi(version, namespace, nested, common, specFolder)
|
||||
if (getters.length > 0) {
|
||||
getters = `Object.defineProperties(${api.namespace}Api.prototype, {\n${getters}})`
|
||||
}
|
||||
|
||||
code += `
|
||||
const acceptedQuerystring = ${JSON.stringify(api.acceptedQuerystring)}
|
||||
const snakeCase = ${JSON.stringify(api.snakeCase)}
|
||||
|
||||
function ${api.namespace}Api (transport, ConfigurationError) {
|
||||
this.transport = transport
|
||||
this[kConfigurationError] = ConfigurationError
|
||||
}
|
||||
|
||||
${api.code}
|
||||
|
||||
${getters}
|
||||
|
||||
module.exports = ${api.namespace}Api
|
||||
`
|
||||
} else {
|
||||
const spec = require(join(specFolder, `${namespace}.json`))
|
||||
const api = generateSingleApi(version, spec, common)
|
||||
code += `
|
||||
const acceptedQuerystring = ${JSON.stringify(api.acceptedQuerystring)}
|
||||
const snakeCase = ${JSON.stringify(api.snakeCase)}
|
||||
|
||||
${api.code}
|
||||
|
||||
module.exports = ${api.name}Api
|
||||
`
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
function generateMultiApi (version, namespace, nested, common, specFolder) {
|
||||
const namespaceSnaked = namespace
|
||||
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
|
||||
.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
let code = ''
|
||||
const snakeCase = {}
|
||||
const acceptedQuerystring = []
|
||||
for (const n of nested) {
|
||||
const nameSnaked = n
|
||||
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
|
||||
.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
const spec = require(join(specFolder, `${namespace}.${n}.json`))
|
||||
const api = generateSingleApi(version, spec, common)
|
||||
code += `${Uppercase(namespaceSnaked)}Api.prototype.${nameSnaked} = ${api.code}\n\n`
|
||||
Object.assign(snakeCase, api.snakeCase)
|
||||
for (const q of api.acceptedQuerystring) {
|
||||
if (!acceptedQuerystring.includes(q)) {
|
||||
acceptedQuerystring.push(q)
|
||||
}
|
||||
}
|
||||
}
|
||||
return { code, snakeCase, acceptedQuerystring, namespace: Uppercase(namespaceSnaked) }
|
||||
}
|
||||
|
||||
function generateSingleApi (version, spec, common) {
|
||||
const release = version.charAt(0)
|
||||
const api = Object.keys(spec)[0]
|
||||
const name = api
|
||||
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
|
||||
.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
|
||||
const { paths } = spec[api].url
|
||||
const { params } = spec[api]
|
||||
const acceptedQuerystring = []
|
||||
const required = []
|
||||
|
||||
const methods = paths.reduce((acc, val) => {
|
||||
for (const method of val.methods) {
|
||||
if (!acc.includes(method)) acc.push(method)
|
||||
}
|
||||
return acc
|
||||
}, [])
|
||||
const parts = paths.reduce((acc, val) => {
|
||||
if (!val.parts) return acc
|
||||
for (const part of Object.keys(val.parts)) {
|
||||
if (!acc.includes(part)) acc.push(part)
|
||||
}
|
||||
return acc
|
||||
}, [])
|
||||
|
||||
// get the required parts from the url
|
||||
// if the url has at least one static path,
|
||||
// then there are not required parts of the url
|
||||
let allParts = []
|
||||
for (const path of paths) {
|
||||
if (path.parts) {
|
||||
allParts.push(Object.keys(path.parts))
|
||||
} else {
|
||||
allParts = []
|
||||
break
|
||||
}
|
||||
}
|
||||
if (allParts.length > 0) {
|
||||
intersect(...allParts).forEach(r => required.push(r))
|
||||
}
|
||||
|
||||
for (const key in params) {
|
||||
if (params[key].required) {
|
||||
required.push(key)
|
||||
}
|
||||
|
||||
acceptedQuerystring.push(key)
|
||||
if (deprecatedParameters[release] && deprecatedParameters[release][key]) {
|
||||
acceptedQuerystring.push(deprecatedParameters[release][key])
|
||||
}
|
||||
}
|
||||
|
||||
for (const key in spec[api]) {
|
||||
const k = spec[api][key]
|
||||
if (k && k.required) {
|
||||
required.push(key)
|
||||
}
|
||||
}
|
||||
if (common && common.params) {
|
||||
for (const key in common.params) {
|
||||
acceptedQuerystring.push(key)
|
||||
}
|
||||
}
|
||||
|
||||
const code = `
|
||||
function ${name}Api (params, options, callback) {
|
||||
;[params, options, callback] = normalizeArguments(params, options, callback)
|
||||
|
||||
${genRequiredChecks()}
|
||||
|
||||
${genUrlValidation(paths, api)}
|
||||
|
||||
let { ${genQueryDenylist(false)}, ...querystring } = params
|
||||
querystring = snakeCaseKeys(acceptedQuerystring, snakeCase, querystring)
|
||||
|
||||
let path = ''
|
||||
${buildPath()}
|
||||
|
||||
// build request object
|
||||
const request = {
|
||||
method,
|
||||
path,
|
||||
${genBody(api, methods, spec[api].body, spec)}
|
||||
querystring
|
||||
}
|
||||
|
||||
return this.transport.request(request, options, callback)
|
||||
}
|
||||
`.trim() // always call trim to avoid newlines
|
||||
|
||||
return {
|
||||
name,
|
||||
code,
|
||||
acceptedQuerystring: acceptedQuerystring,
|
||||
snakeCase: genSnakeCaseMap(),
|
||||
documentation: generateDocumentation(spec[api], api)
|
||||
}
|
||||
|
||||
function genRequiredChecks () {
|
||||
const code = required
|
||||
.map(_genRequiredCheck)
|
||||
.concat(_noBody())
|
||||
.filter(Boolean)
|
||||
|
||||
if (code.length) {
|
||||
code.unshift('// check required parameters')
|
||||
}
|
||||
|
||||
return code.join('\n ')
|
||||
|
||||
function _genRequiredCheck (param) {
|
||||
const camelCased = param[0] === '_'
|
||||
? '_' + param.slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
: param.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
|
||||
if (param === camelCased) {
|
||||
const check = `
|
||||
if (params['${param}'] == null) {
|
||||
const err = new this[kConfigurationError]('Missing required parameter: ${param}')
|
||||
return handleError(err, callback)
|
||||
}
|
||||
`
|
||||
return check.trim()
|
||||
} else {
|
||||
const check = `
|
||||
if (params['${param}'] == null && params['${camelCased}'] == null) {
|
||||
const err = new this[kConfigurationError]('Missing required parameter: ${param} or ${camelCased}')
|
||||
return handleError(err, callback)
|
||||
}
|
||||
`
|
||||
return check.trim()
|
||||
}
|
||||
}
|
||||
|
||||
function _noBody () {
|
||||
const check = `
|
||||
if (params.body != null) {
|
||||
const err = new this[kConfigurationError]('This API does not require a body')
|
||||
return handleError(err, callback)
|
||||
}
|
||||
`
|
||||
return spec[api].body === null ? check.trim() : ''
|
||||
}
|
||||
}
|
||||
|
||||
function genSnakeCaseMap () {
|
||||
const toCamelCase = str => {
|
||||
return str[0] === '_'
|
||||
? '_' + str.slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
: str.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
}
|
||||
|
||||
return acceptedQuerystring.reduce((acc, val, index) => {
|
||||
if (toCamelCase(val) !== val) {
|
||||
acc[toCamelCase(val)] = val
|
||||
}
|
||||
return acc
|
||||
}, {})
|
||||
}
|
||||
|
||||
function genQueryDenylist (addQuotes = true) {
|
||||
const toCamelCase = str => {
|
||||
return str[0] === '_'
|
||||
? '_' + str.slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
: str.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
}
|
||||
|
||||
const denylist = ['method', 'body']
|
||||
parts.forEach(p => {
|
||||
const camelStr = toCamelCase(p)
|
||||
if (camelStr !== p) denylist.push(`${camelStr}`)
|
||||
denylist.push(`${p}`)
|
||||
})
|
||||
return addQuotes ? denylist.map(q => `'${q}'`) : denylist
|
||||
}
|
||||
|
||||
function buildPath () {
|
||||
const toCamelCase = str => {
|
||||
return str[0] === '_'
|
||||
? '_' + str.slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
: str.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
}
|
||||
|
||||
const genAccessKey = str => {
|
||||
const camelStr = toCamelCase(str)
|
||||
return camelStr === str
|
||||
? str
|
||||
: `${str} || ${camelStr}`
|
||||
}
|
||||
|
||||
const genCheck = path => {
|
||||
return path
|
||||
.split('/')
|
||||
.filter(Boolean)
|
||||
.map(p => p.startsWith('{') ? `(${genAccessKey(p.slice(1, -1))}) != null` : false)
|
||||
.filter(Boolean)
|
||||
.join(' && ')
|
||||
}
|
||||
|
||||
const genPath = path => {
|
||||
path = path
|
||||
.split('/')
|
||||
.filter(Boolean)
|
||||
.map(p => p.startsWith('{') ? `encodeURIComponent(${genAccessKey(p.slice(1, -1))})` : `'${p}'`)
|
||||
.join(' + \'/\' + ')
|
||||
return path.length > 0 ? ('\'/\' + ' + path) : '\'/\''
|
||||
}
|
||||
|
||||
let hasStaticPath = false
|
||||
let sortedPaths = paths
|
||||
// some legacy API have mutliple statis paths
|
||||
// this filter removes them
|
||||
.filter(p => {
|
||||
if (p.path.includes('{')) return true
|
||||
if (hasStaticPath === false && p.deprecated == null) {
|
||||
hasStaticPath = true
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
// sort by number of parameters (desc)
|
||||
.sort((a, b) => Object.keys(b.parts || {}).length - Object.keys(a.parts || {}).length)
|
||||
|
||||
const allDeprecated = paths.filter(path => path.deprecated != null)
|
||||
if (allDeprecated.length === paths.length) sortedPaths = [paths[0]]
|
||||
|
||||
let code = ''
|
||||
for (let i = 0; i < sortedPaths.length; i++) {
|
||||
const { path, methods } = sortedPaths[i]
|
||||
if (sortedPaths.length === 1) {
|
||||
code += `if (method == null) method = ${generatePickMethod(methods)}
|
||||
path = ${genPath(path)}
|
||||
`
|
||||
} else if (i === 0) {
|
||||
code += `if (${genCheck(path)}) {
|
||||
if (method == null) method = ${generatePickMethod(methods)}
|
||||
path = ${genPath(path)}
|
||||
}
|
||||
`
|
||||
} else if (i === sortedPaths.length - 1) {
|
||||
code += ` else {
|
||||
if (method == null) method = ${generatePickMethod(methods)}
|
||||
path = ${genPath(path)}
|
||||
}
|
||||
`
|
||||
} else {
|
||||
code += ` else if (${genCheck(path)}) {
|
||||
if (method == null) method = ${generatePickMethod(methods)}
|
||||
path = ${genPath(path)}
|
||||
}
|
||||
`
|
||||
}
|
||||
}
|
||||
|
||||
return code
|
||||
}
|
||||
}
|
||||
|
||||
function generatePickMethod (methods) {
|
||||
if (methods.length === 1) {
|
||||
return `'${methods[0]}'`
|
||||
}
|
||||
const bodyMethod = getBodyMethod(methods)
|
||||
const noBodyMethod = getNoBodyMethod(methods)
|
||||
if (bodyMethod && noBodyMethod) {
|
||||
return `body == null ? '${noBodyMethod}' : '${bodyMethod}'`
|
||||
} else if (bodyMethod) {
|
||||
return `'${bodyMethod}'`
|
||||
} else {
|
||||
return `'${noBodyMethod}'`
|
||||
}
|
||||
}
|
||||
|
||||
function genBody (api, methods, body, spec) {
|
||||
const bodyMethod = getBodyMethod(methods)
|
||||
const { content_type } = spec[api].headers
|
||||
if (content_type && content_type.includes('application/x-ndjson')) {
|
||||
return 'bulkBody: body,'
|
||||
}
|
||||
if (body === null && bodyMethod) {
|
||||
return 'body: \'\','
|
||||
} else if (bodyMethod) {
|
||||
return 'body: body || \'\','
|
||||
} else {
|
||||
return 'body: null,'
|
||||
}
|
||||
}
|
||||
|
||||
function getBodyMethod (methods) {
|
||||
const m = methods.filter(m => ~allowedMethods.body.indexOf(m))
|
||||
if (m.length) return m[0]
|
||||
return null
|
||||
}
|
||||
|
||||
function getNoBodyMethod (methods) {
|
||||
const m = methods.filter(m => ~allowedMethods.noBody.indexOf(m))
|
||||
if (m.length) return m[0]
|
||||
return null
|
||||
}
|
||||
|
||||
function genUrlValidation (paths, api) {
|
||||
// this api does not need url validation
|
||||
if (!needsPathValidation(api)) return ''
|
||||
// gets only the dynamic components of the url in an array
|
||||
// then we reverse it. A parameters always require what is
|
||||
// at its right in the array.
|
||||
const chunks = paths
|
||||
.sort((a, b) => Object.keys(a.parts || {}).length > Object.keys(b.parts || {}).length ? -1 : 1)
|
||||
.slice(0, 1)
|
||||
.reduce((acc, val) => val.path, '')
|
||||
// .reduce((a, b) => a.path.split('/').length > b.path.split('/').length ? a.path : b.path)
|
||||
.split('/')
|
||||
.filter(s => s.startsWith('{'))
|
||||
.map(s => s.slice(1, -1))
|
||||
.reverse()
|
||||
|
||||
let code = ''
|
||||
|
||||
const len = chunks.length
|
||||
chunks.forEach((chunk, index) => {
|
||||
if (index === len - 1) return
|
||||
const params = []
|
||||
let camelCased = chunk[0] === '_'
|
||||
? '_' + chunk.slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
: chunk.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
|
||||
if (chunk === camelCased) {
|
||||
code += `${index ? '} else ' : ''}if (params['${chunk}'] != null && (`
|
||||
} else {
|
||||
code += `${index ? '} else ' : ''}if ((params['${chunk}'] != null || params['${camelCased}'] != null) && (`
|
||||
}
|
||||
for (let i = index + 1; i < len; i++) {
|
||||
params.push(chunks[i])
|
||||
// url parts can be declared in camelCase fashion
|
||||
camelCased = chunks[i][0] === '_'
|
||||
? '_' + chunks[i].slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
: chunks[i].replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
|
||||
if (chunks[i] === camelCased) {
|
||||
code += `params['${chunks[i]}'] == null${i === len - 1 ? '' : ' || '}`
|
||||
} else {
|
||||
code += `(params['${chunks[i]}'] == null && params['${camelCased}'] == null)${i === len - 1 ? '' : ' || '}`
|
||||
}
|
||||
}
|
||||
code += `)) {
|
||||
const err = new this[kConfigurationError]('Missing required parameter of the url: ${params.join(', ')}')
|
||||
return handleError(err, callback)
|
||||
`
|
||||
})
|
||||
|
||||
if (chunks.length > 1) {
|
||||
code += '\n}'
|
||||
}
|
||||
|
||||
if (code.length) {
|
||||
code = '// check required url components\n' + code
|
||||
}
|
||||
|
||||
return code.trim()
|
||||
}
|
||||
|
||||
function generateDocumentation ({ documentation }, op) {
|
||||
// we use `replace(/\u00A0/g, ' ')` to remove no breaking spaces
|
||||
// because some parts of the description fields are using it
|
||||
|
||||
if (documentation == null) return ''
|
||||
|
||||
let doc = '/**\n'
|
||||
doc += ` * Perform a ${op} request\n`
|
||||
if (documentation.description) {
|
||||
doc += ` * ${documentation.description.replace(/\u00A0/g, ' ')}\n`
|
||||
}
|
||||
if (documentation.url) {
|
||||
doc += ` * ${documentation.url}\n`
|
||||
}
|
||||
doc += ' */'
|
||||
|
||||
return doc
|
||||
}
|
||||
|
||||
function needsPathValidation (api) {
|
||||
return noPathValidation.indexOf(api) === -1
|
||||
}
|
||||
|
||||
function intersect (first, ...rest) {
|
||||
return rest.reduce((accum, current) => {
|
||||
return accum.filter(x => current.indexOf(x) !== -1)
|
||||
}, first)
|
||||
}
|
||||
|
||||
function Uppercase (str) {
|
||||
return str[0].toUpperCase() + str.slice(1)
|
||||
}
|
||||
|
||||
module.exports = generateNamespace
|
||||
@ -1,318 +0,0 @@
|
||||
/*
|
||||
* Licensed to Elasticsearch B.V. under one or more contributor
|
||||
* license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright
|
||||
* ownership. Elasticsearch B.V. licenses this file to you under
|
||||
* the Apache License, Version 2.0 (the "License"); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
const { readdirSync } = require('fs')
|
||||
const { join } = require('path')
|
||||
const dedent = require('dedent')
|
||||
|
||||
const codeExamples = readdirSync(join(__dirname, '..', '..', 'docs', 'examples'))
|
||||
.map(file => file.slice(0, -9))
|
||||
.filter(api => api !== 'index')
|
||||
|
||||
function generateDocs (common, spec) {
|
||||
let doc = dedent`
|
||||
[[api-reference]]
|
||||
|
||||
////////
|
||||
|
||||
|
||||
|
||||
===========================================================================================================================
|
||||
|| ||
|
||||
|| ||
|
||||
|| ||
|
||||
|| ██████╗ ███████╗ █████╗ ██████╗ ███╗ ███╗███████╗ ||
|
||||
|| ██╔══██╗██╔════╝██╔══██╗██╔══██╗████╗ ████║██╔════╝ ||
|
||||
|| ██████╔╝█████╗ ███████║██║ ██║██╔████╔██║█████╗ ||
|
||||
|| ██╔══██╗██╔══╝ ██╔══██║██║ ██║██║╚██╔╝██║██╔══╝ ||
|
||||
|| ██║ ██║███████╗██║ ██║██████╔╝██║ ╚═╝ ██║███████╗ ||
|
||||
|| ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚══════╝ ||
|
||||
|| ||
|
||||
|| ||
|
||||
|| This file is autogenerated, DO NOT send pull requests that changes this file directly. ||
|
||||
|| You should update the script that does the generation, which can be found in '/scripts/utils/generateDocs.js'. ||
|
||||
|| ||
|
||||
|| You can run the script with the following command: ||
|
||||
|| node scripts/generate --branch <branch_name> ||
|
||||
|| or ||
|
||||
|| node scripts/generate --tag <tag_name> ||
|
||||
|| ||
|
||||
|| ||
|
||||
|| ||
|
||||
===========================================================================================================================
|
||||
|
||||
|
||||
|
||||
////////
|
||||
|
||||
== API Reference
|
||||
|
||||
This document contains the entire list of the Elasticsearch API supported by the client, both OSS and commercial. The client is entirely licensed under Apache 2.0.
|
||||
|
||||
Elasticsearch exposes an HTTP layer to communicate with, and the client is a library that will help you do this. Because of this reason, you will see HTTP related parameters, such as ${'`'}body${'`'} or ${'`'}headers${'`'}.
|
||||
|
||||
Every API can accept two objects, the first contains all the parameters that will be sent to Elasticsearch, while the second includes the request specific parameters, such as timeouts, headers, and so on.
|
||||
In the first object, every parameter but the body will be sent via querystring or url parameter, depending on the API, and every unrecognized parameter will be sent as querystring.
|
||||
|
||||
[source,js]
|
||||
----
|
||||
// promise API
|
||||
const result = await client.search({
|
||||
index: 'my-index',
|
||||
from: 20,
|
||||
size: 10,
|
||||
body: { foo: 'bar' }
|
||||
}, {
|
||||
ignore: [404],
|
||||
maxRetries: 3
|
||||
})
|
||||
|
||||
// callback API
|
||||
client.search({
|
||||
index: 'my-index',
|
||||
from: 20,
|
||||
size: 10,
|
||||
body: { foo: 'bar' }
|
||||
}, {
|
||||
ignore: [404],
|
||||
maxRetries: 3
|
||||
}, (err, result) => {
|
||||
if (err) console.log(err)
|
||||
})
|
||||
----
|
||||
|
||||
In this document, you will find the reference of every parameter accepted by the querystring or the url. If you also need to send the body, you can find the documentation of its format in the reference link that is present along with every endpoint.
|
||||
|
||||
\n\n`
|
||||
doc += commonParameters(common)
|
||||
spec.forEach(s => {
|
||||
doc += '\n' + generateApiDoc(s)
|
||||
})
|
||||
return doc
|
||||
}
|
||||
|
||||
function commonParameters (spec) {
|
||||
let doc = dedent`
|
||||
[discrete]
|
||||
=== Common parameters
|
||||
Parameters that are accepted by all API endpoints.
|
||||
|
||||
link:{ref}/common-options.html[Documentation]
|
||||
[cols=2*]
|
||||
|===\n`
|
||||
Object.keys(spec.params).forEach(key => {
|
||||
const name = isSnakeCased(key) && key !== camelify(key)
|
||||
? '`' + key + '` or `' + camelify(key) + '`'
|
||||
: '`' + key + '`'
|
||||
|
||||
doc += dedent`
|
||||
|${name}
|
||||
|${'`' + spec.params[key].type + '`'} - ${spec.params[key].description}`
|
||||
if (spec.params[key].default) {
|
||||
doc += ` +
|
||||
_Default:_ ${'`' + spec.params[key].default + '`'}`
|
||||
}
|
||||
doc += '\n\n'
|
||||
})
|
||||
|
||||
doc += dedent`
|
||||
|===
|
||||
`
|
||||
return doc
|
||||
}
|
||||
|
||||
function generateApiDoc (spec) {
|
||||
const name = Object.keys(spec)[0]
|
||||
const documentationUrl = spec[name].documentation && spec[name].documentation.url
|
||||
? fixLink(name, spec[name].documentation.url)
|
||||
: ''
|
||||
const params = []
|
||||
// url params
|
||||
const urlParts = spec[name].url.paths.reduce((acc, path) => {
|
||||
if (!path.parts) return acc
|
||||
for (const part in path.parts) {
|
||||
if (acc[part] != null) continue
|
||||
acc[part] = path.parts[part]
|
||||
}
|
||||
return acc
|
||||
}, {})
|
||||
if (urlParts) {
|
||||
Object.keys(urlParts).forEach(param => {
|
||||
params.push({
|
||||
name: param,
|
||||
type: getType(urlParts[param].type, urlParts[param].options),
|
||||
description: urlParts[param].description,
|
||||
default: urlParts[param].default,
|
||||
deprecated: !!urlParts[param].deprecated
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// query params
|
||||
const urlParams = spec[name].params
|
||||
if (urlParams) {
|
||||
Object.keys(urlParams).forEach(param => {
|
||||
const duplicate = params.find(ele => ele.name === param)
|
||||
if (duplicate) return
|
||||
params.push({
|
||||
name: param,
|
||||
type: getType(urlParams[param].type, urlParams[param].options),
|
||||
description: urlParams[param].description,
|
||||
default: urlParams[param].default,
|
||||
deprecated: !!urlParams[param].deprecated
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// body params
|
||||
const body = spec[name].body
|
||||
if (body) {
|
||||
params.push({
|
||||
name: 'body',
|
||||
type: 'object',
|
||||
description: body.description,
|
||||
default: body.default,
|
||||
deprecated: !!body.deprecated
|
||||
})
|
||||
}
|
||||
|
||||
const codeParameters = params
|
||||
.reduce((acc, val) => {
|
||||
const code = `${val.name}: ${val.type},`
|
||||
acc += acc === ''
|
||||
? code
|
||||
: '\n ' + code
|
||||
|
||||
return acc
|
||||
}, '')
|
||||
// remove last comma
|
||||
.slice(0, -1)
|
||||
|
||||
const stability = spec[name].stability === 'stable'
|
||||
? ''
|
||||
: `*Stability:* ${spec[name].stability}`
|
||||
|
||||
let doc = dedent`
|
||||
[discrete]
|
||||
=== ${camelify(name)}
|
||||
${stability}
|
||||
[source,ts]
|
||||
----
|
||||
client.${camelify(name)}(${codeParameters.length > 0 ? `{\n ${codeParameters}\n}` : ''})
|
||||
----\n`
|
||||
if (documentationUrl) {
|
||||
doc += `link:${documentationUrl}[Documentation] +\n`
|
||||
}
|
||||
if (codeExamples.includes(name)) {
|
||||
doc += `{jsclient}/${name.replace(/\./g, '_')}_examples.html[Code Example] +\n`
|
||||
}
|
||||
|
||||
if (params.length !== 0) {
|
||||
doc += dedent`[cols=2*]
|
||||
|===\n`
|
||||
doc += params.reduce((acc, val) => {
|
||||
const name = isSnakeCased(val.name) && val.name !== camelify(val.name)
|
||||
? '`' + val.name + '` or `' + camelify(val.name) + '`'
|
||||
: '`' + val.name + '`'
|
||||
acc += dedent`
|
||||
|${name}
|
||||
|${'`' + val.type.replace(/\|/g, '\\|') + '`'} - ${val.description}`
|
||||
if (val.default) {
|
||||
acc += ` +\n_Default:_ ${'`' + val.default + '`'}`
|
||||
}
|
||||
if (val.deprecated) {
|
||||
acc += ' +\n\nWARNING: This parameter has been deprecated.'
|
||||
}
|
||||
return acc + '\n\n'
|
||||
}, '')
|
||||
|
||||
doc += dedent`
|
||||
|===
|
||||
`
|
||||
}
|
||||
doc += '\n'
|
||||
return doc
|
||||
}
|
||||
|
||||
const LINK_OVERRIDES = {
|
||||
'license.delete': '{ref}/delete-license.html',
|
||||
'license.get': '{ref}/get-license.html',
|
||||
'license.get_basic_status': '{ref}/get-basic-status.html',
|
||||
'license.get_trial_status': '{ref}/get-trial-status.html',
|
||||
'license.post': '{ref}/update-license.html',
|
||||
'license.post_start_basic': '{ref}/start-basic.html',
|
||||
'license.post_start_trial': '{ref}/start-trial.html',
|
||||
'migration.deprecations': '{ref}/migration-api-deprecation.html',
|
||||
'monitoring.bulk': '{ref}/monitor-elasticsearch-cluster.html',
|
||||
'ingest.delete_pipeline': '{ref}/delete-pipeline-api.html',
|
||||
'ingest.get_pipeline': '{ref}/get-pipeline-api.html',
|
||||
'ingest.put_pipeline': '{ref}/put-pipeline-api.html',
|
||||
'ingest.simulate': '{ref}/simulate-pipeline-api.html',
|
||||
'ingest.processor_grok': '{ref}/grok-processor.html#grok-processor-rest-get'
|
||||
}
|
||||
// Fixes bad urls in the JSON spec
|
||||
function fixLink (name, str) {
|
||||
/* In 6.x some API start with `xpack.` when in master they do not. We
|
||||
* can safely ignore that for link generation. */
|
||||
name = name.replace(/^xpack\./, '')
|
||||
const override = LINK_OVERRIDES[name]
|
||||
if (override) return override
|
||||
if (!str) return ''
|
||||
/* Replace references to the guide with the attribute {ref} because
|
||||
* the json files in the Elasticsearch repo are a bit of a mess. */
|
||||
str = str.replace(/^.+guide\/en\/elasticsearch\/reference\/[^/]+\/([^./]*\.html(?:#.+)?)$/, '{ref}/$1')
|
||||
str = str.replace(/frozen\.html/, 'freeze-index-api.html')
|
||||
str = str.replace(/ml-file-structure\.html/, 'ml-find-file-structure.html')
|
||||
str = str.replace(/security-api-get-user-privileges\.html/, 'security-api-get-privileges.html')
|
||||
|
||||
return str
|
||||
}
|
||||
|
||||
function getType (type, options) {
|
||||
switch (type) {
|
||||
case 'list':
|
||||
return 'string | string[]'
|
||||
case 'date':
|
||||
case 'time':
|
||||
case 'timeout':
|
||||
return 'string'
|
||||
case 'enum':
|
||||
return options.map(k => `'${k}'`).join(' | ')
|
||||
case 'int':
|
||||
case 'double':
|
||||
case 'long':
|
||||
return 'number'
|
||||
default:
|
||||
return type
|
||||
}
|
||||
}
|
||||
|
||||
function camelify (str) {
|
||||
return str[0] === '_'
|
||||
? '_' + str.slice(1).replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
: str.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
}
|
||||
|
||||
function isSnakeCased (str) {
|
||||
return !!~str.indexOf('_')
|
||||
}
|
||||
|
||||
module.exports = generateDocs
|
||||
@ -1,299 +0,0 @@
|
||||
/*
|
||||
* Licensed to Elasticsearch B.V. under one or more contributor
|
||||
* license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright
|
||||
* ownership. Elasticsearch B.V. licenses this file to you under
|
||||
* the Apache License, Version 2.0 (the "License"); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/* eslint-disable no-template-curly-in-string */
|
||||
/* eslint camelcase: 0 */
|
||||
|
||||
'use strict'
|
||||
|
||||
const { readdirSync } = require('fs')
|
||||
const { join } = require('path')
|
||||
const dedent = require('dedent')
|
||||
const deepmerge = require('deepmerge')
|
||||
|
||||
function genFactory (folder, specFolder, namespaces) {
|
||||
// get all the API files
|
||||
// const apiFiles = readdirSync(folder)
|
||||
const apiFiles = readdirSync(specFolder)
|
||||
.filter(file => file !== '_common.json')
|
||||
.filter(file => !file.includes('deprecated'))
|
||||
.sort()
|
||||
const types = apiFiles
|
||||
.map(file => {
|
||||
const name = file
|
||||
.slice(0, -5)
|
||||
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
|
||||
.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
|
||||
return file
|
||||
.slice(0, -5) // remove `.json` extension
|
||||
.split('.')
|
||||
.reverse()
|
||||
.reduce((acc, val) => {
|
||||
const spec = readSpec(specFolder, file.slice(0, -5))
|
||||
const isHead = isHeadMethod(spec, file.slice(0, -5))
|
||||
const body = hasBody(spec, file.slice(0, -5))
|
||||
const methods = acc === null ? buildMethodDefinition({ kibana: false }, val, name, body, isHead, spec) : null
|
||||
const obj = {}
|
||||
if (methods) {
|
||||
for (const m of methods) {
|
||||
obj[m.key] = m.val
|
||||
}
|
||||
} else {
|
||||
obj[val] = acc
|
||||
if (isSnakeCased(val)) {
|
||||
obj[camelify(val)] = acc
|
||||
}
|
||||
}
|
||||
return obj
|
||||
}, null)
|
||||
})
|
||||
.reduce((acc, val) => deepmerge(acc, val), {})
|
||||
|
||||
const kibanaTypes = apiFiles
|
||||
.map(file => {
|
||||
const name = file
|
||||
.slice(0, -5)
|
||||
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
|
||||
.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
|
||||
return file
|
||||
.slice(0, -5) // remove `.json` extension
|
||||
.split('.')
|
||||
.reverse()
|
||||
.reduce((acc, val) => {
|
||||
const spec = readSpec(specFolder, file.slice(0, -5))
|
||||
const isHead = isHeadMethod(spec, file.slice(0, -5))
|
||||
const body = hasBody(spec, file.slice(0, -5))
|
||||
const methods = acc === null ? buildMethodDefinition({ kibana: true }, val, name, body, isHead, spec) : null
|
||||
const obj = {}
|
||||
if (methods) {
|
||||
for (const m of methods) {
|
||||
obj[m.key] = m.val
|
||||
}
|
||||
} else {
|
||||
obj[camelify(val)] = acc
|
||||
}
|
||||
return obj
|
||||
}, null)
|
||||
})
|
||||
.reduce((acc, val) => deepmerge(acc, val), {})
|
||||
|
||||
// serialize the type object
|
||||
const typesStr = Object.keys(types)
|
||||
.map(key => {
|
||||
const line = ` ${key}: ${JSON.stringify(types[key], null, 4)}`
|
||||
if (line.slice(-1) === '}') {
|
||||
return line.slice(0, -1) + ' }'
|
||||
}
|
||||
return line
|
||||
})
|
||||
.join('\n')
|
||||
// remove useless quotes and commas
|
||||
.replace(/"/g, '')
|
||||
.replace(/,$/gm, '')
|
||||
const kibanaTypesStr = Object.keys(kibanaTypes)
|
||||
.map(key => {
|
||||
const line = ` ${key}: ${JSON.stringify(kibanaTypes[key], null, 4)}`
|
||||
if (line.slice(-1) === '}') {
|
||||
return line.slice(0, -1) + ' }'
|
||||
}
|
||||
return line
|
||||
})
|
||||
.join('\n')
|
||||
// remove useless quotes and commas
|
||||
.replace(/"/g, '')
|
||||
.replace(/,$/gm, '')
|
||||
|
||||
let apisStr = ''
|
||||
const getters = []
|
||||
for (const namespace in namespaces) {
|
||||
if (namespaces[namespace].length > 0) {
|
||||
getters.push(`${camelify(namespace)}: {
|
||||
get () {
|
||||
if (this[k${toPascalCase(camelify(namespace))}] === null) {
|
||||
this[k${toPascalCase(camelify(namespace))}] = new ${toPascalCase(camelify(namespace))}Api(this.transport, this[kConfigurationError])
|
||||
}
|
||||
return this[k${toPascalCase(camelify(namespace))}]
|
||||
}
|
||||
},\n`)
|
||||
if (namespace.includes('_')) {
|
||||
getters.push(`${namespace}: { get () { return this.${camelify(namespace)} } },\n`)
|
||||
}
|
||||
} else {
|
||||
apisStr += `ESAPI.prototype.${camelify(namespace)} = ${camelify(namespace)}Api\n`
|
||||
if (namespace.includes('_')) {
|
||||
getters.push(`${namespace}: { get () { return this.${camelify(namespace)} } },\n`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
apisStr += '\nObject.defineProperties(ESAPI.prototype, {\n'
|
||||
for (const getter of getters) {
|
||||
apisStr += getter
|
||||
}
|
||||
apisStr += '})'
|
||||
|
||||
let modules = ''
|
||||
let symbols = ''
|
||||
let symbolsInstance = ''
|
||||
for (const namespace in namespaces) {
|
||||
if (namespaces[namespace].length > 0) {
|
||||
modules += `const ${toPascalCase(camelify(namespace))}Api = require('./api/${namespace}')\n`
|
||||
symbols += `const k${toPascalCase(camelify(namespace))} = Symbol('${toPascalCase(camelify(namespace))}')\n`
|
||||
symbolsInstance += `this[k${toPascalCase(camelify(namespace))}] = null\n`
|
||||
} else {
|
||||
modules += `const ${camelify(namespace)}Api = require('./api/${namespace}')\n`
|
||||
}
|
||||
}
|
||||
|
||||
const fn = dedent`
|
||||
/*
|
||||
* Licensed to Elasticsearch B.V. under one or more contributor
|
||||
* license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright
|
||||
* ownership. Elasticsearch B.V. licenses this file to you under
|
||||
* the Apache License, Version 2.0 (the "License"); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
${modules}
|
||||
|
||||
const { kConfigurationError } = require('./utils')
|
||||
${symbols}
|
||||
|
||||
function ESAPI (opts) {
|
||||
this[kConfigurationError] = opts.ConfigurationError
|
||||
${symbolsInstance}
|
||||
}
|
||||
|
||||
${apisStr}
|
||||
|
||||
module.exports = ESAPI
|
||||
`
|
||||
|
||||
// new line at the end of file
|
||||
return { fn: fn + '\n', types: typesStr, kibanaTypes: kibanaTypesStr }
|
||||
}
|
||||
|
||||
// from snake_case to camelCase
|
||||
function camelify (str) {
|
||||
return str.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
}
|
||||
|
||||
function isSnakeCased (str) {
|
||||
return !!~str.indexOf('_')
|
||||
}
|
||||
|
||||
function toPascalCase (str) {
|
||||
return str[0].toUpperCase() + str.slice(1)
|
||||
}
|
||||
|
||||
function buildMethodDefinition (opts, api, name, hasBody, isHead, spec) {
|
||||
const Name = toPascalCase(name)
|
||||
const { content_type } = spec[Object.keys(spec)[0]].headers
|
||||
const bodyType = content_type && content_type.includes('application/x-ndjson') ? 'RequestNDBody' : 'RequestBody'
|
||||
const responseType = isHead ? 'boolean' : 'Record<string, any>'
|
||||
const defaultBodyType = content_type && content_type.includes('application/x-ndjson') ? 'Record<string, any>[]' : 'Record<string, any>'
|
||||
|
||||
if (opts.kibana) {
|
||||
if (hasBody) {
|
||||
return [
|
||||
{ key: `${camelify(api)}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params?: RequestParams.${Name}<TRequestBody>, options?: TransportRequestOptions)`, val: 'TransportRequestPromise<ApiResponse<TResponse, TContext>>' }
|
||||
]
|
||||
} else {
|
||||
return [
|
||||
{ key: `${camelify(api)}<TResponse = ${responseType}, TContext = Context>(params?: RequestParams.${Name}, options?: TransportRequestOptions)`, val: 'TransportRequestPromise<ApiResponse<TResponse, TContext>>' }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
if (hasBody) {
|
||||
let methods = [
|
||||
{ key: `${api}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params?: RequestParams.${Name}<TRequestBody>, options?: TransportRequestOptions)`, val: 'TransportRequestPromise<ApiResponse<TResponse, TContext>>' },
|
||||
{ key: `${api}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
|
||||
{ key: `${api}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params: RequestParams.${Name}<TRequestBody>, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
|
||||
{ key: `${api}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params: RequestParams.${Name}<TRequestBody>, options: TransportRequestOptions, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' }
|
||||
]
|
||||
if (isSnakeCased(api)) {
|
||||
methods = methods.concat([
|
||||
{ key: `${camelify(api)}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params?: RequestParams.${Name}<TRequestBody>, options?: TransportRequestOptions)`, val: 'TransportRequestPromise<ApiResponse<TResponse, TContext>>' },
|
||||
{ key: `${camelify(api)}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
|
||||
{ key: `${camelify(api)}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params: RequestParams.${Name}<TRequestBody>, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
|
||||
{ key: `${camelify(api)}<TResponse = ${responseType}, TRequestBody extends ${bodyType} = ${defaultBodyType}, TContext = Context>(params: RequestParams.${Name}<TRequestBody>, options: TransportRequestOptions, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' }
|
||||
])
|
||||
}
|
||||
return methods
|
||||
} else {
|
||||
let methods = [
|
||||
{ key: `${api}<TResponse = ${responseType}, TContext = Context>(params?: RequestParams.${Name}, options?: TransportRequestOptions)`, val: 'TransportRequestPromise<ApiResponse<TResponse, TContext>>' },
|
||||
{ key: `${api}<TResponse = ${responseType}, TContext = Context>(callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
|
||||
{ key: `${api}<TResponse = ${responseType}, TContext = Context>(params: RequestParams.${Name}, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
|
||||
{ key: `${api}<TResponse = ${responseType}, TContext = Context>(params: RequestParams.${Name}, options: TransportRequestOptions, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' }
|
||||
]
|
||||
if (isSnakeCased(api)) {
|
||||
methods = methods.concat([
|
||||
{ key: `${camelify(api)}<TResponse = ${responseType}, TContext = Context>(params?: RequestParams.${Name}, options?: TransportRequestOptions)`, val: 'TransportRequestPromise<ApiResponse<TResponse, TContext>>' },
|
||||
{ key: `${camelify(api)}<TResponse = ${responseType}, TContext = Context>(callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
|
||||
{ key: `${camelify(api)}<TResponse = ${responseType}, TContext = Context>(params: RequestParams.${Name}, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' },
|
||||
{ key: `${camelify(api)}<TResponse = ${responseType}, TContext = Context>(params: RequestParams.${Name}, options: TransportRequestOptions, callback: callbackFn<TResponse, TContext>)`, val: 'TransportRequestCallback' }
|
||||
])
|
||||
}
|
||||
return methods
|
||||
}
|
||||
}
|
||||
|
||||
function hasBody (spec, api) {
|
||||
return !!spec[api].body
|
||||
}
|
||||
|
||||
function isHeadMethod (spec, api) {
|
||||
const { paths } = spec[api].url
|
||||
const methods = []
|
||||
for (const path of paths) {
|
||||
for (const method of path.methods) {
|
||||
if (!methods.includes(method)) {
|
||||
methods.push(method)
|
||||
}
|
||||
}
|
||||
}
|
||||
return methods.length === 1 && methods[0] === 'HEAD'
|
||||
}
|
||||
|
||||
function readSpec (specFolder, file) {
|
||||
try {
|
||||
return require(join(specFolder, file))
|
||||
} catch (err) {
|
||||
throw new Error(`Cannot read spec file ${file}`)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = genFactory
|
||||
@ -1,191 +0,0 @@
|
||||
/*
|
||||
* Licensed to Elasticsearch B.V. under one or more contributor
|
||||
* license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright
|
||||
* ownership. Elasticsearch B.V. licenses this file to you under
|
||||
* the Apache License, Version 2.0 (the "License"); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/* eslint camelcase: 0 */
|
||||
|
||||
'use strict'
|
||||
|
||||
const deprecatedParameters = require('./patch.json')
|
||||
|
||||
function generate (version, api) {
|
||||
const release = version.charAt(0)
|
||||
let types = `/*
|
||||
* Licensed to Elasticsearch B.V. under one or more contributor
|
||||
* license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright
|
||||
* ownership. Elasticsearch B.V. licenses this file to you under
|
||||
* the Apache License, Version 2.0 (the "License"); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
import { RequestBody, RequestNDBody } from '../lib/Transport'
|
||||
|
||||
export interface Generic {
|
||||
method?: string;
|
||||
filter_path?: string | string[];
|
||||
pretty?: boolean;
|
||||
human?: boolean;
|
||||
error_trace?: boolean;
|
||||
source?: string;
|
||||
}
|
||||
`
|
||||
|
||||
api.forEach(generateRequestType)
|
||||
return types
|
||||
|
||||
function generateRequestType (spec) {
|
||||
const api = Object.keys(spec)[0]
|
||||
const name = api
|
||||
.replace(/\.([a-z])/g, k => k[1].toUpperCase())
|
||||
.replace(/_([a-z])/g, k => k[1].toUpperCase())
|
||||
|
||||
const { paths = {} } = spec[api].url
|
||||
const { body, params = {} } = spec[api]
|
||||
|
||||
// get the required parts from the url
|
||||
// if the url has at least one static path,
|
||||
// then there are not required parts of the url
|
||||
let allParts = []
|
||||
let requiredParts = []
|
||||
for (const path of paths) {
|
||||
if (path.parts) {
|
||||
allParts.push(Object.keys(path.parts))
|
||||
} else {
|
||||
allParts = []
|
||||
break
|
||||
}
|
||||
}
|
||||
if (allParts.length > 0) {
|
||||
requiredParts = intersect(...allParts)
|
||||
}
|
||||
|
||||
const parts = paths.reduce((acc, path) => {
|
||||
if (!path.parts) return acc
|
||||
for (const part in path.parts) {
|
||||
if (acc[part] != null) continue
|
||||
acc[part] = { key: part, value: path.parts[part], required: requiredParts.includes(part) }
|
||||
}
|
||||
return acc
|
||||
}, {})
|
||||
const deprecatedParametersToAdd = []
|
||||
const paramsArr = Object.keys(params)
|
||||
.filter(k => !Object.keys(parts).includes(k))
|
||||
.map(k => {
|
||||
if (deprecatedParameters[release] && deprecatedParameters[release][k]) {
|
||||
deprecatedParametersToAdd.push({
|
||||
key: deprecatedParameters[release][k],
|
||||
value: params[k],
|
||||
required: params[k].required
|
||||
})
|
||||
}
|
||||
return { key: k, value: params[k], required: params[k].required }
|
||||
})
|
||||
|
||||
const partsArr = Object.keys(parts).map(k => parts[k])
|
||||
deprecatedParametersToAdd.forEach(k => partsArr.push(k))
|
||||
|
||||
const genLine = e => {
|
||||
const optional = e.required ? '' : '?'
|
||||
return `${e.key}${optional}: ${getType(e.value.type, e.value.options)};`
|
||||
}
|
||||
|
||||
const { content_type } = spec[api].headers
|
||||
const bodyGeneric = content_type && content_type.includes('application/x-ndjson') ? 'RequestNDBody' : 'RequestBody'
|
||||
|
||||
const code = `
|
||||
export interface ${toPascalCase(name)}${body ? `<T = ${bodyGeneric}>` : ''} extends Generic {
|
||||
${partsArr.map(genLine).join('\n ')}
|
||||
${paramsArr.map(genLine).join('\n ')}
|
||||
${body ? `body${body.required ? '' : '?'}: T;` : ''}
|
||||
}
|
||||
`
|
||||
|
||||
types += '\n'
|
||||
// remove empty lines
|
||||
types += code.replace(/^\s*\n/gm, '')
|
||||
}
|
||||
|
||||
function getType (type, options) {
|
||||
switch (type) {
|
||||
case 'list':
|
||||
return 'string | string[]'
|
||||
case 'date':
|
||||
case 'time':
|
||||
case 'timeout':
|
||||
return 'string'
|
||||
case 'enum': {
|
||||
// the following code changes 'true' | 'false' to boolean
|
||||
let foundTrue = false
|
||||
let foundFalse = false
|
||||
options = options
|
||||
.map(k => {
|
||||
if (k === 'true') {
|
||||
foundTrue = true
|
||||
return true
|
||||
} else if (k === 'false') {
|
||||
foundFalse = true
|
||||
return false
|
||||
} else {
|
||||
return `'${k}'`
|
||||
}
|
||||
})
|
||||
.filter(k => {
|
||||
if (foundTrue && foundFalse && (k === true || k === false)) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
if (foundTrue && foundFalse) {
|
||||
options.push('boolean')
|
||||
}
|
||||
return options.join(' | ')
|
||||
}
|
||||
case 'int':
|
||||
case 'double':
|
||||
case 'long':
|
||||
return 'number'
|
||||
case 'boolean|long':
|
||||
return 'boolean | number'
|
||||
default:
|
||||
return type
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function intersect (first, ...rest) {
|
||||
return rest.reduce((accum, current) => {
|
||||
return accum.filter(x => current.indexOf(x) !== -1)
|
||||
}, first)
|
||||
}
|
||||
|
||||
function toPascalCase (str) {
|
||||
return str[0].toUpperCase() + str.slice(1)
|
||||
}
|
||||
|
||||
module.exports = generate
|
||||
@ -1,34 +0,0 @@
|
||||
/*
|
||||
* Licensed to Elasticsearch B.V. under one or more contributor
|
||||
* license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright
|
||||
* ownership. Elasticsearch B.V. licenses this file to you under
|
||||
* the Apache License, Version 2.0 (the "License"); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
const generate = require('./generateApis')
|
||||
const cloneAndCheckout = require('./clone-es')
|
||||
const genFactory = require('./generateMain')
|
||||
const generateDocs = require('./generateDocs')
|
||||
const generateRequestTypes = require('./generateRequestTypes')
|
||||
|
||||
module.exports = {
|
||||
generate,
|
||||
cloneAndCheckout,
|
||||
genFactory,
|
||||
generateDocs,
|
||||
generateRequestTypes
|
||||
}
|
||||
@ -1,14 +0,0 @@
|
||||
{
|
||||
"6": {
|
||||
"_source_includes": "_source_include",
|
||||
"_source_excludes": "_source_exclude"
|
||||
},
|
||||
"7": {
|
||||
"_source_includes": "_source_include",
|
||||
"_source_excludes": "_source_exclude"
|
||||
},
|
||||
"8": {
|
||||
"_source_includes": "_source_include",
|
||||
"_source_excludes": "_source_exclude"
|
||||
}
|
||||
}
|
||||
@ -1,21 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
TEST_ES_SERVER=${TEST_ES_SERVER:-"http://localhost:9200"}
|
||||
|
||||
attempt_counter=0
|
||||
max_attempts=5
|
||||
url="${TEST_ES_SERVER}/_cluster/health?wait_for_status=green&timeout=50s"
|
||||
|
||||
echo "Waiting for Elasticsearch..."
|
||||
while [[ "$(curl -s -o /dev/null -w ''%{http_code}'' --max-time 55 "$url")" != "200" ]]; do
|
||||
if [ ${attempt_counter} -eq ${max_attempts} ];then
|
||||
echo "\nCouldn't connect to Elasticsearch"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf '.'
|
||||
attempt_counter=$(($attempt_counter+1))
|
||||
sleep 5
|
||||
done
|
||||
|
||||
echo "\nReady"
|
||||
@ -44,7 +44,7 @@ export default class Cluster {
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides explanations for shard allocations in the cluster.
|
||||
* Explain the shard allocations. Get explanations for shard allocations in the cluster. For unassigned shards, it provides an explanation for why the shard is unassigned. For assigned shards, it provides an explanation for why the shard is remaining on its current node and has not moved or rebalanced to another node. This API can be very useful when attempting to diagnose why a shard is unassigned or why a shard continues to remain on its current node when you might expect otherwise.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-allocation-explain.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async allocationExplain (this: That, params?: T.ClusterAllocationExplainRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterAllocationExplainResponse>
|
||||
@ -110,7 +110,7 @@ export default class Cluster {
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears cluster voting config exclusions.
|
||||
* Clear cluster voting config exclusions. Remove master-eligible nodes from the voting configuration exclusion list.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/voting-config-exclusions.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async deleteVotingConfigExclusions (this: That, params?: T.ClusterDeleteVotingConfigExclusionsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterDeleteVotingConfigExclusionsResponse>
|
||||
@ -212,7 +212,7 @@ export default class Cluster {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns cluster-wide settings. By default, it returns only settings that have been explicitly defined.
|
||||
* Get cluster-wide settings. By default, it returns only settings that have been explicitly defined.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-get-settings.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async getSettings (this: That, params?: T.ClusterGetSettingsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterGetSettingsResponse>
|
||||
@ -242,7 +242,7 @@ export default class Cluster {
|
||||
}
|
||||
|
||||
/**
|
||||
* The cluster health API returns a simple status on the health of the cluster. You can also use the API to get the health status of only specified data streams and indices. For data streams, the API retrieves the health status of the stream’s backing indices. The cluster health status is: green, yellow or red. On the shard level, a red status indicates that the specific shard is not allocated in the cluster, yellow means that the primary shard is allocated but replicas are not, and green means that all shards are allocated. The index level status is controlled by the worst shard status. The cluster status is controlled by the worst index status.
|
||||
* Get the cluster health status. You can also use the API to get the health status of only specified data streams and indices. For data streams, the API retrieves the health status of the stream’s backing indices. The cluster health status is: green, yellow or red. On the shard level, a red status indicates that the specific shard is not allocated in the cluster. Yellow means that the primary shard is allocated but replicas are not. Green means that all shards are allocated. The index level status is controlled by the worst shard status. One of the main benefits of the API is the ability to wait until the cluster reaches a certain high watermark health level. The cluster status is controlled by the worst index status.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-health.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async health (this: That, params?: T.ClusterHealthRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterHealthResponse>
|
||||
@ -314,7 +314,7 @@ export default class Cluster {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns cluster-level changes (such as create index, update mapping, allocate or fail shard) that have not yet been executed. NOTE: This API returns a list of any pending updates to the cluster state. These are distinct from the tasks reported by the Task Management API which include periodic tasks and tasks initiated by the user, such as node stats, search queries, or create index requests. However, if a user-initiated task such as a create index command causes a cluster state update, the activity of this task might be reported by both task api and pending cluster tasks API.
|
||||
* Get the pending cluster tasks. Get information about cluster-level changes (such as create index, update mapping, allocate or fail shard) that have not yet taken effect. NOTE: This API returns a list of any pending updates to the cluster state. These are distinct from the tasks reported by the task management API which include periodic tasks and tasks initiated by the user, such as node stats, search queries, or create index requests. However, if a user-initiated task such as a create index command causes a cluster state update, the activity of this task might be reported by both task api and pending cluster tasks API.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-pending.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async pendingTasks (this: That, params?: T.ClusterPendingTasksRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterPendingTasksResponse>
|
||||
@ -344,7 +344,7 @@ export default class Cluster {
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the cluster voting config exclusions by node ids or node names.
|
||||
* Update voting configuration exclusions. Update the cluster voting config exclusions by node IDs or node names. By default, if there are more than three master-eligible nodes in the cluster and you remove fewer than half of the master-eligible nodes in the cluster at once, the voting configuration automatically shrinks. If you want to shrink the voting configuration to contain fewer than three nodes or to remove half or more of the master-eligible nodes in the cluster at once, use this API to remove departing nodes from the voting configuration manually. The API adds an entry for each specified node to the cluster’s voting configuration exclusions list. It then waits until the cluster has reconfigured its voting configuration to exclude the specified nodes. Clusters should have no voting configuration exclusions in normal operation. Once the excluded nodes have stopped, clear the voting configuration exclusions with `DELETE /_cluster/voting_config_exclusions`. This API waits for the nodes to be fully removed from the cluster before it returns. If your cluster has voting configuration exclusions for nodes that you no longer intend to remove, use `DELETE /_cluster/voting_config_exclusions?wait_for_removal=false` to clear the voting configuration exclusions without waiting for the nodes to leave the cluster. A response to `POST /_cluster/voting_config_exclusions` with an HTTP status code of 200 OK guarantees that the node has been removed from the voting configuration and will not be reinstated until the voting configuration exclusions are cleared by calling `DELETE /_cluster/voting_config_exclusions`. If the call to `POST /_cluster/voting_config_exclusions` fails or returns a response with an HTTP status code other than 200 OK then the node may not have been removed from the voting configuration. In that case, you may safely retry the call. NOTE: Voting exclusions are required only when you remove at least half of the master-eligible nodes from a cluster in a short time period. They are not required when removing master-ineligible nodes or when removing fewer than half of the master-eligible nodes.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/voting-config-exclusions.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async postVotingConfigExclusions (this: That, params?: T.ClusterPostVotingConfigExclusionsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterPostVotingConfigExclusionsResponse>
|
||||
@ -410,7 +410,7 @@ export default class Cluster {
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the cluster settings.
|
||||
* Update the cluster settings. Configure and update dynamic settings on a running cluster. You can also configure dynamic settings locally on an unstarted or shut down node in `elasticsearch.yml`. Updates made with this API can be persistent, which apply across cluster restarts, or transient, which reset after a cluster restart. You can also reset transient or persistent settings by assigning them a null value. If you configure the same setting using multiple methods, Elasticsearch applies the settings in following order of precedence: 1) Transient setting; 2) Persistent setting; 3) `elasticsearch.yml` setting; 4) Default setting value. For example, you can apply a transient setting to override a persistent setting or `elasticsearch.yml` setting. However, a change to an `elasticsearch.yml` setting will not override a defined transient or persistent setting. TIP: In Elastic Cloud, use the user settings feature to configure all cluster settings. This method automatically rejects unsafe settings that could break your cluster. If you run Elasticsearch on your own hardware, use this API to configure dynamic cluster settings. Only use `elasticsearch.yml` for static cluster settings and node settings. The API doesn’t require a restart and ensures a setting’s value is the same on all nodes. WARNING: Transient cluster settings are no longer recommended. Use persistent cluster settings instead. If a cluster becomes unstable, transient settings can clear unexpectedly, resulting in a potentially undesired cluster configuration.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-update-settings.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async putSettings (this: That, params?: T.ClusterPutSettingsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterPutSettingsResponse>
|
||||
@ -444,7 +444,7 @@ export default class Cluster {
|
||||
}
|
||||
|
||||
/**
|
||||
* The cluster remote info API allows you to retrieve all of the configured remote cluster information. It returns connection and endpoint information keyed by the configured remote cluster alias.
|
||||
* Get remote cluster information. Get all of the configured remote cluster information. This API returns connection and endpoint information keyed by the configured remote cluster alias.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-remote-info.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async remoteInfo (this: That, params?: T.ClusterRemoteInfoRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterRemoteInfoResponse>
|
||||
@ -474,7 +474,7 @@ export default class Cluster {
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows to manually change the allocation of individual shards in the cluster.
|
||||
* Reroute the cluster. Manually change the allocation of individual shards in the cluster. For example, a shard can be moved from one node to another explicitly, an allocation can be canceled, and an unassigned shard can be explicitly allocated to a specific node. It is important to note that after processing any reroute commands Elasticsearch will perform rebalancing as normal (respecting the values of settings such as `cluster.routing.rebalance.enable`) in order to remain in a balanced state. For example, if the requested allocation includes moving a shard from node1 to node2 then this may cause a shard to be moved from node2 back to node1 to even things out. The cluster can be set to disable allocations using the `cluster.routing.allocation.enable` setting. If allocations are disabled then the only allocations that will be performed are explicit ones given using the reroute command, and consequent allocations due to rebalancing. The cluster will attempt to allocate a shard a maximum of `index.allocation.max_retries` times in a row (defaults to `5`), before giving up and leaving the shard unallocated. This scenario can be caused by structural problems such as having an analyzer which refers to a stopwords file which doesn’t exist on all nodes. Once the problem has been corrected, allocation can be manually retried by calling the reroute API with the `?retry_failed` URI query parameter, which will attempt a single retry round for these shards.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-reroute.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async reroute (this: That, params?: T.ClusterRerouteRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterRerouteResponse>
|
||||
@ -508,7 +508,7 @@ export default class Cluster {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a comprehensive information about the state of the cluster.
|
||||
* Get the cluster state. Get comprehensive information about the state of the cluster. The cluster state is an internal data structure which keeps track of a variety of information needed by every node, including the identity and attributes of the other nodes in the cluster; cluster-wide settings; index metadata, including the mapping and settings for each index; the location and status of every shard copy in the cluster. The elected master node ensures that every node in the cluster has a copy of the same cluster state. This API lets you retrieve a representation of this internal state for debugging or diagnostic purposes. You may need to consult the Elasticsearch source code to determine the precise meaning of the response. By default the API will route requests to the elected master node since this node is the authoritative source of cluster states. You can also retrieve the cluster state held on the node handling the API request by adding the `?local=true` query parameter. Elasticsearch may need to expend significant effort to compute a response to this API in larger clusters, and the response may comprise a very large quantity of data. If you use this API repeatedly, your cluster may become unstable. WARNING: The response is a representation of an internal data structure. Its format is not subject to the same compatibility guarantees as other more stable APIs and may change from version to version. Do not query this API using external monitoring tools. Instead, obtain the information you require using other more stable cluster APIs.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-state.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async state (this: That, params?: T.ClusterStateRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterStateResponse>
|
||||
@ -552,7 +552,7 @@ export default class Cluster {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns cluster statistics. It returns basic index metrics (shard numbers, store size, memory usage) and information about the current nodes that form the cluster (number, roles, os, jvm versions, memory usage, cpu and installed plugins).
|
||||
* Get cluster statistics. Get basic index metrics (shard numbers, store size, memory usage) and information about the current nodes that form the cluster (number, roles, os, jvm versions, memory usage, cpu and installed plugins).
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-stats.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async stats (this: That, params?: T.ClusterStatsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.ClusterStatsResponse>
|
||||
|
||||
@ -38,7 +38,7 @@ import * as T from '../types'
|
||||
interface That { transport: Transport }
|
||||
|
||||
/**
|
||||
* Returns the health of the cluster.
|
||||
* Get the cluster health. Get a report with the health status of an Elasticsearch cluster. The report contains a list of indicators that compose Elasticsearch functionality. Each indicator has a health status of: green, unknown, yellow or red. The indicator will provide an explanation and metadata describing the reason for its current health status. The cluster’s status is controlled by the worst indicator status. In the event that an indicator’s status is non-green, a list of impacts may be present in the indicator result which detail the functionalities that are negatively affected by the health issue. Each impact carries with it a severity level, an area of the system that is affected, and a simple description of the impact on the system. Some health indicators can determine the root cause of a health problem and prescribe a set of steps that can be performed in order to improve the health of the system. The root cause and remediation steps are encapsulated in a diagnosis. A diagnosis contains a cause detailing a root cause analysis, an action containing a brief description of the steps to take to fix the problem, the list of affected resources (if applicable), and a detailed step-by-step troubleshooting guide to fix the diagnosed problem. NOTE: The health indicators perform root cause analysis of non-green health statuses. This can be computationally expensive when called frequently. When setting up automated polling of the API for health status, set verbose to false to disable the more expensive analysis logic.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/health-api.html | Elasticsearch API documentation}
|
||||
*/
|
||||
export default async function HealthReportApi (this: That, params?: T.HealthReportRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.HealthReportResponse>
|
||||
|
||||
@ -44,7 +44,7 @@ export default class Nodes {
|
||||
}
|
||||
|
||||
/**
|
||||
* You can use this API to clear the archived repositories metering information in the cluster.
|
||||
* Clear the archived repositories metering. Clear the archived repositories metering information in the cluster.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/clear-repositories-metering-archive-api.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async clearRepositoriesMeteringArchive (this: That, params: T.NodesClearRepositoriesMeteringArchiveRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.NodesClearRepositoriesMeteringArchiveResponse>
|
||||
@ -77,7 +77,7 @@ export default class Nodes {
|
||||
}
|
||||
|
||||
/**
|
||||
* You can use the cluster repositories metering API to retrieve repositories metering information in a cluster. This API exposes monotonically non-decreasing counters and it’s expected that clients would durably store the information needed to compute aggregations over a period of time. Additionally, the information exposed by this API is volatile, meaning that it won’t be present after node restarts.
|
||||
* Get cluster repositories metering. Get repositories metering information for a cluster. This API exposes monotonically non-decreasing counters and it is expected that clients would durably store the information needed to compute aggregations over a period of time. Additionally, the information exposed by this API is volatile, meaning that it will not be present after node restarts.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/get-repositories-metering-api.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async getRepositoriesMeteringInfo (this: That, params: T.NodesGetRepositoriesMeteringInfoRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.NodesGetRepositoriesMeteringInfoResponse>
|
||||
@ -109,7 +109,7 @@ export default class Nodes {
|
||||
}
|
||||
|
||||
/**
|
||||
* This API yields a breakdown of the hot threads on each selected node in the cluster. The output is plain text with a breakdown of each node’s top hot threads.
|
||||
* Get the hot threads for nodes. Get a breakdown of the hot threads on each selected node in the cluster. The output is plain text with a breakdown of the top hot threads for each node.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-hot-threads.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async hotThreads (this: That, params?: T.NodesHotThreadsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.NodesHotThreadsResponse>
|
||||
@ -149,7 +149,7 @@ export default class Nodes {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns cluster nodes information.
|
||||
* Get node information. By default, the API returns all attributes and core settings for cluster nodes.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-info.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async info (this: That, params?: T.NodesInfoRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.NodesInfoResponse>
|
||||
@ -196,7 +196,7 @@ export default class Nodes {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads the keystore on nodes in the cluster.
|
||||
* Reload the keystore on nodes in the cluster. Secure settings are stored in an on-disk keystore. Certain of these settings are reloadable. That is, you can change them on disk and reload them without restarting any nodes in the cluster. When you have updated reloadable secure settings in your keystore, you can use this API to reload those settings on each node. When the Elasticsearch keystore is password protected and not simply obfuscated, you must provide the password for the keystore when you reload the secure settings. Reloading the settings for the whole cluster assumes that the keystores for all nodes are protected with the same password; this method is allowed only when inter-node communications are encrypted. Alternatively, you can reload the secure settings on each node by locally accessing the API and passing the node-specific Elasticsearch keystore password.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/secure-settings.html#reloadable-secure-settings | Elasticsearch API documentation}
|
||||
*/
|
||||
async reloadSecureSettings (this: That, params?: T.NodesReloadSecureSettingsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.NodesReloadSecureSettingsResponse>
|
||||
@ -240,7 +240,7 @@ export default class Nodes {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns cluster nodes statistics.
|
||||
* Get node statistics. Get statistics for nodes in a cluster. By default, all stats are returned. You can limit the returned information by using metrics.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-stats.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async stats (this: That, params?: T.NodesStatsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.NodesStatsResponse>
|
||||
@ -294,7 +294,7 @@ export default class Nodes {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns information on the usage of features.
|
||||
* Get feature usage information.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-usage.html | Elasticsearch API documentation}
|
||||
*/
|
||||
async usage (this: That, params?: T.NodesUsageRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.NodesUsageResponse>
|
||||
|
||||
@ -38,7 +38,7 @@ import * as T from '../types'
|
||||
interface That { transport: Transport }
|
||||
|
||||
/**
|
||||
* Ping the cluster. Returns whether the cluster is running.
|
||||
* Ping the cluster. Get information about whether the cluster is running.
|
||||
* @see {@link https://www.elastic.co/guide/en/elasticsearch/reference/master/index.html | Elasticsearch API documentation}
|
||||
*/
|
||||
export default async function PingApi (this: That, params?: T.PingRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.PingResponse>
|
||||
|
||||
Reference in New Issue
Block a user