From 2812b28706f16919ed2be4df59ce13de25cf1cbf Mon Sep 17 00:00:00 2001 From: Brusic Date: Wed, 24 Jan 2018 13:27:47 -0800 Subject: [PATCH 01/28] Get all scripts from ScriptService --- .../test/painless/70_get_all.yml | 25 ++++++ .../rest-api-spec/api/get_scripts.json | 15 ++++ .../storedscripts/GetStoredScriptsAction.java | 45 ++++++++++ .../GetStoredScriptsRequest.java | 53 +++++++++++ .../GetStoredScriptsRequestBuilder.java | 33 +++++++ .../GetStoredScriptsResponse.java | 86 ++++++++++++++++++ .../TransportGetStoredScriptsAction.java | 72 +++++++++++++++ .../client/ClusterAdminClient.java | 18 ++++ .../client/support/AbstractClient.java | 20 +++++ .../cluster/RestGetStoredScriptsAction.java | 88 +++++++++++++++++++ .../elasticsearch/script/ScriptMetaData.java | 7 ++ .../elasticsearch/script/ScriptService.java | 7 ++ .../GetStoredScriptsRequestTests.java | 45 ++++++++++ .../script/ScriptMetaDataTests.java | 25 ++++++ .../elasticsearch/script/StoredScriptsIT.java | 22 +++++ 15 files changed, 561 insertions(+) create mode 100644 modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml create mode 100644 rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json create mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java create mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java create mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java create mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java create mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java create mode 100644 server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java create mode 100644 server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml new file mode 100644 index 0000000000000..4f7e0a5cfdaf8 --- /dev/null +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml @@ -0,0 +1,25 @@ +--- +"Get all scripts": + + - skip: + version: " - 6.99.99" + reason: this uses a new API that has been added in 7.0 + + - do: + put_script: + id: "1" + body: { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value" } } + - match: { acknowledged: true } + + - do: + put_script: + id: "foo" + body: { "script": {"lang": "painless", "source": "_score * 9.9" } } + - match: { acknowledged: true } + + - do: + get_scripts: {} + + - length: {$body: 2} + - match: { 1.script: {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } + - match: { foo.script: {"lang": "painless", "source": "_score * 9.9"} } diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json b/rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json new file mode 100644 index 0000000000000..e254e9e5013ff --- /dev/null +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json @@ -0,0 +1,15 @@ +{ + "get_scripts": { + "documentation": "http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting.html", + "methods": ["GET"], + "url": { + "path": "/_scripts", + "paths": [ "/_scripts" ], + "parts": { + }, + "params" : { + } + }, + "body": null + } +} \ No newline at end of file diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java new file mode 100644 index 0000000000000..2ef78444ce0af --- /dev/null +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java @@ -0,0 +1,45 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ + +package org.elasticsearch.action.admin.cluster.storedscripts; + +import org.elasticsearch.action.Action; +import org.elasticsearch.client.ElasticsearchClient; + +public class GetStoredScriptsAction extends Action { + + public static final GetStoredScriptsAction INSTANCE = new GetStoredScriptsAction(); + public static final String NAME = "cluster:admin/scripts/get"; + + private GetStoredScriptsAction() { + super(NAME); + } + + @Override + public GetStoredScriptsResponse newResponse() { + return new GetStoredScriptsResponse(); + } + + @Override + public GetStoredScriptsRequestBuilder newRequestBuilder(ElasticsearchClient client) { + return new GetStoredScriptsRequestBuilder(client, this); + } + +} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java new file mode 100644 index 0000000000000..284d43c26277e --- /dev/null +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java @@ -0,0 +1,53 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ + +package org.elasticsearch.action.admin.cluster.storedscripts; + +import org.elasticsearch.action.ActionRequestValidationException; +import org.elasticsearch.action.support.master.MasterNodeReadRequest; +import org.elasticsearch.common.io.stream.StreamInput; + +import java.io.IOException; + +public class GetStoredScriptsRequest extends MasterNodeReadRequest { + + + public GetStoredScriptsRequest() { + super(); + } + + public GetStoredScriptsRequest(StreamInput in) throws IOException { + super(in); + } + + @Override + public ActionRequestValidationException validate() { + return null; + } + + @Override + public void readFrom(StreamInput in) throws IOException { + throw new UnsupportedOperationException("usage of Streamable is to be replaced by Writeable"); + } + + @Override + public String toString() { + return "get scripts"; + } +} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java new file mode 100644 index 0000000000000..b35afff425b48 --- /dev/null +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java @@ -0,0 +1,33 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ + +package org.elasticsearch.action.admin.cluster.storedscripts; + +import org.elasticsearch.action.support.master.MasterNodeReadOperationRequestBuilder; +import org.elasticsearch.client.ElasticsearchClient; + +public class GetStoredScriptsRequestBuilder extends + MasterNodeReadOperationRequestBuilder { + + + public GetStoredScriptsRequestBuilder(ElasticsearchClient client, GetStoredScriptsAction action) { + super(client, action, new GetStoredScriptsRequest()); + } +} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java new file mode 100644 index 0000000000000..89f5dc66870c5 --- /dev/null +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java @@ -0,0 +1,86 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ + +package org.elasticsearch.action.admin.cluster.storedscripts; + +import org.elasticsearch.action.ActionResponse; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.common.xcontent.ToXContentObject; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.script.StoredScriptSource; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class GetStoredScriptsResponse extends ActionResponse implements ToXContentObject { + + private Map storedScripts; + + GetStoredScriptsResponse() { + } + + GetStoredScriptsResponse(Map storedScripts) { + this.storedScripts = storedScripts; + } + + public Map getStoredScripts() { + return storedScripts; + } + + @Override + public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { + builder.startObject(); + for (Map.Entry storedScript : getStoredScripts().entrySet()) { + + builder.startObject(storedScript.getKey()); + + builder.startObject(); + storedScript.getValue().toXContent(builder, params); + builder.endObject(); + + builder.endObject(); + } + builder.endObject(); + return builder; + } + + @Override + public void readFrom(StreamInput in) throws IOException { + super.readFrom(in); + + int size = in.readVInt(); + storedScripts = new HashMap<>(size); + for (int i = 0 ; i < size ; i++) { + String id = in.readString(); + storedScripts.put(id, new StoredScriptSource(in)); + } + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + super.writeTo(out); + out.writeVInt(storedScripts.size()); + for (Map.Entry storedScript : storedScripts.entrySet()) { + out.writeString(storedScript.getKey()); + storedScript.getValue().writeTo(out); + } + } +} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java new file mode 100644 index 0000000000000..2496dcca393bb --- /dev/null +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java @@ -0,0 +1,72 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ + +package org.elasticsearch.action.admin.cluster.storedscripts; + +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.action.support.ActionFilters; +import org.elasticsearch.action.support.master.TransportMasterNodeReadAction; +import org.elasticsearch.cluster.ClusterState; +import org.elasticsearch.cluster.block.ClusterBlockException; +import org.elasticsearch.cluster.block.ClusterBlockLevel; +import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; +import org.elasticsearch.cluster.service.ClusterService; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.script.ScriptService; +import org.elasticsearch.threadpool.ThreadPool; +import org.elasticsearch.transport.TransportService; + +public class TransportGetStoredScriptsAction extends TransportMasterNodeReadAction { + + private final ScriptService scriptService; + + @Inject + public TransportGetStoredScriptsAction(Settings settings, TransportService transportService, ClusterService clusterService, + ThreadPool threadPool, ActionFilters actionFilters, + IndexNameExpressionResolver indexNameExpressionResolver, ScriptService scriptService) { + super(settings, GetStoredScriptsAction.NAME, transportService, clusterService, threadPool, + actionFilters, + GetStoredScriptsRequest::new, indexNameExpressionResolver); + this.scriptService = scriptService; + } + + @Override + protected String executor() { + return ThreadPool.Names.SAME; + } + + @Override + protected GetStoredScriptsResponse newResponse() { + return new GetStoredScriptsResponse(); + } + + @Override + protected void masterOperation(GetStoredScriptsRequest request, ClusterState state, + ActionListener listener) throws Exception { + listener.onResponse(new GetStoredScriptsResponse(scriptService.getStoredScripts(state))); + } + + @Override + protected ClusterBlockException checkBlock(GetStoredScriptsRequest request, ClusterState state) { + return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); + } + +} diff --git a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java index fdee39fdb1f93..d90bf5b164cbd 100644 --- a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java +++ b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java @@ -96,6 +96,9 @@ import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequestBuilder; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequestBuilder; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequestBuilder; import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksRequest; @@ -718,4 +721,19 @@ public interface ClusterAdminClient extends ElasticsearchClient { * Get a script from the cluster state */ ActionFuture getStoredScript(GetStoredScriptRequest request); + + /** + * Get a script from the cluster state + */ + GetStoredScriptsRequestBuilder prepareGetStoredScripts(); + + /** + * Get all scripts from the cluster state + */ + void getStoredScripts(GetStoredScriptsRequest request, ActionListener listener); + + /** + * Get all scripts from the cluster state + */ + ActionFuture getStoredScripts(GetStoredScriptsRequest request); } diff --git a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java index 283b8dc0a2843..e4724ffccda0b 100644 --- a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java +++ b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java @@ -128,6 +128,10 @@ import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequestBuilder; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsAction; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequestBuilder; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptAction; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequestBuilder; @@ -1159,6 +1163,22 @@ public GetStoredScriptRequestBuilder prepareGetStoredScript(String id) { return prepareGetStoredScript().setId(id); } + @Override + public ActionFuture getStoredScripts(GetStoredScriptsRequest request) { + return execute(GetStoredScriptsAction.INSTANCE, request); + } + + @Override + public void getStoredScripts(GetStoredScriptsRequest request, + ActionListener listener) { + execute(GetStoredScriptsAction.INSTANCE, request, listener); + } + + @Override + public GetStoredScriptsRequestBuilder prepareGetStoredScripts() { + return new GetStoredScriptsRequestBuilder(this, GetStoredScriptsAction.INSTANCE); + } + @Override public PutStoredScriptRequestBuilder preparePutStoredScript() { return new PutStoredScriptRequestBuilder(this, PutStoredScriptAction.INSTANCE); diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java new file mode 100644 index 0000000000000..121acd39c2430 --- /dev/null +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java @@ -0,0 +1,88 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ +package org.elasticsearch.rest.action.admin.cluster; + +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; +import org.elasticsearch.client.node.NodeClient; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.rest.BaseRestHandler; +import org.elasticsearch.rest.BytesRestResponse; +import org.elasticsearch.rest.RestController; +import org.elasticsearch.rest.RestRequest; +import org.elasticsearch.rest.RestResponse; +import org.elasticsearch.rest.RestStatus; +import org.elasticsearch.rest.action.RestBuilderListener; +import org.elasticsearch.script.StoredScriptSource; + +import java.io.IOException; +import java.util.Map; + +import static org.elasticsearch.rest.RestRequest.Method.GET; + +public class RestGetStoredScriptsAction extends BaseRestHandler { + + public RestGetStoredScriptsAction(Settings settings, RestController controller) { + super(settings); + + controller.registerHandler(GET, "/_scripts", this); + } + + @Override + public String getName() { + return "get_all_stored_scripts_action"; + } + + @Override + public RestChannelConsumer prepareRequest(final RestRequest request, NodeClient client) throws IOException { + GetStoredScriptsRequest getRequest = new GetStoredScriptsRequest(); + + + return channel -> client.admin().cluster().getStoredScripts(getRequest, new + RestBuilderListener(channel) { + @Override + public RestResponse buildResponse(GetStoredScriptsResponse response, XContentBuilder builder) + throws Exception { + builder.startObject(); + + Map storedScripts = response.getStoredScripts(); + for (Map.Entry storedScript : storedScripts.entrySet()) { + builder.startObject(storedScript.getKey()); + + StoredScriptSource source = storedScript.getValue(); + builder.startObject(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); + builder.field(StoredScriptSource.LANG_PARSE_FIELD.getPreferredName(), source.getLang()); + builder.field(StoredScriptSource.SOURCE_PARSE_FIELD.getPreferredName(), source.getSource()); + + if (!source.getOptions().isEmpty()) { + builder.field(StoredScriptSource.OPTIONS_PARSE_FIELD.getPreferredName(), source.getOptions()); + } + + builder.endObject(); + builder.endObject(); + } + + builder.endObject(); + + return new BytesRestResponse(RestStatus.OK, builder); + } + }); + } +} diff --git a/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java b/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java index 52a06db582966..118755b60c339 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java @@ -366,6 +366,13 @@ StoredScriptSource getStoredScript(String id) { return scripts.get(id); } + /** + * Retrieves all stored scripts + */ + Map getStoredScripts() { + return scripts; + } + @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/server/src/main/java/org/elasticsearch/script/ScriptService.java b/server/src/main/java/org/elasticsearch/script/ScriptService.java index f1472afba9342..83e51a5f0ccaf 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptService.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptService.java @@ -538,6 +538,13 @@ public StoredScriptSource getStoredScript(ClusterState state, GetStoredScriptReq } } + public Map getStoredScripts(ClusterState state) { + ScriptMetaData scriptMetadata = state.metaData().custom(ScriptMetaData.TYPE); + + return scriptMetadata.getStoredScripts(); + } + + public ScriptStats stats() { return scriptMetrics.stats(); } diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java new file mode 100644 index 0000000000000..4c2dd2b617152 --- /dev/null +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java @@ -0,0 +1,45 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ + +package org.elasticsearch.action.admin.cluster.storedscripts; + +import org.elasticsearch.common.io.stream.BytesStreamOutput; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.test.ESTestCase; + +import java.io.IOException; + +import static org.elasticsearch.test.VersionUtils.randomVersion; +import static org.hamcrest.CoreMatchers.equalTo; + +public class GetStoredScriptsRequestTests extends ESTestCase { + public void testGetIndexedScriptsRequestSerialization() throws IOException { + GetStoredScriptsRequest request = new GetStoredScriptsRequest(); + + BytesStreamOutput out = new BytesStreamOutput(); + out.setVersion(randomVersion(random())); + request.writeTo(out); + + StreamInput in = out.bytes().streamInput(); + in.setVersion(out.getVersion()); + GetStoredScriptsRequest request2 = new GetStoredScriptsRequest(in); + + assertThat(request2, equalTo(request)); + } +} diff --git a/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java b/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java index 7a856ee13b9d3..173f3d4e24d30 100644 --- a/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java +++ b/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java @@ -32,6 +32,7 @@ import java.io.IOException; import java.io.UncheckedIOException; +import java.util.Map; public class ScriptMetaDataTests extends AbstractSerializingTestCase { @@ -93,6 +94,30 @@ public void testGetScript() throws Exception { assertEquals("{\"field\":\"value\"}", scriptMetaData.getStoredScript("source_template").getSource()); } + public void testGetScripts() throws Exception { + ScriptMetaData.Builder builder = new ScriptMetaData.Builder(null); + + XContentBuilder sourceBuilder = XContentFactory.jsonBuilder(); + sourceBuilder.startObject().startObject("template").field("field", "value").endObject().endObject(); + builder.storeScript("template", StoredScriptSource.parse(sourceBuilder.bytes(), sourceBuilder.contentType())); + + sourceBuilder = XContentFactory.jsonBuilder(); + sourceBuilder.startObject().field("template", "value").endObject(); + builder.storeScript("template_field", StoredScriptSource.parse(sourceBuilder.bytes(), sourceBuilder.contentType())); + + sourceBuilder = XContentFactory.jsonBuilder(); + sourceBuilder.startObject().startObject("script").field("lang", "_lang").field("source", "_source").endObject().endObject(); + builder.storeScript("script", StoredScriptSource.parse(sourceBuilder.bytes(), sourceBuilder.contentType())); + + ScriptMetaData scriptMetaData = builder.build(); + Map storedScripts = scriptMetaData.getStoredScripts(); + + assertEquals(3, storedScripts.size()); + assertEquals("_source", storedScripts.get("script").getSource()); + assertEquals("{\"field\":\"value\"}", storedScripts.get("template").getSource()); + assertEquals("value", storedScripts.get("template_field").getSource()); + } + public void testDiff() throws Exception { ScriptMetaData.Builder builder = new ScriptMetaData.Builder(null); builder.storeScript("1", StoredScriptSource.parse( diff --git a/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java b/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java index a1a82c88819a2..3f0f1801735bd 100644 --- a/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java +++ b/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java @@ -71,6 +71,28 @@ public void testBasics() { assertEquals("Validation Failed: 1: id cannot contain '#' for stored script;", e.getMessage()); } + public void testGetAllScripts() { + assertAcked(client().admin().cluster().preparePutStoredScript() + .setId("foobar") + .setContent(new BytesArray("{\"script\": {\"lang\": \"" + LANG + "\", \"source\": \"1\"} }"), XContentType.JSON)); + + assertAcked(client().admin().cluster().preparePutStoredScript() + .setId("1") + .setContent(new BytesArray("{\"script\": {\"lang\": \"" + LANG + "\", \"source\": \"9.9\"} }"), + XContentType.JSON)); + + Map storedScripts = client().admin().cluster().prepareGetStoredScripts().get().getStoredScripts(); + assertEquals(2, storedScripts.size()); + + StoredScriptSource source = storedScripts.get("foobar"); + assertNotNull(source); + assertEquals(LANG, source.getLang()); + + source = storedScripts.get("1"); + assertNotNull(source); + assertEquals("9.9", source.getSource()); + } + public void testMaxScriptSize() { IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> client().admin().cluster().preparePutStoredScript() .setId("foobar") From 322f70ba476a633ba3c2dd6a28f4a071519b3c1f Mon Sep 17 00:00:00 2001 From: Brusic Date: Wed, 24 Jan 2018 18:56:06 -0800 Subject: [PATCH 02/28] fixed silly assertEquals test with trivial equals() --- .../storedscripts/GetStoredScriptsRequest.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java index 284d43c26277e..82ac82f982e72 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java @@ -46,8 +46,20 @@ public void readFrom(StreamInput in) throws IOException { throw new UnsupportedOperationException("usage of Streamable is to be replaced by Writeable"); } + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + return !(obj == null || getClass() != obj.getClass()); + } + @Override public String toString() { return "get scripts"; } + } From 9b8406ec92956f74bea40229a0a52f7aa4d7775f Mon Sep 17 00:00:00 2001 From: ivan Date: Thu, 8 Aug 2019 22:57:11 +0200 Subject: [PATCH 03/28] update to latest master --- .../storedscripts/GetStoredScriptsAction.java | 19 ++----- .../GetStoredScriptsRequest.java | 30 ++++++----- .../GetStoredScriptsRequestBuilder.java | 5 +- .../GetStoredScriptsResponse.java | 39 +++++++------- .../TransportGetStoredScriptsAction.java | 51 +++++++++++++++---- .../client/ClusterAdminClient.java | 2 +- .../client/support/AbstractClient.java | 4 +- .../cluster/RestGetStoredScriptsAction.java | 47 +++++++---------- .../elasticsearch/script/ScriptMetaData.java | 7 --- .../elasticsearch/script/ScriptService.java | 6 ++- .../script/ScriptMetaDataTests.java | 19 ++++--- 11 files changed, 116 insertions(+), 113 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java index 2ef78444ce0af..debe140d66c51 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java @@ -19,27 +19,14 @@ package org.elasticsearch.action.admin.cluster.storedscripts; -import org.elasticsearch.action.Action; -import org.elasticsearch.client.ElasticsearchClient; +import org.elasticsearch.action.ActionType; -public class GetStoredScriptsAction extends Action { +public class GetStoredScriptsAction extends ActionType { public static final GetStoredScriptsAction INSTANCE = new GetStoredScriptsAction(); public static final String NAME = "cluster:admin/scripts/get"; private GetStoredScriptsAction() { - super(NAME); + super(NAME, GetStoredScriptsResponse::new); } - - @Override - public GetStoredScriptsResponse newResponse() { - return new GetStoredScriptsResponse(); - } - - @Override - public GetStoredScriptsRequestBuilder newRequestBuilder(ElasticsearchClient client) { - return new GetStoredScriptsRequestBuilder(client, this); - } - } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java index 82ac82f982e72..42d01fad49e5e 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java @@ -22,39 +22,43 @@ import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.support.master.MasterNodeReadRequest; import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; import java.io.IOException; public class GetStoredScriptsRequest extends MasterNodeReadRequest { + private String[] names; public GetStoredScriptsRequest() { super(); } - public GetStoredScriptsRequest(StreamInput in) throws IOException { - super(in); + public GetStoredScriptsRequest(String... names) { + this.names = names; } - @Override - public ActionRequestValidationException validate() { - return null; + public GetStoredScriptsRequest(StreamInput in) throws IOException { + super(in); + names = in.readStringArray(); } - @Override - public void readFrom(StreamInput in) throws IOException { - throw new UnsupportedOperationException("usage of Streamable is to be replaced by Writeable"); + /** + * The names of the search templates. + */ + public String[] names() { + return this.names; } @Override - public int hashCode() { - return super.hashCode(); + public void writeTo(StreamOutput out) throws IOException { + super.writeTo(out); + out.writeStringArray(names); } @Override - public boolean equals(Object obj) { - if (this == obj) return true; - return !(obj == null || getClass() != obj.getClass()); + public ActionRequestValidationException validate() { + return null; } @Override diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java index b35afff425b48..a2522ceb68b3c 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java @@ -26,8 +26,11 @@ public class GetStoredScriptsRequestBuilder extends MasterNodeReadOperationRequestBuilder { - public GetStoredScriptsRequestBuilder(ElasticsearchClient client, GetStoredScriptsAction action) { super(client, action, new GetStoredScriptsRequest()); } + + public GetStoredScriptsRequestBuilder(ElasticsearchClient client, GetStoredScriptsAction action, String... names) { + super(client, action, new GetStoredScriptsRequest(names)); + } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java index 89f5dc66870c5..db6bd2bc9be1f 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java @@ -34,7 +34,15 @@ public class GetStoredScriptsResponse extends ActionResponse implements ToXConte private Map storedScripts; - GetStoredScriptsResponse() { + GetStoredScriptsResponse(StreamInput in) throws IOException { + super(in); + + int size = in.readVInt(); + storedScripts = new HashMap<>(size); + for (int i = 0 ; i < size ; i++) { + String id = in.readString(); + storedScripts.put(id, new StoredScriptSource(in)); + } } GetStoredScriptsResponse(Map storedScripts) { @@ -48,35 +56,22 @@ public Map getStoredScripts() { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); - for (Map.Entry storedScript : getStoredScripts().entrySet()) { - - builder.startObject(storedScript.getKey()); - builder.startObject(); - storedScript.getValue().toXContent(builder, params); - builder.endObject(); - - builder.endObject(); + Map storedScripts = getStoredScripts(); + if (storedScripts != null) { + for (Map.Entry storedScript : storedScripts.entrySet()) { + builder.startObject(storedScript.getKey()); + builder.field(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); + storedScript.getValue().toXContent(builder, params); + builder.endObject(); + } } builder.endObject(); return builder; } - @Override - public void readFrom(StreamInput in) throws IOException { - super.readFrom(in); - - int size = in.readVInt(); - storedScripts = new HashMap<>(size); - for (int i = 0 ; i < size ; i++) { - String id = in.readString(); - storedScripts.put(id, new StoredScriptSource(in)); - } - } - @Override public void writeTo(StreamOutput out) throws IOException { - super.writeTo(out); out.writeVInt(storedScripts.size()); for (Map.Entry storedScript : storedScripts.entrySet()) { out.writeString(storedScript.getKey()); diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java index 2496dcca393bb..3e4aea7ea116f 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java @@ -28,22 +28,28 @@ import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.regex.Regex; import org.elasticsearch.script.ScriptService; +import org.elasticsearch.script.StoredScriptSource; +import org.elasticsearch.tasks.Task; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + public class TransportGetStoredScriptsAction extends TransportMasterNodeReadAction { private final ScriptService scriptService; @Inject - public TransportGetStoredScriptsAction(Settings settings, TransportService transportService, ClusterService clusterService, - ThreadPool threadPool, ActionFilters actionFilters, - IndexNameExpressionResolver indexNameExpressionResolver, ScriptService scriptService) { - super(settings, GetStoredScriptsAction.NAME, transportService, clusterService, threadPool, - actionFilters, + public TransportGetStoredScriptsAction(TransportService transportService, ClusterService clusterService, + ThreadPool threadPool, ActionFilters actionFilters, + IndexNameExpressionResolver indexNameExpressionResolver, ScriptService scriptService) { + super(GetStoredScriptsAction.NAME, transportService, clusterService, threadPool, actionFilters, GetStoredScriptsRequest::new, indexNameExpressionResolver); this.scriptService = scriptService; } @@ -54,14 +60,39 @@ protected String executor() { } @Override - protected GetStoredScriptsResponse newResponse() { - return new GetStoredScriptsResponse(); + protected GetStoredScriptsResponse read(StreamInput in) throws IOException { + return new GetStoredScriptsResponse(in); } @Override - protected void masterOperation(GetStoredScriptsRequest request, ClusterState state, + protected void masterOperation(Task task, GetStoredScriptsRequest request, ClusterState state, ActionListener listener) throws Exception { - listener.onResponse(new GetStoredScriptsResponse(scriptService.getStoredScripts(state))); + + Map results; + + Map storedScripts = scriptService.getStoredScripts(state); + // If we did not ask for a specific name, then we return all templates + if (request.names().length == 0) { + results = storedScripts; + } else { + results = new HashMap<>(); + } + + if (storedScripts != null) { + for (String name : request.names()) { + if (Regex.isSimpleMatchPattern(name)) { + for (Map.Entry entry : storedScripts.entrySet()) { + if (Regex.simpleMatch(name, entry.getKey())) { + results.put(entry.getKey(), entry.getValue()); + } + } + } else if (storedScripts.containsKey(name)) { + results.put(name, storedScripts.get(name)); + } + } + } + + listener.onResponse(new GetStoredScriptsResponse(results)); } @Override diff --git a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java index d90bf5b164cbd..36e6eb2900f1c 100644 --- a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java +++ b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java @@ -725,7 +725,7 @@ public interface ClusterAdminClient extends ElasticsearchClient { /** * Get a script from the cluster state */ - GetStoredScriptsRequestBuilder prepareGetStoredScripts(); + GetStoredScriptsRequestBuilder prepareGetStoredScripts(String... name); /** * Get all scripts from the cluster state diff --git a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java index e4724ffccda0b..174829403cc42 100644 --- a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java +++ b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java @@ -1175,8 +1175,8 @@ public void getStoredScripts(GetStoredScriptsRequest request, } @Override - public GetStoredScriptsRequestBuilder prepareGetStoredScripts() { - return new GetStoredScriptsRequestBuilder(this, GetStoredScriptsAction.INSTANCE); + public GetStoredScriptsRequestBuilder prepareGetStoredScripts(String... names) { + return new GetStoredScriptsRequestBuilder(this, GetStoredScriptsAction.INSTANCE, names); } @Override diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java index 121acd39c2430..5e272ae5ba1e1 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java @@ -21,21 +21,22 @@ import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; import org.elasticsearch.client.node.NodeClient; +import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.BaseRestHandler; -import org.elasticsearch.rest.BytesRestResponse; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; -import org.elasticsearch.rest.RestResponse; import org.elasticsearch.rest.RestStatus; -import org.elasticsearch.rest.action.RestBuilderListener; +import org.elasticsearch.rest.action.RestToXContentListener; import org.elasticsearch.script.StoredScriptSource; import java.io.IOException; import java.util.Map; import static org.elasticsearch.rest.RestRequest.Method.GET; +import static org.elasticsearch.rest.RestRequest.Method.HEAD; +import static org.elasticsearch.rest.RestStatus.NOT_FOUND; +import static org.elasticsearch.rest.RestStatus.OK; public class RestGetStoredScriptsAction extends BaseRestHandler { @@ -43,6 +44,8 @@ public RestGetStoredScriptsAction(Settings settings, RestController controller) super(settings); controller.registerHandler(GET, "/_scripts", this); + controller.registerHandler(GET, "/_script/{name}", this); + controller.registerHandler(HEAD, "/_script/{name}", this); } @Override @@ -52,36 +55,20 @@ public String getName() { @Override public RestChannelConsumer prepareRequest(final RestRequest request, NodeClient client) throws IOException { - GetStoredScriptsRequest getRequest = new GetStoredScriptsRequest(); + final String[] names = Strings.splitStringByCommaToArray(request.param("name")); + GetStoredScriptsRequest getRequest = new GetStoredScriptsRequest(names); + getRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRequest.masterNodeTimeout())); - return channel -> client.admin().cluster().getStoredScripts(getRequest, new - RestBuilderListener(channel) { - @Override - public RestResponse buildResponse(GetStoredScriptsResponse response, XContentBuilder builder) - throws Exception { - builder.startObject(); + final boolean implicitAll = getRequest.names().length == 0; + return channel -> client.admin().cluster().getStoredScripts(getRequest, new RestToXContentListener<>(channel) { + @Override + protected RestStatus getStatus(final GetStoredScriptsResponse response) + { Map storedScripts = response.getStoredScripts(); - for (Map.Entry storedScript : storedScripts.entrySet()) { - builder.startObject(storedScript.getKey()); - - StoredScriptSource source = storedScript.getValue(); - builder.startObject(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); - builder.field(StoredScriptSource.LANG_PARSE_FIELD.getPreferredName(), source.getLang()); - builder.field(StoredScriptSource.SOURCE_PARSE_FIELD.getPreferredName(), source.getSource()); - - if (!source.getOptions().isEmpty()) { - builder.field(StoredScriptSource.OPTIONS_PARSE_FIELD.getPreferredName(), source.getOptions()); - } - - builder.endObject(); - builder.endObject(); - } - - builder.endObject(); - - return new BytesRestResponse(RestStatus.OK, builder); + final boolean templateExists = storedScripts != null && !storedScripts.isEmpty(); + return (templateExists || implicitAll) ? OK : NOT_FOUND; } }); } diff --git a/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java b/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java index 118755b60c339..52a06db582966 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java @@ -366,13 +366,6 @@ StoredScriptSource getStoredScript(String id) { return scripts.get(id); } - /** - * Retrieves all stored scripts - */ - Map getStoredScripts() { - return scripts; - } - @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/server/src/main/java/org/elasticsearch/script/ScriptService.java b/server/src/main/java/org/elasticsearch/script/ScriptService.java index 83e51a5f0ccaf..1425b8746ad6e 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptService.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptService.java @@ -541,7 +541,11 @@ public StoredScriptSource getStoredScript(ClusterState state, GetStoredScriptReq public Map getStoredScripts(ClusterState state) { ScriptMetaData scriptMetadata = state.metaData().custom(ScriptMetaData.TYPE); - return scriptMetadata.getStoredScripts(); + if (scriptMetadata != null) { + return scriptMetadata.getStoredScripts(); + } else { + return null; + } } diff --git a/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java b/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java index 173f3d4e24d30..3889b94d2e4e9 100644 --- a/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java +++ b/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java @@ -98,24 +98,23 @@ public void testGetScripts() throws Exception { ScriptMetaData.Builder builder = new ScriptMetaData.Builder(null); XContentBuilder sourceBuilder = XContentFactory.jsonBuilder(); - sourceBuilder.startObject().startObject("template").field("field", "value").endObject().endObject(); - builder.storeScript("template", StoredScriptSource.parse(sourceBuilder.bytes(), sourceBuilder.contentType())); - - sourceBuilder = XContentFactory.jsonBuilder(); - sourceBuilder.startObject().field("template", "value").endObject(); - builder.storeScript("template_field", StoredScriptSource.parse(sourceBuilder.bytes(), sourceBuilder.contentType())); + sourceBuilder.startObject().startObject("script") + .field("lang", "_lang") + .startObject("source").field("field", "value").endObject() + .endObject().endObject(); + builder.storeScript("source_template", StoredScriptSource.parse(BytesReference.bytes(sourceBuilder), + sourceBuilder.contentType())); sourceBuilder = XContentFactory.jsonBuilder(); sourceBuilder.startObject().startObject("script").field("lang", "_lang").field("source", "_source").endObject().endObject(); - builder.storeScript("script", StoredScriptSource.parse(sourceBuilder.bytes(), sourceBuilder.contentType())); + builder.storeScript("script", StoredScriptSource.parse(BytesReference.bytes(sourceBuilder), sourceBuilder.contentType())); ScriptMetaData scriptMetaData = builder.build(); Map storedScripts = scriptMetaData.getStoredScripts(); - assertEquals(3, storedScripts.size()); + assertEquals(2, storedScripts.size()); assertEquals("_source", storedScripts.get("script").getSource()); - assertEquals("{\"field\":\"value\"}", storedScripts.get("template").getSource()); - assertEquals("value", storedScripts.get("template_field").getSource()); + assertEquals("{\"field\":\"value\"}", storedScripts.get("source_template").getSource()); } public void testDiff() throws Exception { From 5d4b9ab93ccf33aad96c51d1bfbbdf57a02894b9 Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 13 Aug 2019 14:05:49 -0700 Subject: [PATCH 04/28] backwards compatibility --- .../GetStoredScriptRequestBuilder.java | 1 - .../GetStoredScriptsRequest.java | 9 +++++++++ .../GetStoredScriptsResponse.java | 20 +++++++++++++++++++ .../TransportGetStoredScriptsAction.java | 4 ++++ .../client/ClusterAdminClient.java | 6 ++++++ .../client/support/AbstractClient.java | 6 ++++++ 6 files changed, 45 insertions(+), 1 deletion(-) diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java index 75708c929f584..15e96aca88049 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java @@ -34,5 +34,4 @@ public GetStoredScriptRequestBuilder setId(String id) { request.id(id); return this; } - } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java index 42d01fad49e5e..c97f8610de5ad 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java @@ -50,6 +50,15 @@ public String[] names() { return this.names; } + /** + * @deprecated - Needed for backwards compatibility. + * * Use {@link #names()} instead + */ + @Deprecated + public String id() { + return names != null && names.length == 1 ? names[0] : null; + } + @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java index db6bd2bc9be1f..50437902d03bf 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java @@ -53,6 +53,21 @@ public Map getStoredScripts() { return storedScripts; } + /** + * @deprecated - Needed for backwards compatibility. + * Use {@link #getStoredScripts()} instead + * + * @return if a stored script and if not found null + */ + @Deprecated + public StoredScriptSource getSource() { + if (storedScripts != null && storedScripts.size() == 1) { + return storedScripts.entrySet().iterator().next().getValue(); + } else { + return null; + } + } + @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); @@ -72,6 +87,11 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public void writeTo(StreamOutput out) throws IOException { + if (storedScripts == null ) { + out.writeVInt(0); + return; + } + out.writeVInt(storedScripts.size()); for (Map.Entry storedScript : storedScripts.entrySet()) { out.writeString(storedScript.getKey()); diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java index 3e4aea7ea116f..b2dea0f921ff8 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java @@ -67,6 +67,10 @@ protected GetStoredScriptsResponse read(StreamInput in) throws IOException { @Override protected void masterOperation(Task task, GetStoredScriptsRequest request, ClusterState state, ActionListener listener) throws Exception { + if (request.id() != null) { + listener.onResponse(new GetStoredScriptsResponse(scriptService.getStoredScripts(state))); + return; + } Map results; diff --git a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java index 36e6eb2900f1c..f6c9ce09d07a4 100644 --- a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java +++ b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java @@ -725,6 +725,12 @@ public interface ClusterAdminClient extends ElasticsearchClient { /** * Get a script from the cluster state */ + @Deprecated + GetStoredScriptsRequestBuilder prepareGetStoredScripts(String id); + + /** + * Get scripts from the cluster state + */ GetStoredScriptsRequestBuilder prepareGetStoredScripts(String... name); /** diff --git a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java index 174829403cc42..73972ba712d2e 100644 --- a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java +++ b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java @@ -1163,6 +1163,12 @@ public GetStoredScriptRequestBuilder prepareGetStoredScript(String id) { return prepareGetStoredScript().setId(id); } + @Override + @Deprecated + public GetStoredScriptsRequestBuilder prepareGetStoredScripts(String id) { + return prepareGetStoredScripts(new String[]{id}); + } + @Override public ActionFuture getStoredScripts(GetStoredScriptsRequest request) { return execute(GetStoredScriptsAction.INSTANCE, request); From 74a1a9348cc0f024103b3e0f26ca628db1dcbadc Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 13 Aug 2019 22:38:43 -0700 Subject: [PATCH 05/28] Update all code to support old/new interaces. Removed *Scripts* family of classes. --- .../client/RequestConverters.java | 6 +- .../elasticsearch/client/StoredScriptsIT.java | 8 +- .../test/painless/70_get_all.yml | 8 +- .../rest-api-spec/api/delete_script.json | 2 +- .../rest-api-spec/api/get_script.json | 14 ++- .../rest-api-spec/api/get_scripts.json | 15 --- .../rest-api-spec/api/put_script.json | 4 +- .../storedscripts/GetStoredScriptRequest.java | 72 +++++++----- .../GetStoredScriptRequestBuilder.java | 5 +- .../GetStoredScriptResponse.java | 101 +++++++++++------ .../storedscripts/GetStoredScriptsAction.java | 32 ------ .../GetStoredScriptsRequest.java | 78 ------------- .../GetStoredScriptsRequestBuilder.java | 36 ------ .../GetStoredScriptsResponse.java | 101 ----------------- .../TransportGetStoredScriptAction.java | 35 +++++- .../TransportGetStoredScriptsAction.java | 107 ------------------ .../client/ClusterAdminClient.java | 28 +---- .../client/support/AbstractClient.java | 25 +--- .../cluster/RestDeleteStoredScriptAction.java | 9 +- .../cluster/RestGetStoredScriptAction.java | 39 ++++++- .../cluster/RestGetStoredScriptsAction.java | 75 ------------ .../cluster/RestPutStoredScriptAction.java | 18 ++- .../elasticsearch/script/ScriptService.java | 1 - .../GetStoredScriptResponseTests.java | 6 +- .../GetStoredScriptsRequestTests.java | 45 -------- .../elasticsearch/script/StoredScriptsIT.java | 12 +- 26 files changed, 248 insertions(+), 634 deletions(-) delete mode 100644 rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json delete mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java delete mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java delete mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java delete mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java delete mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java delete mode 100644 server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java delete mode 100644 server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java index 78a84b33ff83c..9342df33154c2 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java @@ -645,7 +645,7 @@ private static Request rethrottle(RethrottleRequest rethrottleRequest, String fi } static Request putScript(PutStoredScriptRequest putStoredScriptRequest) throws IOException { - String endpoint = new EndpointBuilder().addPathPartAsIs("_scripts").addPathPart(putStoredScriptRequest.id()).build(); + String endpoint = new EndpointBuilder().addPathPartAsIs("_script").addPathPart(putStoredScriptRequest.id()).build(); Request request = new Request(HttpPost.METHOD_NAME, endpoint); Params params = new Params(); params.withTimeout(putStoredScriptRequest.timeout()); @@ -702,7 +702,7 @@ static Request mtermVectors(MultiTermVectorsRequest mtvrequest) throws IOExcepti } static Request getScript(GetStoredScriptRequest getStoredScriptRequest) { - String endpoint = new EndpointBuilder().addPathPartAsIs("_scripts").addPathPart(getStoredScriptRequest.id()).build(); + String endpoint = new EndpointBuilder().addPathPartAsIs("_script").addPathPart(getStoredScriptRequest.id()).build(); Request request = new Request(HttpGet.METHOD_NAME, endpoint); Params params = new Params(); params.withMasterTimeout(getStoredScriptRequest.masterNodeTimeout()); @@ -711,7 +711,7 @@ static Request getScript(GetStoredScriptRequest getStoredScriptRequest) { } static Request deleteScript(DeleteStoredScriptRequest deleteStoredScriptRequest) { - String endpoint = new EndpointBuilder().addPathPartAsIs("_scripts").addPathPart(deleteStoredScriptRequest.id()).build(); + String endpoint = new EndpointBuilder().addPathPartAsIs("_script").addPathPart(deleteStoredScriptRequest.id()).build(); Request request = new Request(HttpDelete.METHOD_NAME, endpoint); Params params = new Params(); params.withTimeout(deleteStoredScriptRequest.timeout()); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java index 242c2d9237dff..ddd4c4e8e6fe3 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java @@ -92,10 +92,8 @@ public void testPutScript() throws Exception { new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); - Map script = getAsMap("/_scripts/" + id); - assertThat(extractValue("_id", script), equalTo(id)); - assertThat(extractValue("found", script), equalTo(true)); - assertThat(extractValue("script.lang", script), equalTo("painless")); - assertThat(extractValue("script.source", script), equalTo("Math.log(_score * 2) + params.my_modifier")); + Map script = getAsMap("/_script/" + id); + assertThat(extractValue(id + ".script.lang", script), equalTo("painless")); + assertThat(extractValue(id + ".script.source", script), equalTo("Math.log(_score * 2) + params.my_modifier")); } } diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml index 4f7e0a5cfdaf8..7f9b00f6c2ca1 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml @@ -8,18 +8,18 @@ - do: put_script: id: "1" - body: { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value" } } + body: { "script": { "lang": "painless", "source": "_score * doc['myParent.weight'].value" } } - match: { acknowledged: true } - do: put_script: id: "foo" - body: { "script": {"lang": "painless", "source": "_score * 9.9" } } + body: { "script": { "lang": "painless", "source": "_score * 9.9" } } - match: { acknowledged: true } - do: - get_scripts: {} + get_script: {} - - length: {$body: 2} + - length: { $body: 2 } - match: { 1.script: {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } - match: { foo.script: {"lang": "painless", "source": "_score * 9.9"} } diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/delete_script.json b/rest-api-spec/src/main/resources/rest-api-spec/api/delete_script.json index b38b97ae57c2e..3d199feefafb7 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/delete_script.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/delete_script.json @@ -8,7 +8,7 @@ "url":{ "paths":[ { - "path":"/_scripts/{id}", + "path":"/_script/{id}", "methods":[ "DELETE" ], diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json index 14307bea2ef0b..6c695914011f4 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json @@ -8,7 +8,19 @@ "url":{ "paths":[ { - "path":"/_scripts/{id}", + "path":"/_script", + "methods":[ + "GET" + ], + "parts":{ + "id":{ + "type":"string", + "description":"Script ID" + } + } + }, + { + "path":"/_script/{id}", "methods":[ "GET" ], diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json b/rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json deleted file mode 100644 index e254e9e5013ff..0000000000000 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "get_scripts": { - "documentation": "http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting.html", - "methods": ["GET"], - "url": { - "path": "/_scripts", - "paths": [ "/_scripts" ], - "parts": { - }, - "params" : { - } - }, - "body": null - } -} \ No newline at end of file diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/put_script.json b/rest-api-spec/src/main/resources/rest-api-spec/api/put_script.json index 750f7fdf4eb62..c3f69f1bc2472 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/put_script.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/put_script.json @@ -8,7 +8,7 @@ "url":{ "paths":[ { - "path":"/_scripts/{id}", + "path":"/_script/{id}", "methods":[ "PUT", "POST" @@ -21,7 +21,7 @@ } }, { - "path":"/_scripts/{id}/{context}", + "path":"/_script/{id}/{context}", "methods":[ "PUT", "POST" diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java index f27c14cc8fb0a..c6fe5a26c813c 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java @@ -21,6 +21,7 @@ import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.support.master.MasterNodeReadRequest; +import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; @@ -30,54 +31,73 @@ public class GetStoredScriptRequest extends MasterNodeReadRequest { - protected String id; + private String[] names; - GetStoredScriptRequest() { - super(); + public GetStoredScriptRequest() { + this(new String[]{}); } - public GetStoredScriptRequest(String id) { - super(); - - this.id = id; + public GetStoredScriptRequest(String... names) { + this.names = names; } public GetStoredScriptRequest(StreamInput in) throws IOException { super(in); - id = in.readString(); + names = in.readStringArray(); + } + + /** + * Returns he names of the scripts. + */ + public String[] names() { + return this.names; + } + + /** + * @deprecated - Needed for backwards compatibility. + * Use {@link #names()} instead + * + * Return the script if there is only one defined, null otherwise + */ + @Deprecated + public String id() { + return names != null && names.length == 1 ? names[0] : null; + } + + /** + * @deprecated - Needed for backwards compatibility. + * Set the script names param instead + */ + @Deprecated + public GetStoredScriptRequest id(String id) { + this.names = new String[] { id }; + + return this; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); - out.writeString(id); + out.writeStringArray(names); } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; - - if (id == null || id.isEmpty()) { - validationException = addValidationError("must specify id for stored script", validationException); - } else if (id.contains("#")) { - validationException = addValidationError("id cannot contain '#' for stored script", validationException); + if (names == null) { + validationException = addValidationError("names is null or empty", validationException); + } else { + for (String name : names) { + if (name == null || !Strings.hasText(name)) { + validationException = addValidationError("name is missing", validationException); + } + } } - return validationException; } - public String id() { - return id; - } - - public GetStoredScriptRequest id(String id) { - this.id = id; - - return this; - } - @Override public String toString() { - return "get script [" + id + "]"; + return "get script"; } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java index 15e96aca88049..76d8d692f092e 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java @@ -25,11 +25,14 @@ public class GetStoredScriptRequestBuilder extends MasterNodeReadOperationRequestBuilder { - public GetStoredScriptRequestBuilder(ElasticsearchClient client, GetStoredScriptAction action) { super(client, action, new GetStoredScriptRequest()); } + public GetStoredScriptRequestBuilder(ElasticsearchClient client, GetStoredScriptAction action, String... names) { + super(client, action, new GetStoredScriptRequest(names)); + } + public GetStoredScriptRequestBuilder setId(String id) { request.id(id); return this; diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java index e0058bba953f0..c242b8e52ada9 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java @@ -25,19 +25,20 @@ import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.ConstructingObjectParser; import org.elasticsearch.common.xcontent.ObjectParser; -import org.elasticsearch.common.xcontent.StatusToXContentObject; +import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.rest.RestStatus; import org.elasticsearch.script.StoredScriptSource; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import java.util.Objects; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg; -public class GetStoredScriptResponse extends ActionResponse implements StatusToXContentObject { +public class GetStoredScriptResponse extends ActionResponse implements ToXContentObject { public static final ParseField _ID_PARSE_FIELD = new ParseField("_id"); public static final ParseField FOUND_PARSE_FIELD = new ParseField("found"); @@ -62,69 +63,96 @@ public class GetStoredScriptResponse extends ActionResponse implements StatusToX SCRIPT, ObjectParser.ValueType.OBJECT); } - private String id; - private StoredScriptSource source; + private Map storedScripts; - public GetStoredScriptResponse(StreamInput in) throws IOException { + GetStoredScriptResponse(StreamInput in) throws IOException { super(in); - if (in.readBoolean()) { - source = new StoredScriptSource(in); - } else { - source = null; + int size = in.readVInt(); + storedScripts = new HashMap<>(size); + for (int i = 0 ; i < size ; i++) { + String id = in.readString(); + storedScripts.put(id, new StoredScriptSource(in)); } - id = in.readString(); } GetStoredScriptResponse(String id, StoredScriptSource source) { - this.id = id; - this.source = source; + this.storedScripts = new HashMap<>(); + storedScripts.put(id, source); + } + + GetStoredScriptResponse(Map storedScripts) { + this.storedScripts = storedScripts; } - public String getId() { - return id; + public Map getStoredScripts() { + return storedScripts; } /** + * @deprecated - Needed for backwards compatibility. + * Use {@link #getStoredScripts()} instead + * * @return if a stored script and if not found null */ + @Deprecated public StoredScriptSource getSource() { - return source; - } - - @Override - public RestStatus status() { - return source != null ? RestStatus.OK : RestStatus.NOT_FOUND; + if (storedScripts != null && storedScripts.size() == 1) { + return storedScripts.entrySet().iterator().next().getValue(); + } else { + return null; + } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { +// ScriptMetaData scriptMetaData = new ScriptMetaData(getStoredScripts()); +// return scriptMetaData.toXContent(builder, params); builder.startObject(); - builder.field(_ID_PARSE_FIELD.getPreferredName(), id); - builder.field(FOUND_PARSE_FIELD.getPreferredName(), source != null); - if (source != null) { - builder.field(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); - source.toXContent(builder, params); + Map storedScripts = getStoredScripts(); + if (storedScripts != null) { + for (Map.Entry storedScript : storedScripts.entrySet()) { + builder.startObject(storedScript.getKey()); + builder.field(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); + storedScript.getValue().toXContent(builder, params); + builder.endObject(); + } } - builder.endObject(); return builder; } public static GetStoredScriptResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); + final Map storedScripts = new HashMap<>(); + for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) { + if (token == XContentParser.Token.FIELD_NAME) { + String name = parser.currentName(); + parser.nextToken(); + parser.nextToken(); + StoredScriptSource storedScriptSource = StoredScriptSource.fromXContent(parser, false); + storedScripts.put(name, storedScriptSource); + } + } + return new GetStoredScriptResponse(storedScripts); } +// public static GetStoredScriptResponse fromXContent(XContentParser parser) throws IOException { +// return PARSER.parse(parser, null); +// } + @Override public void writeTo(StreamOutput out) throws IOException { - if (source == null) { - out.writeBoolean(false); - } else { - out.writeBoolean(true); - source.writeTo(out); + if (storedScripts == null ) { + out.writeVInt(0); + return; + } + + out.writeVInt(storedScripts.size()); + for (Map.Entry storedScript : storedScripts.entrySet()) { + out.writeString(storedScript.getKey()); + storedScript.getValue().writeTo(out); } - out.writeString(id); } @Override @@ -132,12 +160,11 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GetStoredScriptResponse that = (GetStoredScriptResponse) o; - return Objects.equals(id, that.id) && - Objects.equals(source, that.source); + return Objects.equals(storedScripts, that.storedScripts); } @Override public int hashCode() { - return Objects.hash(id, source); + return storedScripts.hashCode(); } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java deleted file mode 100644 index debe140d66c51..0000000000000 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ - -package org.elasticsearch.action.admin.cluster.storedscripts; - -import org.elasticsearch.action.ActionType; - -public class GetStoredScriptsAction extends ActionType { - - public static final GetStoredScriptsAction INSTANCE = new GetStoredScriptsAction(); - public static final String NAME = "cluster:admin/scripts/get"; - - private GetStoredScriptsAction() { - super(NAME, GetStoredScriptsResponse::new); - } -} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java deleted file mode 100644 index c97f8610de5ad..0000000000000 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ - -package org.elasticsearch.action.admin.cluster.storedscripts; - -import org.elasticsearch.action.ActionRequestValidationException; -import org.elasticsearch.action.support.master.MasterNodeReadRequest; -import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.common.io.stream.StreamOutput; - -import java.io.IOException; - -public class GetStoredScriptsRequest extends MasterNodeReadRequest { - - private String[] names; - - public GetStoredScriptsRequest() { - super(); - } - - public GetStoredScriptsRequest(String... names) { - this.names = names; - } - - public GetStoredScriptsRequest(StreamInput in) throws IOException { - super(in); - names = in.readStringArray(); - } - - /** - * The names of the search templates. - */ - public String[] names() { - return this.names; - } - - /** - * @deprecated - Needed for backwards compatibility. - * * Use {@link #names()} instead - */ - @Deprecated - public String id() { - return names != null && names.length == 1 ? names[0] : null; - } - - @Override - public void writeTo(StreamOutput out) throws IOException { - super.writeTo(out); - out.writeStringArray(names); - } - - @Override - public ActionRequestValidationException validate() { - return null; - } - - @Override - public String toString() { - return "get scripts"; - } - -} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java deleted file mode 100644 index a2522ceb68b3c..0000000000000 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ - -package org.elasticsearch.action.admin.cluster.storedscripts; - -import org.elasticsearch.action.support.master.MasterNodeReadOperationRequestBuilder; -import org.elasticsearch.client.ElasticsearchClient; - -public class GetStoredScriptsRequestBuilder extends - MasterNodeReadOperationRequestBuilder { - - public GetStoredScriptsRequestBuilder(ElasticsearchClient client, GetStoredScriptsAction action) { - super(client, action, new GetStoredScriptsRequest()); - } - - public GetStoredScriptsRequestBuilder(ElasticsearchClient client, GetStoredScriptsAction action, String... names) { - super(client, action, new GetStoredScriptsRequest(names)); - } -} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java deleted file mode 100644 index 50437902d03bf..0000000000000 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ - -package org.elasticsearch.action.admin.cluster.storedscripts; - -import org.elasticsearch.action.ActionResponse; -import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.common.xcontent.ToXContentObject; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.script.StoredScriptSource; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -public class GetStoredScriptsResponse extends ActionResponse implements ToXContentObject { - - private Map storedScripts; - - GetStoredScriptsResponse(StreamInput in) throws IOException { - super(in); - - int size = in.readVInt(); - storedScripts = new HashMap<>(size); - for (int i = 0 ; i < size ; i++) { - String id = in.readString(); - storedScripts.put(id, new StoredScriptSource(in)); - } - } - - GetStoredScriptsResponse(Map storedScripts) { - this.storedScripts = storedScripts; - } - - public Map getStoredScripts() { - return storedScripts; - } - - /** - * @deprecated - Needed for backwards compatibility. - * Use {@link #getStoredScripts()} instead - * - * @return if a stored script and if not found null - */ - @Deprecated - public StoredScriptSource getSource() { - if (storedScripts != null && storedScripts.size() == 1) { - return storedScripts.entrySet().iterator().next().getValue(); - } else { - return null; - } - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - - Map storedScripts = getStoredScripts(); - if (storedScripts != null) { - for (Map.Entry storedScript : storedScripts.entrySet()) { - builder.startObject(storedScript.getKey()); - builder.field(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); - storedScript.getValue().toXContent(builder, params); - builder.endObject(); - } - } - builder.endObject(); - return builder; - } - - @Override - public void writeTo(StreamOutput out) throws IOException { - if (storedScripts == null ) { - out.writeVInt(0); - return; - } - - out.writeVInt(storedScripts.size()); - for (Map.Entry storedScript : storedScripts.entrySet()) { - out.writeString(storedScript.getKey()); - storedScript.getValue().writeTo(out); - } - } -} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java index 4de6dfef713dc..1a516309fbc8e 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java @@ -29,12 +29,16 @@ import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.regex.Regex; import org.elasticsearch.script.ScriptService; +import org.elasticsearch.script.StoredScriptSource; import org.elasticsearch.tasks.Task; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; public class TransportGetStoredScriptAction extends TransportMasterNodeReadAction { @@ -63,7 +67,36 @@ protected GetStoredScriptResponse read(StreamInput in) throws IOException { @Override protected void masterOperation(Task task, GetStoredScriptRequest request, ClusterState state, ActionListener listener) throws Exception { - listener.onResponse(new GetStoredScriptResponse(request.id(), scriptService.getStoredScript(state, request))); + if (request.id() != null) { + listener.onResponse(new GetStoredScriptResponse(scriptService.getStoredScripts(state))); + return; + } + + Map results; + + Map storedScripts = scriptService.getStoredScripts(state); + // If we did not ask for a specific name, then we return all templates + if (request.names().length == 0) { + results = storedScripts; + } else { + results = new HashMap<>(); + } + + if (storedScripts != null) { + for (String name : request.names()) { + if (Regex.isSimpleMatchPattern(name)) { + for (Map.Entry entry : storedScripts.entrySet()) { + if (Regex.simpleMatch(name, entry.getKey())) { + results.put(entry.getKey(), entry.getValue()); + } + } + } else if (storedScripts.containsKey(name)) { + results.put(name, storedScripts.get(name)); + } + } + } + + listener.onResponse(new GetStoredScriptResponse(results)); } @Override diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java deleted file mode 100644 index b2dea0f921ff8..0000000000000 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ - -package org.elasticsearch.action.admin.cluster.storedscripts; - -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.support.ActionFilters; -import org.elasticsearch.action.support.master.TransportMasterNodeReadAction; -import org.elasticsearch.cluster.ClusterState; -import org.elasticsearch.cluster.block.ClusterBlockException; -import org.elasticsearch.cluster.block.ClusterBlockLevel; -import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; -import org.elasticsearch.cluster.service.ClusterService; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.common.regex.Regex; -import org.elasticsearch.script.ScriptService; -import org.elasticsearch.script.StoredScriptSource; -import org.elasticsearch.tasks.Task; -import org.elasticsearch.threadpool.ThreadPool; -import org.elasticsearch.transport.TransportService; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -public class TransportGetStoredScriptsAction extends TransportMasterNodeReadAction { - - private final ScriptService scriptService; - - @Inject - public TransportGetStoredScriptsAction(TransportService transportService, ClusterService clusterService, - ThreadPool threadPool, ActionFilters actionFilters, - IndexNameExpressionResolver indexNameExpressionResolver, ScriptService scriptService) { - super(GetStoredScriptsAction.NAME, transportService, clusterService, threadPool, actionFilters, - GetStoredScriptsRequest::new, indexNameExpressionResolver); - this.scriptService = scriptService; - } - - @Override - protected String executor() { - return ThreadPool.Names.SAME; - } - - @Override - protected GetStoredScriptsResponse read(StreamInput in) throws IOException { - return new GetStoredScriptsResponse(in); - } - - @Override - protected void masterOperation(Task task, GetStoredScriptsRequest request, ClusterState state, - ActionListener listener) throws Exception { - if (request.id() != null) { - listener.onResponse(new GetStoredScriptsResponse(scriptService.getStoredScripts(state))); - return; - } - - Map results; - - Map storedScripts = scriptService.getStoredScripts(state); - // If we did not ask for a specific name, then we return all templates - if (request.names().length == 0) { - results = storedScripts; - } else { - results = new HashMap<>(); - } - - if (storedScripts != null) { - for (String name : request.names()) { - if (Regex.isSimpleMatchPattern(name)) { - for (Map.Entry entry : storedScripts.entrySet()) { - if (Regex.simpleMatch(name, entry.getKey())) { - results.put(entry.getKey(), entry.getValue()); - } - } - } else if (storedScripts.containsKey(name)) { - results.put(name, storedScripts.get(name)); - } - } - } - - listener.onResponse(new GetStoredScriptsResponse(results)); - } - - @Override - protected ClusterBlockException checkBlock(GetStoredScriptsRequest request, ClusterState state) { - return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); - } - -} diff --git a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java index f6c9ce09d07a4..25c4c19cdbc8e 100644 --- a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java +++ b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java @@ -96,9 +96,6 @@ import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequestBuilder; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequestBuilder; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequestBuilder; import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksRequest; @@ -710,36 +707,21 @@ public interface ClusterAdminClient extends ElasticsearchClient { /** * Get a script from the cluster state */ + @Deprecated GetStoredScriptRequestBuilder prepareGetStoredScript(String id); /** - * Get a script from the cluster state + * Get scripts from the cluster state */ - void getStoredScript(GetStoredScriptRequest request, ActionListener listener); + GetStoredScriptRequestBuilder prepareGetStoredScript(String... name); /** * Get a script from the cluster state */ - ActionFuture getStoredScript(GetStoredScriptRequest request); + void getStoredScript(GetStoredScriptRequest request, ActionListener listener); /** * Get a script from the cluster state */ - @Deprecated - GetStoredScriptsRequestBuilder prepareGetStoredScripts(String id); - - /** - * Get scripts from the cluster state - */ - GetStoredScriptsRequestBuilder prepareGetStoredScripts(String... name); - - /** - * Get all scripts from the cluster state - */ - void getStoredScripts(GetStoredScriptsRequest request, ActionListener listener); - - /** - * Get all scripts from the cluster state - */ - ActionFuture getStoredScripts(GetStoredScriptsRequest request); + ActionFuture getStoredScript(GetStoredScriptRequest request); } diff --git a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java index 73972ba712d2e..3f26b205c67db 100644 --- a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java +++ b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java @@ -128,10 +128,6 @@ import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequestBuilder; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsAction; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequestBuilder; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptAction; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequestBuilder; @@ -1164,25 +1160,8 @@ public GetStoredScriptRequestBuilder prepareGetStoredScript(String id) { } @Override - @Deprecated - public GetStoredScriptsRequestBuilder prepareGetStoredScripts(String id) { - return prepareGetStoredScripts(new String[]{id}); - } - - @Override - public ActionFuture getStoredScripts(GetStoredScriptsRequest request) { - return execute(GetStoredScriptsAction.INSTANCE, request); - } - - @Override - public void getStoredScripts(GetStoredScriptsRequest request, - ActionListener listener) { - execute(GetStoredScriptsAction.INSTANCE, request, listener); - } - - @Override - public GetStoredScriptsRequestBuilder prepareGetStoredScripts(String... names) { - return new GetStoredScriptsRequestBuilder(this, GetStoredScriptsAction.INSTANCE, names); + public GetStoredScriptRequestBuilder prepareGetStoredScript(String... names) { + return new GetStoredScriptRequestBuilder(this, GetStoredScriptAction.INSTANCE, names); } @Override diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java index a0258974cfc41..05bcd4e19038c 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java @@ -18,8 +18,11 @@ */ package org.elasticsearch.rest.action.admin.cluster; +import org.apache.logging.log4j.LogManager; import org.elasticsearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest; import org.elasticsearch.client.node.NodeClient; +import org.elasticsearch.common.logging.DeprecationLogger; +import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; @@ -31,8 +34,12 @@ public class RestDeleteStoredScriptAction extends BaseRestHandler { + private static final DeprecationLogger deprecationLogger = + new DeprecationLogger(LogManager.getLogger(RestGetStoredScriptAction.class)); + public RestDeleteStoredScriptAction(RestController controller) { - controller.registerHandler(DELETE, "/_scripts/{id}", this); + controller.registerWithDeprecatedHandler(DELETE, "/_script/{id}", this, + DELETE, "/_scripts/{id}", deprecationLogger); } @Override diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java index f87c6f513b79c..9f4543e09c1ce 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java @@ -18,21 +18,38 @@ */ package org.elasticsearch.rest.action.admin.cluster; +import org.apache.logging.log4j.LogManager; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequest; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse; import org.elasticsearch.client.node.NodeClient; +import org.elasticsearch.common.Strings; +import org.elasticsearch.common.logging.DeprecationLogger; +import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; -import org.elasticsearch.rest.action.RestStatusToXContentListener; +import org.elasticsearch.rest.RestStatus; +import org.elasticsearch.rest.action.RestToXContentListener; +import org.elasticsearch.script.StoredScriptSource; import java.io.IOException; +import java.util.Map; import static org.elasticsearch.rest.RestRequest.Method.GET; +import static org.elasticsearch.rest.RestRequest.Method.HEAD; +import static org.elasticsearch.rest.RestStatus.NOT_FOUND; +import static org.elasticsearch.rest.RestStatus.OK; public class RestGetStoredScriptAction extends BaseRestHandler { + private static final DeprecationLogger deprecationLogger = + new DeprecationLogger(LogManager.getLogger(RestGetStoredScriptAction.class)); + public RestGetStoredScriptAction(RestController controller) { - controller.registerHandler(GET, "/_scripts/{id}", this); + controller.registerHandler(GET, "/_script", this); + controller.registerWithDeprecatedHandler(GET, "/_script/{name}", this, + GET, "/_scripts/{name}", deprecationLogger); + controller.registerHandler(HEAD, "/_script/{name}", this); } @Override @@ -42,9 +59,21 @@ public String getName() { @Override public RestChannelConsumer prepareRequest(final RestRequest request, NodeClient client) throws IOException { - String id = request.param("id"); - GetStoredScriptRequest getRequest = new GetStoredScriptRequest(id); + final String[] names = Strings.splitStringByCommaToArray(request.param("name")); + + GetStoredScriptRequest getRequest = new GetStoredScriptRequest(names); getRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRequest.masterNodeTimeout())); - return channel -> client.admin().cluster().getStoredScript(getRequest, new RestStatusToXContentListener<>(channel)); + + final boolean implicitAll = getRequest.names().length == 0; + + return channel -> client.admin().cluster().getStoredScript(getRequest, new RestToXContentListener<>(channel) { + @Override + protected RestStatus getStatus(final GetStoredScriptResponse response) + { + Map storedScripts = response.getStoredScripts(); + final boolean templateExists = storedScripts != null && !storedScripts.isEmpty(); + return (templateExists || implicitAll) ? OK : NOT_FOUND; + } + }); } } diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java deleted file mode 100644 index 5e272ae5ba1e1..0000000000000 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ -package org.elasticsearch.rest.action.admin.cluster; - -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; -import org.elasticsearch.client.node.NodeClient; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.rest.BaseRestHandler; -import org.elasticsearch.rest.RestController; -import org.elasticsearch.rest.RestRequest; -import org.elasticsearch.rest.RestStatus; -import org.elasticsearch.rest.action.RestToXContentListener; -import org.elasticsearch.script.StoredScriptSource; - -import java.io.IOException; -import java.util.Map; - -import static org.elasticsearch.rest.RestRequest.Method.GET; -import static org.elasticsearch.rest.RestRequest.Method.HEAD; -import static org.elasticsearch.rest.RestStatus.NOT_FOUND; -import static org.elasticsearch.rest.RestStatus.OK; - -public class RestGetStoredScriptsAction extends BaseRestHandler { - - public RestGetStoredScriptsAction(Settings settings, RestController controller) { - super(settings); - - controller.registerHandler(GET, "/_scripts", this); - controller.registerHandler(GET, "/_script/{name}", this); - controller.registerHandler(HEAD, "/_script/{name}", this); - } - - @Override - public String getName() { - return "get_all_stored_scripts_action"; - } - - @Override - public RestChannelConsumer prepareRequest(final RestRequest request, NodeClient client) throws IOException { - final String[] names = Strings.splitStringByCommaToArray(request.param("name")); - - GetStoredScriptsRequest getRequest = new GetStoredScriptsRequest(names); - getRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRequest.masterNodeTimeout())); - - final boolean implicitAll = getRequest.names().length == 0; - - return channel -> client.admin().cluster().getStoredScripts(getRequest, new RestToXContentListener<>(channel) { - @Override - protected RestStatus getStatus(final GetStoredScriptsResponse response) - { - Map storedScripts = response.getStoredScripts(); - final boolean templateExists = storedScripts != null && !storedScripts.isEmpty(); - return (templateExists || implicitAll) ? OK : NOT_FOUND; - } - }); - } -} diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java index 2e316abc14296..b86f81e46766a 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java @@ -18,9 +18,12 @@ */ package org.elasticsearch.rest.action.admin.cluster; +import org.apache.logging.log4j.LogManager; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequest; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.bytes.BytesReference; +import org.elasticsearch.common.logging.DeprecationLogger; +import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; @@ -35,11 +38,18 @@ public class RestPutStoredScriptAction extends BaseRestHandler { + private static final DeprecationLogger deprecationLogger = + new DeprecationLogger(LogManager.getLogger(RestGetStoredScriptAction.class)); + public RestPutStoredScriptAction(RestController controller) { - controller.registerHandler(POST, "/_scripts/{id}", this); - controller.registerHandler(PUT, "/_scripts/{id}", this); - controller.registerHandler(POST, "/_scripts/{id}/{context}", this); - controller.registerHandler(PUT, "/_scripts/{id}/{context}", this); + controller.registerWithDeprecatedHandler(POST, "/_script/{id}", this, + POST, "/_scripts/{id}", deprecationLogger); + controller.registerWithDeprecatedHandler(PUT, "/_script/{id}", this, + PUT, "/_scripts/{id}", deprecationLogger); + controller.registerWithDeprecatedHandler(POST, "/_script/{id}/{context}", this, + POST, "/_scripts/{id}/{context}", deprecationLogger); + controller.registerWithDeprecatedHandler(PUT, "/_script/{id}/{context}", this, + PUT, "/_scripts/{id}/{context}", deprecationLogger); } @Override diff --git a/server/src/main/java/org/elasticsearch/script/ScriptService.java b/server/src/main/java/org/elasticsearch/script/ScriptService.java index 1425b8746ad6e..b1258b74b0c35 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptService.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptService.java @@ -548,7 +548,6 @@ public Map getStoredScripts(ClusterState state) { } } - public ScriptStats stats() { return scriptMetrics.stats(); } diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java index 8bea7fecc571a..5bd6e64cec2fd 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java @@ -26,6 +26,7 @@ import java.io.IOException; import java.util.Collections; +import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; @@ -38,7 +39,10 @@ protected GetStoredScriptResponse doParseInstance(XContentParser parser) throws @Override protected GetStoredScriptResponse createTestInstance() { - return new GetStoredScriptResponse(randomAlphaOfLengthBetween(1, 10), randomScriptSource()); + Map storedScripts = new HashMap<>(); + storedScripts.put(randomAlphaOfLengthBetween(1, 10), randomScriptSource()); + + return new GetStoredScriptResponse(storedScripts); } @Override diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java deleted file mode 100644 index 4c2dd2b617152..0000000000000 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ - -package org.elasticsearch.action.admin.cluster.storedscripts; - -import org.elasticsearch.common.io.stream.BytesStreamOutput; -import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.test.ESTestCase; - -import java.io.IOException; - -import static org.elasticsearch.test.VersionUtils.randomVersion; -import static org.hamcrest.CoreMatchers.equalTo; - -public class GetStoredScriptsRequestTests extends ESTestCase { - public void testGetIndexedScriptsRequestSerialization() throws IOException { - GetStoredScriptsRequest request = new GetStoredScriptsRequest(); - - BytesStreamOutput out = new BytesStreamOutput(); - out.setVersion(randomVersion(random())); - request.writeTo(out); - - StreamInput in = out.bytes().streamInput(); - in.setVersion(out.getVersion()); - GetStoredScriptsRequest request2 = new GetStoredScriptsRequest(in); - - assertThat(request2, equalTo(request)); - } -} diff --git a/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java b/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java index 3f0f1801735bd..a2771a1c00c3d 100644 --- a/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java +++ b/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java @@ -18,6 +18,7 @@ */ package org.elasticsearch.script; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentType; @@ -53,16 +54,15 @@ public void testBasics() { assertAcked(client().admin().cluster().preparePutStoredScript() .setId("foobar") .setContent(new BytesArray("{\"script\": {\"lang\": \"" + LANG + "\", \"source\": \"1\"} }"), XContentType.JSON)); - String script = client().admin().cluster().prepareGetStoredScript("foobar") - .get().getSource().getSource(); + String script = client().admin().cluster().prepareGetStoredScript("foobar").get().getSource().getSource(); assertNotNull(script); assertEquals("1", script); assertAcked(client().admin().cluster().prepareDeleteStoredScript() .setId("foobar")); - StoredScriptSource source = client().admin().cluster().prepareGetStoredScript("foobar") - .get().getSource(); - assertNull(source); + GetStoredScriptResponse response = client().admin().cluster().prepareGetStoredScript("foobar") + .get(); + assertEquals(0, response.getStoredScripts().size()); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> client().admin().cluster().preparePutStoredScript() .setId("id#") @@ -81,7 +81,7 @@ public void testGetAllScripts() { .setContent(new BytesArray("{\"script\": {\"lang\": \"" + LANG + "\", \"source\": \"9.9\"} }"), XContentType.JSON)); - Map storedScripts = client().admin().cluster().prepareGetStoredScripts().get().getStoredScripts(); + Map storedScripts = client().admin().cluster().prepareGetStoredScript().get().getStoredScripts(); assertEquals(2, storedScripts.size()); StoredScriptSource source = storedScripts.get("foobar"); From 2702d6b7bf3dac264d8ee4987056515389ab6cf2 Mon Sep 17 00:00:00 2001 From: ivan Date: Wed, 14 Aug 2019 21:39:27 -0700 Subject: [PATCH 06/28] Change all /_scripts references to /_script --- .../client/RequestConvertersTests.java | 6 ++-- .../documentation/CRUDDocumentationIT.java | 2 +- .../documentation/SearchDocumentationIT.java | 2 +- .../StoredScriptsDocumentationIT.java | 12 +++---- .../test/rest/RequestsWithoutContentIT.java | 2 +- .../bucket/range-aggregation.asciidoc | 2 +- .../bucket/terms-aggregation.asciidoc | 2 +- docs/reference/scripting/using.asciidoc | 10 +++--- docs/reference/search/multi-search.asciidoc | 4 +-- .../reference/search/search-template.asciidoc | 12 +++---- .../test/painless/16_update2.yml | 6 +--- .../test/painless/70_get_all.yml | 4 +-- .../rest-api-spec/api/get_script.json | 20 +++++++++++ .../GetStoredScriptResponse.java | 35 ++++++++++++++----- .../TransportGetStoredScriptAction.java | 5 --- .../cluster/RestDeleteStoredScriptAction.java | 1 - .../cluster/RestGetStoredScriptAction.java | 9 +++-- .../cluster/RestPutStoredScriptAction.java | 1 - 18 files changed, 80 insertions(+), 55 deletions(-) diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/RequestConvertersTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/RequestConvertersTests.java index 8ec5bd1d57c0a..ff8f0d606b7b4 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/RequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/RequestConvertersTests.java @@ -1612,7 +1612,7 @@ public void testPutScript() throws Exception { Request request = RequestConverters.putScript(putStoredScriptRequest); - assertThat(request.getEndpoint(), equalTo("/_scripts/" + id)); + assertThat(request.getEndpoint(), equalTo("/_script/" + id)); assertThat(request.getParameters(), equalTo(expectedParams)); assertNotNull(request.getEntity()); assertToXContentBody(putStoredScriptRequest, request.getEntity()); @@ -1636,7 +1636,7 @@ public void testGetScriptRequest() { setRandomMasterTimeout(getStoredScriptRequest, expectedParams); Request request = RequestConverters.getScript(getStoredScriptRequest); - assertThat(request.getEndpoint(), equalTo("/_scripts/" + getStoredScriptRequest.id())); + assertThat(request.getEndpoint(), equalTo("/_script/" + getStoredScriptRequest.id())); assertThat(request.getMethod(), equalTo(HttpGet.METHOD_NAME)); assertThat(request.getParameters(), equalTo(expectedParams)); assertThat(request.getEntity(), nullValue()); @@ -1650,7 +1650,7 @@ public void testDeleteScriptRequest() { setRandomMasterTimeout(deleteStoredScriptRequest, expectedParams); Request request = RequestConverters.deleteScript(deleteStoredScriptRequest); - assertThat(request.getEndpoint(), equalTo("/_scripts/" + deleteStoredScriptRequest.id())); + assertThat(request.getEndpoint(), equalTo("/_script/" + deleteStoredScriptRequest.id())); assertThat(request.getMethod(), equalTo(HttpDelete.METHOD_NAME)); assertThat(request.getParameters(), equalTo(expectedParams)); assertThat(request.getEntity(), nullValue()); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/CRUDDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/CRUDDocumentationIT.java index 062f90c0eb4db..30fb908590fb9 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/CRUDDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/CRUDDocumentationIT.java @@ -284,7 +284,7 @@ public void testUpdate() throws Exception { IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT); assertSame(RestStatus.CREATED, indexResponse.status()); - Request request = new Request("POST", "/_scripts/increment-field"); + Request request = new Request("POST", "/_script/increment-field"); request.setJsonEntity(Strings.toString(JsonXContent.contentBuilder() .startObject() .startObject("script") diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SearchDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SearchDocumentationIT.java index ff5deb5cbdfcc..fd80446863ce2 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SearchDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SearchDocumentationIT.java @@ -962,7 +962,7 @@ public void onFailure(Exception e) { protected void registerQueryScript(RestClient restClient) throws IOException { // tag::register-script - Request scriptRequest = new Request("POST", "_scripts/title_search"); + Request scriptRequest = new Request("POST", "_script/title_search"); scriptRequest.setJsonEntity( "{" + " \"script\": {" + diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java index ac4f2269f9c79..f980d6f0a02eb 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java @@ -103,7 +103,7 @@ public void testGetStoredScript() throws Exception { // tag::get-stored-script-execute-listener ActionListener listener = - new ActionListener() { + new ActionListener<>() { @Override public void onResponse(GetStoredScriptResponse response) { // <1> @@ -166,7 +166,7 @@ public void testDeleteStoredScript() throws Exception { // tag::delete-stored-script-execute-listener ActionListener listener = - new ActionListener() { + new ActionListener<>() { @Override public void onResponse(AcknowledgedResponse response) { // <1> @@ -254,7 +254,7 @@ public void testPutScript() throws Exception { // tag::put-stored-script-execute-listener ActionListener listener = - new ActionListener() { + new ActionListener<>() { @Override public void onResponse(AcknowledgedResponse response) { // <1> @@ -299,9 +299,9 @@ public void onFailure(Exception e) { client.putScript(request, RequestOptions.DEFAULT); - Map script = getAsMap("/_scripts/id"); - assertThat(extractValue("script.lang", script), equalTo("mustache")); - assertThat(extractValue("script.source", script), equalTo("{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}")); + Map script = getAsMap("/_script/id"); + assertThat(extractValue("id.script.lang", script), equalTo("mustache")); + assertThat(extractValue("id.script.source", script), equalTo("{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}")); } } diff --git a/distribution/archives/integ-test-zip/src/test/java/org/elasticsearch/test/rest/RequestsWithoutContentIT.java b/distribution/archives/integ-test-zip/src/test/java/org/elasticsearch/test/rest/RequestsWithoutContentIT.java index 4d27f156b3826..f8ada87df5acd 100644 --- a/distribution/archives/integ-test-zip/src/test/java/org/elasticsearch/test/rest/RequestsWithoutContentIT.java +++ b/distribution/archives/integ-test-zip/src/test/java/org/elasticsearch/test/rest/RequestsWithoutContentIT.java @@ -78,7 +78,7 @@ public void testSimulatePipelineMissingBody() throws IOException { public void testPutScriptMissingBody() throws IOException { ResponseException responseException = expectThrows(ResponseException.class, () -> - client().performRequest(new Request(randomBoolean() ? "POST" : "PUT", "/_scripts/lang"))); + client().performRequest(new Request(randomBoolean() ? "POST" : "PUT", "/_script/lang"))); assertResponseException(responseException, "request body is required"); } diff --git a/docs/reference/aggregations/bucket/range-aggregation.asciidoc b/docs/reference/aggregations/bucket/range-aggregation.asciidoc index 8ff26c7c92f5c..f5c844359ab8a 100644 --- a/docs/reference/aggregations/bucket/range-aggregation.asciidoc +++ b/docs/reference/aggregations/bucket/range-aggregation.asciidoc @@ -204,7 +204,7 @@ It is also possible to use stored scripts. Here is a simple stored script: [source,js] -------------------------------------------------- -POST /_scripts/convert_currency +POST /_script/convert_currency { "script": { "lang": "painless", diff --git a/docs/reference/aggregations/bucket/terms-aggregation.asciidoc b/docs/reference/aggregations/bucket/terms-aggregation.asciidoc index b40302b6120e9..a29f8ab92073f 100644 --- a/docs/reference/aggregations/bucket/terms-aggregation.asciidoc +++ b/docs/reference/aggregations/bucket/terms-aggregation.asciidoc @@ -572,7 +572,7 @@ This will interpret the `script` parameter as an `inline` script with the defaul [source,js] -------------------------------------------------- -POST /_scripts/my_script +POST /_script/my_script { "script": { "lang": "painless", diff --git a/docs/reference/scripting/using.asciidoc b/docs/reference/scripting/using.asciidoc index 5060c7fc67d2f..e95f50b4419ce 100644 --- a/docs/reference/scripting/using.asciidoc +++ b/docs/reference/scripting/using.asciidoc @@ -134,19 +134,19 @@ The same script in the normal form: === Stored scripts Scripts may be stored in and retrieved from the cluster state using the -`_scripts` end-point. +`_script` end-point. [float] ==== Request examples The following are examples of using a stored script that lives at -`/_scripts/{id}`. +`/_script/{id}`. First, create the script called `calculate-score` in the cluster state: [source,js] ----------------------------------- -POST _scripts/calculate-score +POST _script/calculate-score { "script": { "lang": "painless", @@ -160,7 +160,7 @@ This same script can be retrieved with: [source,js] ----------------------------------- -GET _scripts/calculate-score +GET _script/calculate-score ----------------------------------- // CONSOLE // TEST[continued] @@ -190,7 +190,7 @@ And deleted with: [source,js] ----------------------------------- -DELETE _scripts/calculate-score +DELETE _script/calculate-score ----------------------------------- // CONSOLE // TEST[continued] diff --git a/docs/reference/search/multi-search.asciidoc b/docs/reference/search/multi-search.asciidoc index 42dbd0f5c2a1a..cf4a6968072de 100644 --- a/docs/reference/search/multi-search.asciidoc +++ b/docs/reference/search/multi-search.asciidoc @@ -126,7 +126,7 @@ You can also create search templates: [source,js] ------------------------------------------ -POST /_scripts/my_template_1 +POST /_script/my_template_1 { "script": { "lang": "mustache", @@ -145,7 +145,7 @@ POST /_scripts/my_template_1 [source,js] ------------------------------------------ -POST /_scripts/my_template_2 +POST /_script/my_template_2 { "script": { "lang": "mustache", diff --git a/docs/reference/search/search-template.asciidoc b/docs/reference/search/search-template.asciidoc index 950477aa7d320..570ab0a7a25d3 100644 --- a/docs/reference/search/search-template.asciidoc +++ b/docs/reference/search/search-template.asciidoc @@ -42,7 +42,7 @@ You can store a search template using the stored scripts API. [source,js] ------------------------------------------ -POST _scripts/ +POST _script/ { "script": { "lang": "mustache", @@ -78,7 +78,7 @@ This template can be retrieved by [source,js] ------------------------------------------ -GET _scripts/ +GET _script/ ------------------------------------------ // CONSOLE // TEST[continued] @@ -88,15 +88,13 @@ which is rendered as: [source,js] ------------------------------------------ { - "script" : { + "" : { "lang" : "mustache", "source" : "{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}", "options": { "content_type" : "application/json; charset=UTF-8" } - }, - "_id": "", - "found": true + } } ------------------------------------------ // TESTRESPONSE @@ -105,7 +103,7 @@ This template can be deleted by [source,js] ------------------------------------------ -DELETE _scripts/ +DELETE _script/ ------------------------------------------ // CONSOLE // TEST[continued] diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml index 999733ff14be7..4a6bc23bf1947 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml @@ -12,16 +12,12 @@ - do: get_script: id: "1" - - match: { found: true } - - match: { _id: "1" } - - match: { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } + - match: { "1" : { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } } - do: catch: missing get_script: id: "2" - - match: { found: false } - - match: { _id: "2" } - is_false: script - do: diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml index 7f9b00f6c2ca1..a92674c754e5b 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml @@ -2,8 +2,8 @@ "Get all scripts": - skip: - version: " - 6.99.99" - reason: this uses a new API that has been added in 7.0 + version: " - 7.99.99" + reason: this uses a new API that has been added in 8.0 - do: put_script: diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json index 6c695914011f4..e4096d781c344 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json @@ -30,6 +30,22 @@ "description":"Script ID" } } + }, + { + "path":"/_scripts/{id}", + "methods":[ + "GET" + ], + "parts":{ + "id":{ + "type":"string", + "description":"Script ID" + } + }, + "deprecated":{ + "version":"8.0.0", + "description":"The path is now singular" + } } ] }, @@ -37,6 +53,10 @@ "master_timeout":{ "type":"time", "description":"Specify timeout for connection to master" + }, + "new_format": { + "type" : "boolean", + "description" : "Use the new format" } } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java index c242b8e52ada9..72d4449347b40 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java @@ -40,9 +40,9 @@ public class GetStoredScriptResponse extends ActionResponse implements ToXContentObject { - public static final ParseField _ID_PARSE_FIELD = new ParseField("_id"); - public static final ParseField FOUND_PARSE_FIELD = new ParseField("found"); - public static final ParseField SCRIPT = new ParseField("script"); + private static final ParseField _ID_PARSE_FIELD = new ParseField("_id"); + private static final ParseField FOUND_PARSE_FIELD = new ParseField("found"); + private static final ParseField SCRIPT = new ParseField("script"); private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("GetStoredScriptResponse", @@ -106,8 +106,9 @@ public StoredScriptSource getSource() { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { -// ScriptMetaData scriptMetaData = new ScriptMetaData(getStoredScripts()); -// return scriptMetaData.toXContent(builder, params); + if (params.paramAsBoolean("new_format", false)) { + return toXContentPre80(builder, params); + } builder.startObject(); Map storedScripts = getStoredScripts(); @@ -137,9 +138,27 @@ public static GetStoredScriptResponse fromXContent(XContentParser parser) throws return new GetStoredScriptResponse(storedScripts); } -// public static GetStoredScriptResponse fromXContent(XContentParser parser) throws IOException { -// return PARSER.parse(parser, null); -// } + private XContentBuilder toXContentPre80(XContentBuilder builder, Params params) throws IOException { + builder.startObject(); + + Map.Entry entry = storedScripts.entrySet().iterator().next(); + String id = entry.getKey(); + StoredScriptSource source = entry.getValue(); + + builder.field(_ID_PARSE_FIELD.getPreferredName(), id); + builder.field(FOUND_PARSE_FIELD.getPreferredName(), source != null); + if (source != null) { + builder.field(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); + source.toXContent(builder, params); + } + + builder.endObject(); + return builder; + } + + public static GetStoredScriptResponse fromXContentPre80(XContentParser parser) throws IOException { + return PARSER.parse(parser, null); + } @Override public void writeTo(StreamOutput out) throws IOException { diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java index 1a516309fbc8e..28ac7178ac8b2 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java @@ -67,11 +67,6 @@ protected GetStoredScriptResponse read(StreamInput in) throws IOException { @Override protected void masterOperation(Task task, GetStoredScriptRequest request, ClusterState state, ActionListener listener) throws Exception { - if (request.id() != null) { - listener.onResponse(new GetStoredScriptResponse(scriptService.getStoredScripts(state))); - return; - } - Map results; Map storedScripts = scriptService.getStoredScripts(state); diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java index 05bcd4e19038c..57d76a40bba06 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java @@ -22,7 +22,6 @@ import org.elasticsearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.logging.DeprecationLogger; -import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java index 9f4543e09c1ce..ef5c869430800 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java @@ -24,7 +24,6 @@ import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.logging.DeprecationLogger; -import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; @@ -47,19 +46,19 @@ public class RestGetStoredScriptAction extends BaseRestHandler { public RestGetStoredScriptAction(RestController controller) { controller.registerHandler(GET, "/_script", this); - controller.registerWithDeprecatedHandler(GET, "/_script/{name}", this, + controller.registerWithDeprecatedHandler(GET, "/_script/{id}", this, GET, "/_scripts/{name}", deprecationLogger); - controller.registerHandler(HEAD, "/_script/{name}", this); + controller.registerHandler(HEAD, "/_script/{id}", this); } @Override public String getName() { - return "get_stored_scripts_action"; + return "get_stored_script_action"; } @Override public RestChannelConsumer prepareRequest(final RestRequest request, NodeClient client) throws IOException { - final String[] names = Strings.splitStringByCommaToArray(request.param("name")); + final String[] names = Strings.splitStringByCommaToArray(request.param("id")); GetStoredScriptRequest getRequest = new GetStoredScriptRequest(names); getRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRequest.masterNodeTimeout())); diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java index b86f81e46766a..91e3d2d13194c 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java @@ -23,7 +23,6 @@ import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.logging.DeprecationLogger; -import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; From 3fb53e6001e1daa120ad884a790d10a8469e6324 Mon Sep 17 00:00:00 2001 From: ivan Date: Thu, 15 Aug 2019 00:25:50 -0700 Subject: [PATCH 07/28] convert /_scripts/painless as well --- .../client/RestHighLevelClientTests.java | 2 +- .../painless-execute-script.asciidoc | 6 +++--- .../painless/ContextDocGenerator.java | 4 ++-- .../painless/action/PainlessContextAction.java | 8 ++++---- .../painless/action/PainlessExecuteAction.java | 6 +++--- ..._context.json => script_painless_context.json} | 13 +++++++++++-- .../test/painless/70_execute_painless_scripts.yml | 8 ++++---- .../test/painless/71_context_api.yml | 4 ++-- .../resources/rest-api-spec/api/get_script.json | 8 +------- ..._execute.json => script_painless_execute.json} | 15 +++++++++++++-- 10 files changed, 44 insertions(+), 30 deletions(-) rename modules/lang-painless/src/test/resources/rest-api-spec/api/{scripts_painless_context.json => script_painless_context.json} (57%) rename rest-api-spec/src/main/resources/rest-api-spec/api/{scripts_painless_execute.json => script_painless_execute.json} (64%) diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java index d0d6f674064ab..8846f81d61ced 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java @@ -746,7 +746,7 @@ public void testApiNamingConventions() throws Exception { "indices.get_upgrade", "indices.put_alias", "render_search_template", - "scripts_painless_execute" + "script_painless_execute" }; //These API are not required for high-level client feature completeness String[] notRequiredApi = new String[] { diff --git a/docs/painless/painless-guide/painless-execute-script.asciidoc b/docs/painless/painless-guide/painless-execute-script.asciidoc index fc5a6bf71d14a..0aaa4384d3b72 100644 --- a/docs/painless/painless-guide/painless-execute-script.asciidoc +++ b/docs/painless/painless-guide/painless-execute-script.asciidoc @@ -32,7 +32,7 @@ Request: [source,js] ---------------------------------------------------------------- -POST /_scripts/painless/_execute +POST /_script/painless/_execute { "script": { "source": "params.count / params.total", @@ -82,7 +82,7 @@ PUT /my-index } } -POST /_scripts/painless/_execute +POST /_script/painless/_execute { "script": { "source": "doc['field'].value.length() <= params.max_length", @@ -142,7 +142,7 @@ PUT /my-index } -POST /_scripts/painless/_execute +POST /_script/painless/_execute { "script": { "source": "doc['rank'].value / params.max_rank", diff --git a/modules/lang-painless/src/doc/java/org/elasticsearch/painless/ContextDocGenerator.java b/modules/lang-painless/src/doc/java/org/elasticsearch/painless/ContextDocGenerator.java index f09dd4f521ade..e16be46c180b2 100644 --- a/modules/lang-painless/src/doc/java/org/elasticsearch/painless/ContextDocGenerator.java +++ b/modules/lang-painless/src/doc/java/org/elasticsearch/painless/ContextDocGenerator.java @@ -105,7 +105,7 @@ public static void main(String[] args) throws IOException { @SuppressForbidden(reason = "retrieving data from an internal API not exposed as part of the REST client") private static List getContextInfos() throws IOException { URLConnection getContextNames = new URL( - "http://" + System.getProperty("cluster.uri") + "/_scripts/painless/_context").openConnection(); + "http://" + System.getProperty("cluster.uri") + "/_script/painless/_context").openConnection(); XContentParser parser = JsonXContent.jsonXContent.createParser(null, null, getContextNames.getInputStream()); parser.nextToken(); parser.nextToken(); @@ -118,7 +118,7 @@ private static List getContextInfos() throws IOException { for (String contextName : contextNames) { URLConnection getContextInfo = new URL( - "http://" + System.getProperty("cluster.uri") + "/_scripts/painless/_context?context=" + contextName).openConnection(); + "http://" + System.getProperty("cluster.uri") + "/_script/painless/_context?context=" + contextName).openConnection(); parser = JsonXContent.jsonXContent.createParser(null, null, getContextInfo.getInputStream()); contextInfos.add(PainlessContextInfo.fromXContent(parser)); ((HttpURLConnection)getContextInfo).disconnect(); diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextAction.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextAction.java index 9075b9e030df8..3c04805ed7138 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextAction.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextAction.java @@ -58,8 +58,8 @@ * Internal REST API for querying context information about Painless whitelists. * Commands include the following: *
    - *
  • GET /_scripts/painless/_context -- retrieves a list of contexts
  • - *
  • GET /_scripts/painless/_context?context=%name% -- + *
  • GET /_script/painless/_context -- retrieves a list of contexts
  • + *
  • GET /_script/painless/_context?context=%name% -- * retrieves all available information about the API for this specific context
  • *
*/ @@ -195,12 +195,12 @@ protected void doExecute(Task task, Request request, ActionListener li public static class RestAction extends BaseRestHandler { public RestAction(RestController controller) { - controller.registerHandler(GET, "/_scripts/painless/_context", this); + controller.registerHandler(GET, "/_script/painless/_context", this); } @Override public String getName() { - return "_scripts_painless_context"; + return "_script_painless_context"; } @Override diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java index 17302c6554791..75479ff182211 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java @@ -564,13 +564,13 @@ private static Response prepareRamIndex(Request request, public static class RestAction extends BaseRestHandler { public RestAction(RestController controller) { - controller.registerHandler(GET, "/_scripts/painless/_execute", this); - controller.registerHandler(POST, "/_scripts/painless/_execute", this); + controller.registerHandler(GET, "/_script/painless/_execute", this); + controller.registerHandler(POST, "/_script/painless/_execute", this); } @Override public String getName() { - return "_scripts_painless_execute"; + return "_script_painless_execute"; } @Override diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/api/scripts_painless_context.json b/modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json similarity index 57% rename from modules/lang-painless/src/test/resources/rest-api-spec/api/scripts_painless_context.json rename to modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json index 31ef7ae8d489a..c8131540bcc92 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/api/scripts_painless_context.json +++ b/modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json @@ -1,12 +1,21 @@ { - "scripts_painless_context": { + "script_painless_context": { "stability": "experimental", "url": { "paths": [ { - "path": "/_scripts/painless/_context", + "path": "/_script/painless/_context", "methods": ["GET"], "parts": {} + }, + { + "path": "/_scripts/painless/_context", + "methods": ["GET"], + "parts": {}, + "deprecated":{ + "version":"8.0.0", + "description":"The path is now singular" + } } ] }, diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_execute_painless_scripts.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_execute_painless_scripts.yml index 5a994425c5dc2..997e79914d33b 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_execute_painless_scripts.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_execute_painless_scripts.yml @@ -15,7 +15,7 @@ setup: --- "Execute with defaults": - do: - scripts_painless_execute: + script_painless_execute: body: script: source: "params.count / params.total" @@ -27,7 +27,7 @@ setup: --- "Execute with painless_test context": - do: - scripts_painless_execute: + script_painless_execute: body: script: source: "params.var1 - params.var2" @@ -40,7 +40,7 @@ setup: --- "Execute with filter context": - do: - scripts_painless_execute: + script_painless_execute: body: script: source: "doc['field'].value.length() <= params.max_length" @@ -56,7 +56,7 @@ setup: --- "Execute with score context": - do: - scripts_painless_execute: + script_painless_execute: body: script: source: "doc['rank'].value / params.max_rank" diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/71_context_api.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/71_context_api.yml index 0413661fc586c..e3c01ffe67ab5 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/71_context_api.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/71_context_api.yml @@ -1,13 +1,13 @@ "Action to list contexts": - do: - scripts_painless_context: {} + script_painless_context: {} - match: { contexts.0: aggregation_selector} - match: { contexts.22: update} --- "Action to get all API values for score context": - do: - scripts_painless_context: + script_painless_context: context: score - match: { name: score } - match: { classes.6.name: java.lang.Appendable } diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json index e4096d781c344..6b03928496e14 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json @@ -11,13 +11,7 @@ "path":"/_script", "methods":[ "GET" - ], - "parts":{ - "id":{ - "type":"string", - "description":"Script ID" - } - } + ] }, { "path":"/_script/{id}", diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/scripts_painless_execute.json b/rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json similarity index 64% rename from rest-api-spec/src/main/resources/rest-api-spec/api/scripts_painless_execute.json rename to rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json index 9f761fb452ba1..2d4bbdd447550 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/scripts_painless_execute.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json @@ -1,5 +1,5 @@ { - "scripts_painless_execute":{ + "script_painless_execute":{ "documentation":{ "url":"https://www.elastic.co/guide/en/elasticsearch/painless/master/painless-execute-api.html", "description":"Allows an arbitrary script to be executed and a result to be returned" @@ -8,11 +8,22 @@ "url":{ "paths":[ { - "path":"/_scripts/painless/_execute", + "path":"/_script/painless/_execute", "methods":[ "GET", "POST" ] + }, + { + "path":"/_scripts/painless/_execute", + "methods":[ + "GET", + "POST" + ], + "deprecated":{ + "version":"8.0.0", + "description":"The path is now singular" + } } ] }, From 73c3a0e743a563c5605c3ddc7c3636679e4f9028 Mon Sep 17 00:00:00 2001 From: ivan Date: Thu, 15 Aug 2019 13:47:12 -0700 Subject: [PATCH 08/28] Remove deprecated paths due to potential bug in integration tests --- .../api/script_painless_context.json | 9 --------- .../resources/rest-api-spec/api/get_script.json | 16 ---------------- .../api/script_painless_execute.json | 11 ----------- 3 files changed, 36 deletions(-) diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json b/modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json index c8131540bcc92..97c1137930dbe 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json +++ b/modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json @@ -7,15 +7,6 @@ "path": "/_script/painless/_context", "methods": ["GET"], "parts": {} - }, - { - "path": "/_scripts/painless/_context", - "methods": ["GET"], - "parts": {}, - "deprecated":{ - "version":"8.0.0", - "description":"The path is now singular" - } } ] }, diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json index 6b03928496e14..f32d64bae0986 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json @@ -24,22 +24,6 @@ "description":"Script ID" } } - }, - { - "path":"/_scripts/{id}", - "methods":[ - "GET" - ], - "parts":{ - "id":{ - "type":"string", - "description":"Script ID" - } - }, - "deprecated":{ - "version":"8.0.0", - "description":"The path is now singular" - } } ] }, diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json b/rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json index 2d4bbdd447550..90a6431391aff 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json @@ -13,17 +13,6 @@ "GET", "POST" ] - }, - { - "path":"/_scripts/painless/_execute", - "methods":[ - "GET", - "POST" - ], - "deprecated":{ - "version":"8.0.0", - "description":"The path is now singular" - } } ] }, From aa2e84e0934b2f545bf29a8b0f6e8835d6b65b56 Mon Sep 17 00:00:00 2001 From: ivan Date: Wed, 21 Aug 2019 16:18:53 -0700 Subject: [PATCH 09/28] Changes based on PR comments. Consistent naming, remove redundancies, trimmed ctors. --- .../elasticsearch/client/StoredScriptsIT.java | 4 +- .../StoredScriptsDocumentationIT.java | 4 +- .../reference/search/search-template.asciidoc | 4 +- .../script/mustache/SearchTemplateIT.java | 7 +- .../test/painless/16_update2.yml | 3 +- .../test/painless/70_get_all.yml | 7 +- .../storedscripts/GetStoredScriptRequest.java | 52 ++++++---- .../GetStoredScriptRequestBuilder.java | 6 +- .../GetStoredScriptResponse.java | 84 ++++++++++------ .../TransportGetStoredScriptAction.java | 6 +- .../client/support/AbstractClient.java | 9 +- .../cluster/RestGetStoredScriptAction.java | 19 +++- .../GetStoredScriptResponseTests.java | 4 +- .../SharedClusterSnapshotRestoreIT.java | 4 +- .../cluster/storedscripts/10_get_script.yml | 96 +++++++++++++++++++ 15 files changed, 235 insertions(+), 74 deletions(-) create mode 100644 server/src/test/resources/org/elasticsearch/action/admin/cluster/storedscripts/10_get_script.yml diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java index ddd4c4e8e6fe3..6d6669dc91a8d 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java @@ -93,7 +93,7 @@ public void testPutScript() throws Exception { assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); Map script = getAsMap("/_script/" + id); - assertThat(extractValue(id + ".script.lang", script), equalTo("painless")); - assertThat(extractValue(id + ".script.source", script), equalTo("Math.log(_score * 2) + params.my_modifier")); + assertThat(extractValue(id + ".lang", script), equalTo("painless")); + assertThat(extractValue(id + ".source", script), equalTo("Math.log(_score * 2) + params.my_modifier")); } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java index f980d6f0a02eb..c426bf1649a7f 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java @@ -300,8 +300,8 @@ public void onFailure(Exception e) { client.putScript(request, RequestOptions.DEFAULT); Map script = getAsMap("/_script/id"); - assertThat(extractValue("id.script.lang", script), equalTo("mustache")); - assertThat(extractValue("id.script.source", script), equalTo("{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}")); + assertThat(extractValue("id.lang", script), equalTo("mustache")); + assertThat(extractValue("id.source", script), equalTo("{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}")); } } diff --git a/docs/reference/search/search-template.asciidoc b/docs/reference/search/search-template.asciidoc index 570ab0a7a25d3..2c1875f7ddb4d 100644 --- a/docs/reference/search/search-template.asciidoc +++ b/docs/reference/search/search-template.asciidoc @@ -78,7 +78,7 @@ This template can be retrieved by [source,js] ------------------------------------------ -GET _script/ +GET _script/?new_format=true ------------------------------------------ // CONSOLE // TEST[continued] @@ -88,7 +88,7 @@ which is rendered as: [source,js] ------------------------------------------ { - "" : { + "" : { "lang" : "mustache", "source" : "{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}", "options": { diff --git a/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateIT.java b/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateIT.java index 3ff2bb649a79b..48d8b5512dbdc 100644 --- a/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateIT.java +++ b/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateIT.java @@ -35,6 +35,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.NoSuchElementException; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; @@ -170,6 +171,7 @@ public void testIndexedTemplateClient() throws Exception { GetStoredScriptResponse getResponse = client().admin().cluster() .prepareGetStoredScript("testTemplate").get(); + assertEquals(1, getResponse.getStoredScripts().size()); assertNotNull(getResponse.getSource()); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); @@ -192,8 +194,9 @@ public void testIndexedTemplateClient() throws Exception { assertAcked(client().admin().cluster().prepareDeleteStoredScript("testTemplate")); - getResponse = client().admin().cluster().prepareGetStoredScript("testTemplate").get(); - assertNull(getResponse.getSource()); + final GetStoredScriptResponse response = client().admin().cluster().prepareGetStoredScript("testTemplate").get(); + assertEquals(0, response.getStoredScripts().size()); + expectThrows(NoSuchElementException.class, () -> response.getSource()); } public void testIndexedTemplate() throws Exception { diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml index 4a6bc23bf1947..b17e7f8e31636 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml @@ -12,7 +12,8 @@ - do: get_script: id: "1" - - match: { "1" : { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } } + new_format: true + - match: { "1" : { "lang": "painless", "source": "_score * doc['myParent.weight'].value"} } - do: catch: missing diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml index a92674c754e5b..6cb17544d94cc 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml @@ -18,8 +18,9 @@ - match: { acknowledged: true } - do: - get_script: {} + get_script: + new_format: true - length: { $body: 2 } - - match: { 1.script: {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } - - match: { foo.script: {"lang": "painless", "source": "_score * 9.9"} } + - match: { 1: {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } + - match: { foo: {"lang": "painless", "source": "_score * 9.9"} } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java index c6fe5a26c813c..7f2fccd3673cd 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java @@ -19,6 +19,7 @@ package org.elasticsearch.action.admin.cluster.storedscripts; +import org.elasticsearch.Version; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.support.master.MasterNodeReadRequest; import org.elasticsearch.common.Strings; @@ -31,46 +32,57 @@ public class GetStoredScriptRequest extends MasterNodeReadRequest { - private String[] names; + private String[] ids; public GetStoredScriptRequest() { this(new String[]{}); } - public GetStoredScriptRequest(String... names) { - this.names = names; + public GetStoredScriptRequest(String... ids) { + this.ids = ids; } public GetStoredScriptRequest(StreamInput in) throws IOException { super(in); - names = in.readStringArray(); + if (in.getVersion().onOrAfter(Version.V_7_4_0)) { + this.ids = in.readStringArray(); + } else { + this.ids = new String[] { in.readString() }; + } } /** - * Returns he names of the scripts. + * Returns the ids of the scripts. */ - public String[] names() { - return this.names; + public String[] ids() { + return this.ids; + } + + public GetStoredScriptRequest ids(String... ids) { + this.ids = ids; + + return this; } /** * @deprecated - Needed for backwards compatibility. - * Use {@link #names()} instead + * Use {@link #ids()} instead * - * Return the script if there is only one defined, null otherwise + * Return the only script */ @Deprecated public String id() { - return names != null && names.length == 1 ? names[0] : null; + assert(ids.length == 1); + return ids[0]; } /** * @deprecated - Needed for backwards compatibility. - * Set the script names param instead + * Set the script ids param instead */ @Deprecated public GetStoredScriptRequest id(String id) { - this.names = new String[] { id }; + this.ids = new String[] { id }; return this; } @@ -78,18 +90,22 @@ public GetStoredScriptRequest id(String id) { @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); - out.writeStringArray(names); + if (out.getVersion().onOrAfter(Version.V_7_4_0)) { + out.writeStringArray(ids); + } else { + out.writeString(ids[0]); + } } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; - if (names == null) { - validationException = addValidationError("names is null or empty", validationException); + if (ids == null) { + validationException = addValidationError("ids is null or empty", validationException); } else { - for (String name : names) { + for (String name : ids) { if (name == null || !Strings.hasText(name)) { - validationException = addValidationError("name is missing", validationException); + validationException = addValidationError("id is missing", validationException); } } } @@ -98,6 +114,6 @@ public ActionRequestValidationException validate() { @Override public String toString() { - return "get script"; + return "get script[ " + String.join(", ", ids) + "]"; } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java index 76d8d692f092e..cac4cbc6ea5cc 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java @@ -29,10 +29,12 @@ public GetStoredScriptRequestBuilder(ElasticsearchClient client, GetStoredScript super(client, action, new GetStoredScriptRequest()); } - public GetStoredScriptRequestBuilder(ElasticsearchClient client, GetStoredScriptAction action, String... names) { - super(client, action, new GetStoredScriptRequest(names)); + public GetStoredScriptRequestBuilder setIds(String... ids) { + request.ids(ids); + return this; } + @Deprecated public GetStoredScriptRequestBuilder setId(String id) { request.id(id); return this; diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java index 72d4449347b40..5ce01367114cb 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java @@ -19,6 +19,7 @@ package org.elasticsearch.action.admin.cluster.storedscripts; +import org.elasticsearch.Version; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.io.stream.StreamInput; @@ -63,25 +64,36 @@ public class GetStoredScriptResponse extends ActionResponse implements ToXConten SCRIPT, ObjectParser.ValueType.OBJECT); } - private Map storedScripts; + private final Map storedScripts; + private final String[] requestedIds; GetStoredScriptResponse(StreamInput in) throws IOException { super(in); - int size = in.readVInt(); - storedScripts = new HashMap<>(size); - for (int i = 0 ; i < size ; i++) { + if (in.getVersion().onOrAfter(Version.V_7_4_0)) { + storedScripts = in.readMap(StreamInput::readString, StoredScriptSource::new); + } else { + StoredScriptSource source; + if (in.readBoolean()) { + source = new StoredScriptSource(in); + } else { + source = null; + } String id = in.readString(); - storedScripts.put(id, new StoredScriptSource(in)); + storedScripts = new HashMap<>(1); + storedScripts.put(id, source); } + requestedIds = new String[0]; } GetStoredScriptResponse(String id, StoredScriptSource source) { this.storedScripts = new HashMap<>(); storedScripts.put(id, source); + requestedIds = new String[]{ id }; } - GetStoredScriptResponse(Map storedScripts) { + GetStoredScriptResponse(String[] requestedIds, Map storedScripts) { + this.requestedIds = requestedIds; this.storedScripts = storedScripts; } @@ -97,27 +109,21 @@ public Map getStoredScripts() { */ @Deprecated public StoredScriptSource getSource() { - if (storedScripts != null && storedScripts.size() == 1) { - return storedScripts.entrySet().iterator().next().getValue(); - } else { - return null; - } + return storedScripts.entrySet().iterator().next().getValue(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - if (params.paramAsBoolean("new_format", false)) { + if (!params.paramAsBoolean("new_format", false)) { return toXContentPre80(builder, params); } - builder.startObject(); + builder.startObject(); Map storedScripts = getStoredScripts(); if (storedScripts != null) { for (Map.Entry storedScript : storedScripts.entrySet()) { - builder.startObject(storedScript.getKey()); - builder.field(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); + builder.field(storedScript.getKey()); storedScript.getValue().toXContent(builder, params); - builder.endObject(); } } builder.endObject(); @@ -129,21 +135,24 @@ public static GetStoredScriptResponse fromXContent(XContentParser parser) throws for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) { if (token == XContentParser.Token.FIELD_NAME) { String name = parser.currentName(); - parser.nextToken(); - parser.nextToken(); + assert parser.nextToken() == XContentParser.Token.START_OBJECT; StoredScriptSource storedScriptSource = StoredScriptSource.fromXContent(parser, false); storedScripts.put(name, storedScriptSource); } } - return new GetStoredScriptResponse(storedScripts); + return new GetStoredScriptResponse(storedScripts.keySet().toArray(String[]::new), storedScripts); } + @Deprecated private XContentBuilder toXContentPre80(XContentBuilder builder, Params params) throws IOException { builder.startObject(); - Map.Entry entry = storedScripts.entrySet().iterator().next(); - String id = entry.getKey(); - StoredScriptSource source = entry.getValue(); + String id = requestedIds[0]; + StoredScriptSource source = null; + if (!storedScripts.isEmpty()) { + Map.Entry entry = storedScripts.entrySet().iterator().next(); + source = entry.getValue(); + } builder.field(_ID_PARSE_FIELD.getPreferredName(), id); builder.field(FOUND_PARSE_FIELD.getPreferredName(), source != null); @@ -156,21 +165,36 @@ private XContentBuilder toXContentPre80(XContentBuilder builder, Params params) return builder; } + /** + * Used to test backwards compatibility since the original format is the default prior to 8.0 + */ + @Deprecated public static GetStoredScriptResponse fromXContentPre80(XContentParser parser) throws IOException { return PARSER.parse(parser, null); } @Override public void writeTo(StreamOutput out) throws IOException { - if (storedScripts == null ) { - out.writeVInt(0); - return; - } + if (out.getVersion().onOrAfter(Version.V_7_4_0)) { + if (storedScripts == null ) { + out.writeVInt(0); + return; + } - out.writeVInt(storedScripts.size()); - for (Map.Entry storedScript : storedScripts.entrySet()) { - out.writeString(storedScript.getKey()); - storedScript.getValue().writeTo(out); + out.writeVInt(storedScripts.size()); + for (Map.Entry storedScript : storedScripts.entrySet()) { + out.writeString(storedScript.getKey()); + storedScript.getValue().writeTo(out); + } + } else { + Map.Entry entry = storedScripts.entrySet().iterator().next(); + if (entry.getValue() == null) { + out.writeBoolean(false); + } else { + out.writeBoolean(true); + entry.getValue().writeTo(out); + } + out.writeString(entry.getKey()); } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java index 28ac7178ac8b2..6a12672e3650d 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java @@ -71,14 +71,14 @@ protected void masterOperation(Task task, GetStoredScriptRequest request, Cluste Map storedScripts = scriptService.getStoredScripts(state); // If we did not ask for a specific name, then we return all templates - if (request.names().length == 0) { + if (request.ids().length == 0) { results = storedScripts; } else { results = new HashMap<>(); } if (storedScripts != null) { - for (String name : request.names()) { + for (String name : request.ids()) { if (Regex.isSimpleMatchPattern(name)) { for (Map.Entry entry : storedScripts.entrySet()) { if (Regex.simpleMatch(name, entry.getKey())) { @@ -91,7 +91,7 @@ protected void masterOperation(Task task, GetStoredScriptRequest request, Cluste } } - listener.onResponse(new GetStoredScriptResponse(results)); + listener.onResponse(new GetStoredScriptResponse(request.ids(), results)); } @Override diff --git a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java index 3f26b205c67db..c4439b363c764 100644 --- a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java +++ b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java @@ -1155,13 +1155,14 @@ public GetStoredScriptRequestBuilder prepareGetStoredScript() { } @Override - public GetStoredScriptRequestBuilder prepareGetStoredScript(String id) { - return prepareGetStoredScript().setId(id); + public GetStoredScriptRequestBuilder prepareGetStoredScript(String... ids) { + return prepareGetStoredScript().setIds(ids); } @Override - public GetStoredScriptRequestBuilder prepareGetStoredScript(String... names) { - return new GetStoredScriptRequestBuilder(this, GetStoredScriptAction.INSTANCE, names); + @Deprecated + public GetStoredScriptRequestBuilder prepareGetStoredScript(String id) { + return prepareGetStoredScript().setId(id); } @Override diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java index ef5c869430800..ae7836bb6da10 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java @@ -24,6 +24,7 @@ import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.logging.DeprecationLogger; +import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; @@ -32,7 +33,11 @@ import org.elasticsearch.script.StoredScriptSource; import java.io.IOException; +import java.util.Collections; import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; import static org.elasticsearch.rest.RestRequest.Method.GET; import static org.elasticsearch.rest.RestRequest.Method.HEAD; @@ -41,13 +46,18 @@ public class RestGetStoredScriptAction extends BaseRestHandler { + private static final String NEW_FORMAT = "new_format"; + private static final Set allowedResponseParameters = Collections + .unmodifiableSet(Stream.concat(Collections.singleton(NEW_FORMAT).stream(), Settings.FORMAT_PARAMS.stream()) + .collect(Collectors.toSet())); + private static final DeprecationLogger deprecationLogger = new DeprecationLogger(LogManager.getLogger(RestGetStoredScriptAction.class)); public RestGetStoredScriptAction(RestController controller) { controller.registerHandler(GET, "/_script", this); controller.registerWithDeprecatedHandler(GET, "/_script/{id}", this, - GET, "/_scripts/{name}", deprecationLogger); + GET, "/_scripts/{id}", deprecationLogger); controller.registerHandler(HEAD, "/_script/{id}", this); } @@ -63,7 +73,7 @@ public RestChannelConsumer prepareRequest(final RestRequest request, NodeClient GetStoredScriptRequest getRequest = new GetStoredScriptRequest(names); getRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRequest.masterNodeTimeout())); - final boolean implicitAll = getRequest.names().length == 0; + final boolean implicitAll = getRequest.ids().length == 0; return channel -> client.admin().cluster().getStoredScript(getRequest, new RestToXContentListener<>(channel) { @Override @@ -75,4 +85,9 @@ protected RestStatus getStatus(final GetStoredScriptResponse response) } }); } + + @Override + protected Set responseParams() { + return allowedResponseParameters; + } } diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java index 5bd6e64cec2fd..b2cedba05a58c 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java @@ -34,7 +34,7 @@ public class GetStoredScriptResponseTests extends AbstractSerializingTestCase storedScripts = new HashMap<>(); storedScripts.put(randomAlphaOfLengthBetween(1, 10), randomScriptSource()); - return new GetStoredScriptResponse(storedScripts); + return new GetStoredScriptResponse(storedScripts.keySet().toArray(String[]::new), storedScripts); } @Override diff --git a/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java b/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java index b11cf9107e30b..099b2e56ae9f6 100644 --- a/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java +++ b/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java @@ -109,6 +109,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.NoSuchElementException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -784,7 +785,8 @@ public void testIncludeGlobalState() throws Exception { getIndexTemplatesResponse = client().admin().indices().prepareGetTemplates().get(); assertIndexTemplateMissing(getIndexTemplatesResponse, "test-template"); assertFalse(client().admin().cluster().prepareGetPipeline("barbaz").get().isFound()); - assertNull(client().admin().cluster().prepareGetStoredScript("foobar").get().getSource()); + final GetStoredScriptResponse getStoredScriptResponse = client().admin().cluster().prepareGetStoredScript("foobar").get(); + expectThrows(NoSuchElementException.class, () -> getStoredScriptResponse.getSource()); assertThat(client.prepareSearch("test-idx").setSize(0).get().getHits().getTotalHits().value, equalTo(100L)); } diff --git a/server/src/test/resources/org/elasticsearch/action/admin/cluster/storedscripts/10_get_script.yml b/server/src/test/resources/org/elasticsearch/action/admin/cluster/storedscripts/10_get_script.yml new file mode 100644 index 0000000000000..fa393c4049d05 --- /dev/null +++ b/server/src/test/resources/org/elasticsearch/action/admin/cluster/storedscripts/10_get_script.yml @@ -0,0 +1,96 @@ +--- +"Get script, default format": + - do: + put_script: + id: "1" + body: { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value" } } + - match: { acknowledged: true } + + - do: + get_script: + id: "1" + - match: { found: true } + - match: { _id: "1" } + - match: { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } + +--- +"Get script, new format": + - + - skip: + version: " - 7.99.99" + reason: this uses a new API that has been added in 8.0 + + - do: + put_script: + id: "1" + body: { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value" } } + - match: { acknowledged: true } + + - do: + get_script: + id: "1" + new_format: true + - match: { "1" : { "lang": "painless", "source": "_score * doc['myParent.weight'].value"} } + +--- +"Get script with wildcard": + + - skip: + version: " - 7.99.99" + reason: this uses a new API that has been added in 8.0 + - do: + put_script: + id: "foo" + body: { "script": {} } + - match: { acknowledged: true } + + - do: + put_script: + id: "foo" + body: { "script": {} } + - match: { acknowledged: true } + + - do: + put_script: + id: "bar" + body: { "script": {} } + - match: { acknowledged: true } + + - do: + put_script: + id: "baz" + body: { "script": {} } + - match: { acknowledged: true } + + - do: + get_script: + id: "ba*" + new_format: true + - length: { $body: 2 } + +--- +"Get all scripts": + + - skip: + version: " - 7.99.99" + reason: this uses a new API that has been added in 8.0 + + - do: + put_script: + id: "1" + body: { "script": { "lang": "painless", "source": "_score * doc['myParent.weight'].value" } } + - match: { acknowledged: true } + + - do: + put_script: + id: "foo" + body: { "script": { "lang": "painless", "source": "_score * 9.9" } } + - match: { acknowledged: true } + + - do: + get_script: + new_format: true + + - length: { $body: 2 } + - match: { 1: {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } + - match: { foo: {"lang": "painless", "source": "_score * 9.9"} } From 23cd4d1ff85caa68d86bd03b983a54e81a0ead3a Mon Sep 17 00:00:00 2001 From: ivan Date: Mon, 2 Sep 2019 15:41:37 -0700 Subject: [PATCH 10/28] make original format the default --- .../elasticsearch/client/StoredScriptsIT.java | 6 ++++-- .../StoredScriptsDocumentationIT.java | 4 ++-- .../storedscripts/GetStoredScriptResponse.java | 17 +++++++++-------- .../GetStoredScriptResponseTests.java | 2 +- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java index 6d6669dc91a8d..0a57208e10ffd 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java @@ -93,7 +93,9 @@ public void testPutScript() throws Exception { assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); Map script = getAsMap("/_script/" + id); - assertThat(extractValue(id + ".lang", script), equalTo("painless")); - assertThat(extractValue(id + ".source", script), equalTo("Math.log(_score * 2) + params.my_modifier")); + assertThat(extractValue("_id", script), equalTo(id)); + assertThat(extractValue("found", script), equalTo(true)); + assertThat(extractValue("script.lang", script), equalTo("painless")); + assertThat(extractValue("script.source", script), equalTo("Math.log(_score * 2) + params.my_modifier")); } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java index c426bf1649a7f..757651bb9943b 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java @@ -300,8 +300,8 @@ public void onFailure(Exception e) { client.putScript(request, RequestOptions.DEFAULT); Map script = getAsMap("/_script/id"); - assertThat(extractValue("id.lang", script), equalTo("mustache")); - assertThat(extractValue("id.source", script), equalTo("{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}")); + assertThat(extractValue("script.lang", script), equalTo("mustache")); + assertThat(extractValue("script.source", script), equalTo("{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}")); } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java index 5ce01367114cb..1c8f47e80756c 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java @@ -130,7 +130,16 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws return builder; } + /** + * The original format is the default prior to 8.0 and needed for backwards compatibility + * @see #fromXContentNewFormat(XContentParser) + */ + @Deprecated public static GetStoredScriptResponse fromXContent(XContentParser parser) throws IOException { + return PARSER.parse(parser, null); + } + + public static GetStoredScriptResponse fromXContentNewFormat(XContentParser parser) throws IOException { final Map storedScripts = new HashMap<>(); for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) { if (token == XContentParser.Token.FIELD_NAME) { @@ -165,14 +174,6 @@ private XContentBuilder toXContentPre80(XContentBuilder builder, Params params) return builder; } - /** - * Used to test backwards compatibility since the original format is the default prior to 8.0 - */ - @Deprecated - public static GetStoredScriptResponse fromXContentPre80(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - @Override public void writeTo(StreamOutput out) throws IOException { if (out.getVersion().onOrAfter(Version.V_7_4_0)) { diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java index b2cedba05a58c..1512c135f98d9 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java @@ -34,7 +34,7 @@ public class GetStoredScriptResponseTests extends AbstractSerializingTestCase Date: Mon, 2 Sep 2019 16:30:47 -0700 Subject: [PATCH 11/28] bump up the version --- .../admin/cluster/storedscripts/GetStoredScriptRequest.java | 4 ++-- .../admin/cluster/storedscripts/GetStoredScriptResponse.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java index 7f2fccd3673cd..fd06205783801 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java @@ -44,7 +44,7 @@ public GetStoredScriptRequest(String... ids) { public GetStoredScriptRequest(StreamInput in) throws IOException { super(in); - if (in.getVersion().onOrAfter(Version.V_7_4_0)) { + if (in.getVersion().onOrAfter(Version.V_7_5_0)) { this.ids = in.readStringArray(); } else { this.ids = new String[] { in.readString() }; @@ -90,7 +90,7 @@ public GetStoredScriptRequest id(String id) { @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); - if (out.getVersion().onOrAfter(Version.V_7_4_0)) { + if (out.getVersion().onOrAfter(Version.V_7_5_0)) { out.writeStringArray(ids); } else { out.writeString(ids[0]); diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java index 1c8f47e80756c..e246051b76432 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java @@ -70,7 +70,7 @@ public class GetStoredScriptResponse extends ActionResponse implements ToXConten GetStoredScriptResponse(StreamInput in) throws IOException { super(in); - if (in.getVersion().onOrAfter(Version.V_7_4_0)) { + if (in.getVersion().onOrAfter(Version.V_7_5_0)) { storedScripts = in.readMap(StreamInput::readString, StoredScriptSource::new); } else { StoredScriptSource source; @@ -176,7 +176,7 @@ private XContentBuilder toXContentPre80(XContentBuilder builder, Params params) @Override public void writeTo(StreamOutput out) throws IOException { - if (out.getVersion().onOrAfter(Version.V_7_4_0)) { + if (out.getVersion().onOrAfter(Version.V_7_5_0)) { if (storedScripts == null ) { out.writeVInt(0); return; From 601e2745ae772189e68fdbbe3d0d9228bd0ac64d Mon Sep 17 00:00:00 2001 From: Brusic Date: Wed, 24 Jan 2018 13:27:47 -0800 Subject: [PATCH 12/28] Get all scripts from ScriptService --- .../test/painless/70_get_all.yml | 25 ++++++ .../rest-api-spec/api/get_scripts.json | 15 ++++ .../storedscripts/GetStoredScriptsAction.java | 45 ++++++++++ .../GetStoredScriptsRequest.java | 53 +++++++++++ .../GetStoredScriptsRequestBuilder.java | 33 +++++++ .../GetStoredScriptsResponse.java | 86 ++++++++++++++++++ .../TransportGetStoredScriptsAction.java | 72 +++++++++++++++ .../client/ClusterAdminClient.java | 18 ++++ .../client/support/AbstractClient.java | 20 +++++ .../cluster/RestGetStoredScriptsAction.java | 88 +++++++++++++++++++ .../elasticsearch/script/ScriptMetaData.java | 7 ++ .../elasticsearch/script/ScriptService.java | 7 ++ .../GetStoredScriptsRequestTests.java | 45 ++++++++++ .../script/ScriptMetaDataTests.java | 25 ++++++ .../elasticsearch/script/StoredScriptsIT.java | 22 +++++ 15 files changed, 561 insertions(+) create mode 100644 modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml create mode 100644 rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json create mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java create mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java create mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java create mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java create mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java create mode 100644 server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java create mode 100644 server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml new file mode 100644 index 0000000000000..4f7e0a5cfdaf8 --- /dev/null +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml @@ -0,0 +1,25 @@ +--- +"Get all scripts": + + - skip: + version: " - 6.99.99" + reason: this uses a new API that has been added in 7.0 + + - do: + put_script: + id: "1" + body: { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value" } } + - match: { acknowledged: true } + + - do: + put_script: + id: "foo" + body: { "script": {"lang": "painless", "source": "_score * 9.9" } } + - match: { acknowledged: true } + + - do: + get_scripts: {} + + - length: {$body: 2} + - match: { 1.script: {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } + - match: { foo.script: {"lang": "painless", "source": "_score * 9.9"} } diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json b/rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json new file mode 100644 index 0000000000000..e254e9e5013ff --- /dev/null +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json @@ -0,0 +1,15 @@ +{ + "get_scripts": { + "documentation": "http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting.html", + "methods": ["GET"], + "url": { + "path": "/_scripts", + "paths": [ "/_scripts" ], + "parts": { + }, + "params" : { + } + }, + "body": null + } +} \ No newline at end of file diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java new file mode 100644 index 0000000000000..2ef78444ce0af --- /dev/null +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java @@ -0,0 +1,45 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ + +package org.elasticsearch.action.admin.cluster.storedscripts; + +import org.elasticsearch.action.Action; +import org.elasticsearch.client.ElasticsearchClient; + +public class GetStoredScriptsAction extends Action { + + public static final GetStoredScriptsAction INSTANCE = new GetStoredScriptsAction(); + public static final String NAME = "cluster:admin/scripts/get"; + + private GetStoredScriptsAction() { + super(NAME); + } + + @Override + public GetStoredScriptsResponse newResponse() { + return new GetStoredScriptsResponse(); + } + + @Override + public GetStoredScriptsRequestBuilder newRequestBuilder(ElasticsearchClient client) { + return new GetStoredScriptsRequestBuilder(client, this); + } + +} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java new file mode 100644 index 0000000000000..284d43c26277e --- /dev/null +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java @@ -0,0 +1,53 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ + +package org.elasticsearch.action.admin.cluster.storedscripts; + +import org.elasticsearch.action.ActionRequestValidationException; +import org.elasticsearch.action.support.master.MasterNodeReadRequest; +import org.elasticsearch.common.io.stream.StreamInput; + +import java.io.IOException; + +public class GetStoredScriptsRequest extends MasterNodeReadRequest { + + + public GetStoredScriptsRequest() { + super(); + } + + public GetStoredScriptsRequest(StreamInput in) throws IOException { + super(in); + } + + @Override + public ActionRequestValidationException validate() { + return null; + } + + @Override + public void readFrom(StreamInput in) throws IOException { + throw new UnsupportedOperationException("usage of Streamable is to be replaced by Writeable"); + } + + @Override + public String toString() { + return "get scripts"; + } +} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java new file mode 100644 index 0000000000000..b35afff425b48 --- /dev/null +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java @@ -0,0 +1,33 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ + +package org.elasticsearch.action.admin.cluster.storedscripts; + +import org.elasticsearch.action.support.master.MasterNodeReadOperationRequestBuilder; +import org.elasticsearch.client.ElasticsearchClient; + +public class GetStoredScriptsRequestBuilder extends + MasterNodeReadOperationRequestBuilder { + + + public GetStoredScriptsRequestBuilder(ElasticsearchClient client, GetStoredScriptsAction action) { + super(client, action, new GetStoredScriptsRequest()); + } +} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java new file mode 100644 index 0000000000000..89f5dc66870c5 --- /dev/null +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java @@ -0,0 +1,86 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ + +package org.elasticsearch.action.admin.cluster.storedscripts; + +import org.elasticsearch.action.ActionResponse; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.common.xcontent.ToXContentObject; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.script.StoredScriptSource; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class GetStoredScriptsResponse extends ActionResponse implements ToXContentObject { + + private Map storedScripts; + + GetStoredScriptsResponse() { + } + + GetStoredScriptsResponse(Map storedScripts) { + this.storedScripts = storedScripts; + } + + public Map getStoredScripts() { + return storedScripts; + } + + @Override + public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { + builder.startObject(); + for (Map.Entry storedScript : getStoredScripts().entrySet()) { + + builder.startObject(storedScript.getKey()); + + builder.startObject(); + storedScript.getValue().toXContent(builder, params); + builder.endObject(); + + builder.endObject(); + } + builder.endObject(); + return builder; + } + + @Override + public void readFrom(StreamInput in) throws IOException { + super.readFrom(in); + + int size = in.readVInt(); + storedScripts = new HashMap<>(size); + for (int i = 0 ; i < size ; i++) { + String id = in.readString(); + storedScripts.put(id, new StoredScriptSource(in)); + } + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + super.writeTo(out); + out.writeVInt(storedScripts.size()); + for (Map.Entry storedScript : storedScripts.entrySet()) { + out.writeString(storedScript.getKey()); + storedScript.getValue().writeTo(out); + } + } +} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java new file mode 100644 index 0000000000000..2496dcca393bb --- /dev/null +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java @@ -0,0 +1,72 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ + +package org.elasticsearch.action.admin.cluster.storedscripts; + +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.action.support.ActionFilters; +import org.elasticsearch.action.support.master.TransportMasterNodeReadAction; +import org.elasticsearch.cluster.ClusterState; +import org.elasticsearch.cluster.block.ClusterBlockException; +import org.elasticsearch.cluster.block.ClusterBlockLevel; +import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; +import org.elasticsearch.cluster.service.ClusterService; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.script.ScriptService; +import org.elasticsearch.threadpool.ThreadPool; +import org.elasticsearch.transport.TransportService; + +public class TransportGetStoredScriptsAction extends TransportMasterNodeReadAction { + + private final ScriptService scriptService; + + @Inject + public TransportGetStoredScriptsAction(Settings settings, TransportService transportService, ClusterService clusterService, + ThreadPool threadPool, ActionFilters actionFilters, + IndexNameExpressionResolver indexNameExpressionResolver, ScriptService scriptService) { + super(settings, GetStoredScriptsAction.NAME, transportService, clusterService, threadPool, + actionFilters, + GetStoredScriptsRequest::new, indexNameExpressionResolver); + this.scriptService = scriptService; + } + + @Override + protected String executor() { + return ThreadPool.Names.SAME; + } + + @Override + protected GetStoredScriptsResponse newResponse() { + return new GetStoredScriptsResponse(); + } + + @Override + protected void masterOperation(GetStoredScriptsRequest request, ClusterState state, + ActionListener listener) throws Exception { + listener.onResponse(new GetStoredScriptsResponse(scriptService.getStoredScripts(state))); + } + + @Override + protected ClusterBlockException checkBlock(GetStoredScriptsRequest request, ClusterState state) { + return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); + } + +} diff --git a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java index fdee39fdb1f93..d90bf5b164cbd 100644 --- a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java +++ b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java @@ -96,6 +96,9 @@ import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequestBuilder; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequestBuilder; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequestBuilder; import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksRequest; @@ -718,4 +721,19 @@ public interface ClusterAdminClient extends ElasticsearchClient { * Get a script from the cluster state */ ActionFuture getStoredScript(GetStoredScriptRequest request); + + /** + * Get a script from the cluster state + */ + GetStoredScriptsRequestBuilder prepareGetStoredScripts(); + + /** + * Get all scripts from the cluster state + */ + void getStoredScripts(GetStoredScriptsRequest request, ActionListener listener); + + /** + * Get all scripts from the cluster state + */ + ActionFuture getStoredScripts(GetStoredScriptsRequest request); } diff --git a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java index 283b8dc0a2843..e4724ffccda0b 100644 --- a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java +++ b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java @@ -128,6 +128,10 @@ import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequestBuilder; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsAction; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequestBuilder; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptAction; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequestBuilder; @@ -1159,6 +1163,22 @@ public GetStoredScriptRequestBuilder prepareGetStoredScript(String id) { return prepareGetStoredScript().setId(id); } + @Override + public ActionFuture getStoredScripts(GetStoredScriptsRequest request) { + return execute(GetStoredScriptsAction.INSTANCE, request); + } + + @Override + public void getStoredScripts(GetStoredScriptsRequest request, + ActionListener listener) { + execute(GetStoredScriptsAction.INSTANCE, request, listener); + } + + @Override + public GetStoredScriptsRequestBuilder prepareGetStoredScripts() { + return new GetStoredScriptsRequestBuilder(this, GetStoredScriptsAction.INSTANCE); + } + @Override public PutStoredScriptRequestBuilder preparePutStoredScript() { return new PutStoredScriptRequestBuilder(this, PutStoredScriptAction.INSTANCE); diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java new file mode 100644 index 0000000000000..121acd39c2430 --- /dev/null +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java @@ -0,0 +1,88 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ +package org.elasticsearch.rest.action.admin.cluster; + +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; +import org.elasticsearch.client.node.NodeClient; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.rest.BaseRestHandler; +import org.elasticsearch.rest.BytesRestResponse; +import org.elasticsearch.rest.RestController; +import org.elasticsearch.rest.RestRequest; +import org.elasticsearch.rest.RestResponse; +import org.elasticsearch.rest.RestStatus; +import org.elasticsearch.rest.action.RestBuilderListener; +import org.elasticsearch.script.StoredScriptSource; + +import java.io.IOException; +import java.util.Map; + +import static org.elasticsearch.rest.RestRequest.Method.GET; + +public class RestGetStoredScriptsAction extends BaseRestHandler { + + public RestGetStoredScriptsAction(Settings settings, RestController controller) { + super(settings); + + controller.registerHandler(GET, "/_scripts", this); + } + + @Override + public String getName() { + return "get_all_stored_scripts_action"; + } + + @Override + public RestChannelConsumer prepareRequest(final RestRequest request, NodeClient client) throws IOException { + GetStoredScriptsRequest getRequest = new GetStoredScriptsRequest(); + + + return channel -> client.admin().cluster().getStoredScripts(getRequest, new + RestBuilderListener(channel) { + @Override + public RestResponse buildResponse(GetStoredScriptsResponse response, XContentBuilder builder) + throws Exception { + builder.startObject(); + + Map storedScripts = response.getStoredScripts(); + for (Map.Entry storedScript : storedScripts.entrySet()) { + builder.startObject(storedScript.getKey()); + + StoredScriptSource source = storedScript.getValue(); + builder.startObject(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); + builder.field(StoredScriptSource.LANG_PARSE_FIELD.getPreferredName(), source.getLang()); + builder.field(StoredScriptSource.SOURCE_PARSE_FIELD.getPreferredName(), source.getSource()); + + if (!source.getOptions().isEmpty()) { + builder.field(StoredScriptSource.OPTIONS_PARSE_FIELD.getPreferredName(), source.getOptions()); + } + + builder.endObject(); + builder.endObject(); + } + + builder.endObject(); + + return new BytesRestResponse(RestStatus.OK, builder); + } + }); + } +} diff --git a/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java b/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java index 52a06db582966..118755b60c339 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java @@ -366,6 +366,13 @@ StoredScriptSource getStoredScript(String id) { return scripts.get(id); } + /** + * Retrieves all stored scripts + */ + Map getStoredScripts() { + return scripts; + } + @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/server/src/main/java/org/elasticsearch/script/ScriptService.java b/server/src/main/java/org/elasticsearch/script/ScriptService.java index f1472afba9342..83e51a5f0ccaf 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptService.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptService.java @@ -538,6 +538,13 @@ public StoredScriptSource getStoredScript(ClusterState state, GetStoredScriptReq } } + public Map getStoredScripts(ClusterState state) { + ScriptMetaData scriptMetadata = state.metaData().custom(ScriptMetaData.TYPE); + + return scriptMetadata.getStoredScripts(); + } + + public ScriptStats stats() { return scriptMetrics.stats(); } diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java new file mode 100644 index 0000000000000..4c2dd2b617152 --- /dev/null +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java @@ -0,0 +1,45 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch 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. + */ + +package org.elasticsearch.action.admin.cluster.storedscripts; + +import org.elasticsearch.common.io.stream.BytesStreamOutput; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.test.ESTestCase; + +import java.io.IOException; + +import static org.elasticsearch.test.VersionUtils.randomVersion; +import static org.hamcrest.CoreMatchers.equalTo; + +public class GetStoredScriptsRequestTests extends ESTestCase { + public void testGetIndexedScriptsRequestSerialization() throws IOException { + GetStoredScriptsRequest request = new GetStoredScriptsRequest(); + + BytesStreamOutput out = new BytesStreamOutput(); + out.setVersion(randomVersion(random())); + request.writeTo(out); + + StreamInput in = out.bytes().streamInput(); + in.setVersion(out.getVersion()); + GetStoredScriptsRequest request2 = new GetStoredScriptsRequest(in); + + assertThat(request2, equalTo(request)); + } +} diff --git a/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java b/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java index 7a856ee13b9d3..173f3d4e24d30 100644 --- a/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java +++ b/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java @@ -32,6 +32,7 @@ import java.io.IOException; import java.io.UncheckedIOException; +import java.util.Map; public class ScriptMetaDataTests extends AbstractSerializingTestCase { @@ -93,6 +94,30 @@ public void testGetScript() throws Exception { assertEquals("{\"field\":\"value\"}", scriptMetaData.getStoredScript("source_template").getSource()); } + public void testGetScripts() throws Exception { + ScriptMetaData.Builder builder = new ScriptMetaData.Builder(null); + + XContentBuilder sourceBuilder = XContentFactory.jsonBuilder(); + sourceBuilder.startObject().startObject("template").field("field", "value").endObject().endObject(); + builder.storeScript("template", StoredScriptSource.parse(sourceBuilder.bytes(), sourceBuilder.contentType())); + + sourceBuilder = XContentFactory.jsonBuilder(); + sourceBuilder.startObject().field("template", "value").endObject(); + builder.storeScript("template_field", StoredScriptSource.parse(sourceBuilder.bytes(), sourceBuilder.contentType())); + + sourceBuilder = XContentFactory.jsonBuilder(); + sourceBuilder.startObject().startObject("script").field("lang", "_lang").field("source", "_source").endObject().endObject(); + builder.storeScript("script", StoredScriptSource.parse(sourceBuilder.bytes(), sourceBuilder.contentType())); + + ScriptMetaData scriptMetaData = builder.build(); + Map storedScripts = scriptMetaData.getStoredScripts(); + + assertEquals(3, storedScripts.size()); + assertEquals("_source", storedScripts.get("script").getSource()); + assertEquals("{\"field\":\"value\"}", storedScripts.get("template").getSource()); + assertEquals("value", storedScripts.get("template_field").getSource()); + } + public void testDiff() throws Exception { ScriptMetaData.Builder builder = new ScriptMetaData.Builder(null); builder.storeScript("1", StoredScriptSource.parse( diff --git a/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java b/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java index a1a82c88819a2..3f0f1801735bd 100644 --- a/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java +++ b/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java @@ -71,6 +71,28 @@ public void testBasics() { assertEquals("Validation Failed: 1: id cannot contain '#' for stored script;", e.getMessage()); } + public void testGetAllScripts() { + assertAcked(client().admin().cluster().preparePutStoredScript() + .setId("foobar") + .setContent(new BytesArray("{\"script\": {\"lang\": \"" + LANG + "\", \"source\": \"1\"} }"), XContentType.JSON)); + + assertAcked(client().admin().cluster().preparePutStoredScript() + .setId("1") + .setContent(new BytesArray("{\"script\": {\"lang\": \"" + LANG + "\", \"source\": \"9.9\"} }"), + XContentType.JSON)); + + Map storedScripts = client().admin().cluster().prepareGetStoredScripts().get().getStoredScripts(); + assertEquals(2, storedScripts.size()); + + StoredScriptSource source = storedScripts.get("foobar"); + assertNotNull(source); + assertEquals(LANG, source.getLang()); + + source = storedScripts.get("1"); + assertNotNull(source); + assertEquals("9.9", source.getSource()); + } + public void testMaxScriptSize() { IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> client().admin().cluster().preparePutStoredScript() .setId("foobar") From 77fd4d706f0592e3c59c4ad6115630cc94c4624a Mon Sep 17 00:00:00 2001 From: Brusic Date: Wed, 24 Jan 2018 18:56:06 -0800 Subject: [PATCH 13/28] fixed silly assertEquals test with trivial equals() --- .../storedscripts/GetStoredScriptsRequest.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java index 284d43c26277e..82ac82f982e72 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java @@ -46,8 +46,20 @@ public void readFrom(StreamInput in) throws IOException { throw new UnsupportedOperationException("usage of Streamable is to be replaced by Writeable"); } + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + return !(obj == null || getClass() != obj.getClass()); + } + @Override public String toString() { return "get scripts"; } + } From 18d92d8faff63063af97787846f1411b9232d292 Mon Sep 17 00:00:00 2001 From: ivan Date: Thu, 8 Aug 2019 22:57:11 +0200 Subject: [PATCH 14/28] update to latest master --- .../storedscripts/GetStoredScriptsAction.java | 19 ++----- .../GetStoredScriptsRequest.java | 30 ++++++----- .../GetStoredScriptsRequestBuilder.java | 5 +- .../GetStoredScriptsResponse.java | 39 +++++++------- .../TransportGetStoredScriptsAction.java | 51 +++++++++++++++---- .../client/ClusterAdminClient.java | 2 +- .../client/support/AbstractClient.java | 4 +- .../cluster/RestGetStoredScriptsAction.java | 47 +++++++---------- .../elasticsearch/script/ScriptMetaData.java | 7 --- .../elasticsearch/script/ScriptService.java | 6 ++- .../script/ScriptMetaDataTests.java | 19 ++++--- 11 files changed, 116 insertions(+), 113 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java index 2ef78444ce0af..debe140d66c51 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java @@ -19,27 +19,14 @@ package org.elasticsearch.action.admin.cluster.storedscripts; -import org.elasticsearch.action.Action; -import org.elasticsearch.client.ElasticsearchClient; +import org.elasticsearch.action.ActionType; -public class GetStoredScriptsAction extends Action { +public class GetStoredScriptsAction extends ActionType { public static final GetStoredScriptsAction INSTANCE = new GetStoredScriptsAction(); public static final String NAME = "cluster:admin/scripts/get"; private GetStoredScriptsAction() { - super(NAME); + super(NAME, GetStoredScriptsResponse::new); } - - @Override - public GetStoredScriptsResponse newResponse() { - return new GetStoredScriptsResponse(); - } - - @Override - public GetStoredScriptsRequestBuilder newRequestBuilder(ElasticsearchClient client) { - return new GetStoredScriptsRequestBuilder(client, this); - } - } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java index 82ac82f982e72..42d01fad49e5e 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java @@ -22,39 +22,43 @@ import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.support.master.MasterNodeReadRequest; import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; import java.io.IOException; public class GetStoredScriptsRequest extends MasterNodeReadRequest { + private String[] names; public GetStoredScriptsRequest() { super(); } - public GetStoredScriptsRequest(StreamInput in) throws IOException { - super(in); + public GetStoredScriptsRequest(String... names) { + this.names = names; } - @Override - public ActionRequestValidationException validate() { - return null; + public GetStoredScriptsRequest(StreamInput in) throws IOException { + super(in); + names = in.readStringArray(); } - @Override - public void readFrom(StreamInput in) throws IOException { - throw new UnsupportedOperationException("usage of Streamable is to be replaced by Writeable"); + /** + * The names of the search templates. + */ + public String[] names() { + return this.names; } @Override - public int hashCode() { - return super.hashCode(); + public void writeTo(StreamOutput out) throws IOException { + super.writeTo(out); + out.writeStringArray(names); } @Override - public boolean equals(Object obj) { - if (this == obj) return true; - return !(obj == null || getClass() != obj.getClass()); + public ActionRequestValidationException validate() { + return null; } @Override diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java index b35afff425b48..a2522ceb68b3c 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java @@ -26,8 +26,11 @@ public class GetStoredScriptsRequestBuilder extends MasterNodeReadOperationRequestBuilder { - public GetStoredScriptsRequestBuilder(ElasticsearchClient client, GetStoredScriptsAction action) { super(client, action, new GetStoredScriptsRequest()); } + + public GetStoredScriptsRequestBuilder(ElasticsearchClient client, GetStoredScriptsAction action, String... names) { + super(client, action, new GetStoredScriptsRequest(names)); + } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java index 89f5dc66870c5..db6bd2bc9be1f 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java @@ -34,7 +34,15 @@ public class GetStoredScriptsResponse extends ActionResponse implements ToXConte private Map storedScripts; - GetStoredScriptsResponse() { + GetStoredScriptsResponse(StreamInput in) throws IOException { + super(in); + + int size = in.readVInt(); + storedScripts = new HashMap<>(size); + for (int i = 0 ; i < size ; i++) { + String id = in.readString(); + storedScripts.put(id, new StoredScriptSource(in)); + } } GetStoredScriptsResponse(Map storedScripts) { @@ -48,35 +56,22 @@ public Map getStoredScripts() { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); - for (Map.Entry storedScript : getStoredScripts().entrySet()) { - - builder.startObject(storedScript.getKey()); - builder.startObject(); - storedScript.getValue().toXContent(builder, params); - builder.endObject(); - - builder.endObject(); + Map storedScripts = getStoredScripts(); + if (storedScripts != null) { + for (Map.Entry storedScript : storedScripts.entrySet()) { + builder.startObject(storedScript.getKey()); + builder.field(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); + storedScript.getValue().toXContent(builder, params); + builder.endObject(); + } } builder.endObject(); return builder; } - @Override - public void readFrom(StreamInput in) throws IOException { - super.readFrom(in); - - int size = in.readVInt(); - storedScripts = new HashMap<>(size); - for (int i = 0 ; i < size ; i++) { - String id = in.readString(); - storedScripts.put(id, new StoredScriptSource(in)); - } - } - @Override public void writeTo(StreamOutput out) throws IOException { - super.writeTo(out); out.writeVInt(storedScripts.size()); for (Map.Entry storedScript : storedScripts.entrySet()) { out.writeString(storedScript.getKey()); diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java index 2496dcca393bb..3e4aea7ea116f 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java @@ -28,22 +28,28 @@ import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.regex.Regex; import org.elasticsearch.script.ScriptService; +import org.elasticsearch.script.StoredScriptSource; +import org.elasticsearch.tasks.Task; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + public class TransportGetStoredScriptsAction extends TransportMasterNodeReadAction { private final ScriptService scriptService; @Inject - public TransportGetStoredScriptsAction(Settings settings, TransportService transportService, ClusterService clusterService, - ThreadPool threadPool, ActionFilters actionFilters, - IndexNameExpressionResolver indexNameExpressionResolver, ScriptService scriptService) { - super(settings, GetStoredScriptsAction.NAME, transportService, clusterService, threadPool, - actionFilters, + public TransportGetStoredScriptsAction(TransportService transportService, ClusterService clusterService, + ThreadPool threadPool, ActionFilters actionFilters, + IndexNameExpressionResolver indexNameExpressionResolver, ScriptService scriptService) { + super(GetStoredScriptsAction.NAME, transportService, clusterService, threadPool, actionFilters, GetStoredScriptsRequest::new, indexNameExpressionResolver); this.scriptService = scriptService; } @@ -54,14 +60,39 @@ protected String executor() { } @Override - protected GetStoredScriptsResponse newResponse() { - return new GetStoredScriptsResponse(); + protected GetStoredScriptsResponse read(StreamInput in) throws IOException { + return new GetStoredScriptsResponse(in); } @Override - protected void masterOperation(GetStoredScriptsRequest request, ClusterState state, + protected void masterOperation(Task task, GetStoredScriptsRequest request, ClusterState state, ActionListener listener) throws Exception { - listener.onResponse(new GetStoredScriptsResponse(scriptService.getStoredScripts(state))); + + Map results; + + Map storedScripts = scriptService.getStoredScripts(state); + // If we did not ask for a specific name, then we return all templates + if (request.names().length == 0) { + results = storedScripts; + } else { + results = new HashMap<>(); + } + + if (storedScripts != null) { + for (String name : request.names()) { + if (Regex.isSimpleMatchPattern(name)) { + for (Map.Entry entry : storedScripts.entrySet()) { + if (Regex.simpleMatch(name, entry.getKey())) { + results.put(entry.getKey(), entry.getValue()); + } + } + } else if (storedScripts.containsKey(name)) { + results.put(name, storedScripts.get(name)); + } + } + } + + listener.onResponse(new GetStoredScriptsResponse(results)); } @Override diff --git a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java index d90bf5b164cbd..36e6eb2900f1c 100644 --- a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java +++ b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java @@ -725,7 +725,7 @@ public interface ClusterAdminClient extends ElasticsearchClient { /** * Get a script from the cluster state */ - GetStoredScriptsRequestBuilder prepareGetStoredScripts(); + GetStoredScriptsRequestBuilder prepareGetStoredScripts(String... name); /** * Get all scripts from the cluster state diff --git a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java index e4724ffccda0b..174829403cc42 100644 --- a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java +++ b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java @@ -1175,8 +1175,8 @@ public void getStoredScripts(GetStoredScriptsRequest request, } @Override - public GetStoredScriptsRequestBuilder prepareGetStoredScripts() { - return new GetStoredScriptsRequestBuilder(this, GetStoredScriptsAction.INSTANCE); + public GetStoredScriptsRequestBuilder prepareGetStoredScripts(String... names) { + return new GetStoredScriptsRequestBuilder(this, GetStoredScriptsAction.INSTANCE, names); } @Override diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java index 121acd39c2430..5e272ae5ba1e1 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java @@ -21,21 +21,22 @@ import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; import org.elasticsearch.client.node.NodeClient; +import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.BaseRestHandler; -import org.elasticsearch.rest.BytesRestResponse; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; -import org.elasticsearch.rest.RestResponse; import org.elasticsearch.rest.RestStatus; -import org.elasticsearch.rest.action.RestBuilderListener; +import org.elasticsearch.rest.action.RestToXContentListener; import org.elasticsearch.script.StoredScriptSource; import java.io.IOException; import java.util.Map; import static org.elasticsearch.rest.RestRequest.Method.GET; +import static org.elasticsearch.rest.RestRequest.Method.HEAD; +import static org.elasticsearch.rest.RestStatus.NOT_FOUND; +import static org.elasticsearch.rest.RestStatus.OK; public class RestGetStoredScriptsAction extends BaseRestHandler { @@ -43,6 +44,8 @@ public RestGetStoredScriptsAction(Settings settings, RestController controller) super(settings); controller.registerHandler(GET, "/_scripts", this); + controller.registerHandler(GET, "/_script/{name}", this); + controller.registerHandler(HEAD, "/_script/{name}", this); } @Override @@ -52,36 +55,20 @@ public String getName() { @Override public RestChannelConsumer prepareRequest(final RestRequest request, NodeClient client) throws IOException { - GetStoredScriptsRequest getRequest = new GetStoredScriptsRequest(); + final String[] names = Strings.splitStringByCommaToArray(request.param("name")); + GetStoredScriptsRequest getRequest = new GetStoredScriptsRequest(names); + getRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRequest.masterNodeTimeout())); - return channel -> client.admin().cluster().getStoredScripts(getRequest, new - RestBuilderListener(channel) { - @Override - public RestResponse buildResponse(GetStoredScriptsResponse response, XContentBuilder builder) - throws Exception { - builder.startObject(); + final boolean implicitAll = getRequest.names().length == 0; + return channel -> client.admin().cluster().getStoredScripts(getRequest, new RestToXContentListener<>(channel) { + @Override + protected RestStatus getStatus(final GetStoredScriptsResponse response) + { Map storedScripts = response.getStoredScripts(); - for (Map.Entry storedScript : storedScripts.entrySet()) { - builder.startObject(storedScript.getKey()); - - StoredScriptSource source = storedScript.getValue(); - builder.startObject(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); - builder.field(StoredScriptSource.LANG_PARSE_FIELD.getPreferredName(), source.getLang()); - builder.field(StoredScriptSource.SOURCE_PARSE_FIELD.getPreferredName(), source.getSource()); - - if (!source.getOptions().isEmpty()) { - builder.field(StoredScriptSource.OPTIONS_PARSE_FIELD.getPreferredName(), source.getOptions()); - } - - builder.endObject(); - builder.endObject(); - } - - builder.endObject(); - - return new BytesRestResponse(RestStatus.OK, builder); + final boolean templateExists = storedScripts != null && !storedScripts.isEmpty(); + return (templateExists || implicitAll) ? OK : NOT_FOUND; } }); } diff --git a/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java b/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java index 118755b60c339..52a06db582966 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptMetaData.java @@ -366,13 +366,6 @@ StoredScriptSource getStoredScript(String id) { return scripts.get(id); } - /** - * Retrieves all stored scripts - */ - Map getStoredScripts() { - return scripts; - } - @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/server/src/main/java/org/elasticsearch/script/ScriptService.java b/server/src/main/java/org/elasticsearch/script/ScriptService.java index 83e51a5f0ccaf..1425b8746ad6e 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptService.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptService.java @@ -541,7 +541,11 @@ public StoredScriptSource getStoredScript(ClusterState state, GetStoredScriptReq public Map getStoredScripts(ClusterState state) { ScriptMetaData scriptMetadata = state.metaData().custom(ScriptMetaData.TYPE); - return scriptMetadata.getStoredScripts(); + if (scriptMetadata != null) { + return scriptMetadata.getStoredScripts(); + } else { + return null; + } } diff --git a/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java b/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java index 173f3d4e24d30..3889b94d2e4e9 100644 --- a/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java +++ b/server/src/test/java/org/elasticsearch/script/ScriptMetaDataTests.java @@ -98,24 +98,23 @@ public void testGetScripts() throws Exception { ScriptMetaData.Builder builder = new ScriptMetaData.Builder(null); XContentBuilder sourceBuilder = XContentFactory.jsonBuilder(); - sourceBuilder.startObject().startObject("template").field("field", "value").endObject().endObject(); - builder.storeScript("template", StoredScriptSource.parse(sourceBuilder.bytes(), sourceBuilder.contentType())); - - sourceBuilder = XContentFactory.jsonBuilder(); - sourceBuilder.startObject().field("template", "value").endObject(); - builder.storeScript("template_field", StoredScriptSource.parse(sourceBuilder.bytes(), sourceBuilder.contentType())); + sourceBuilder.startObject().startObject("script") + .field("lang", "_lang") + .startObject("source").field("field", "value").endObject() + .endObject().endObject(); + builder.storeScript("source_template", StoredScriptSource.parse(BytesReference.bytes(sourceBuilder), + sourceBuilder.contentType())); sourceBuilder = XContentFactory.jsonBuilder(); sourceBuilder.startObject().startObject("script").field("lang", "_lang").field("source", "_source").endObject().endObject(); - builder.storeScript("script", StoredScriptSource.parse(sourceBuilder.bytes(), sourceBuilder.contentType())); + builder.storeScript("script", StoredScriptSource.parse(BytesReference.bytes(sourceBuilder), sourceBuilder.contentType())); ScriptMetaData scriptMetaData = builder.build(); Map storedScripts = scriptMetaData.getStoredScripts(); - assertEquals(3, storedScripts.size()); + assertEquals(2, storedScripts.size()); assertEquals("_source", storedScripts.get("script").getSource()); - assertEquals("{\"field\":\"value\"}", storedScripts.get("template").getSource()); - assertEquals("value", storedScripts.get("template_field").getSource()); + assertEquals("{\"field\":\"value\"}", storedScripts.get("source_template").getSource()); } public void testDiff() throws Exception { From e47056dc890ca85ba0d6d660b61b93728cbf97d6 Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 13 Aug 2019 14:05:49 -0700 Subject: [PATCH 15/28] backwards compatibility --- .../GetStoredScriptRequestBuilder.java | 1 - .../GetStoredScriptsRequest.java | 9 +++++++++ .../GetStoredScriptsResponse.java | 20 +++++++++++++++++++ .../TransportGetStoredScriptsAction.java | 4 ++++ .../client/ClusterAdminClient.java | 6 ++++++ .../client/support/AbstractClient.java | 6 ++++++ 6 files changed, 45 insertions(+), 1 deletion(-) diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java index 75708c929f584..15e96aca88049 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java @@ -34,5 +34,4 @@ public GetStoredScriptRequestBuilder setId(String id) { request.id(id); return this; } - } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java index 42d01fad49e5e..c97f8610de5ad 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java @@ -50,6 +50,15 @@ public String[] names() { return this.names; } + /** + * @deprecated - Needed for backwards compatibility. + * * Use {@link #names()} instead + */ + @Deprecated + public String id() { + return names != null && names.length == 1 ? names[0] : null; + } + @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java index db6bd2bc9be1f..50437902d03bf 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java @@ -53,6 +53,21 @@ public Map getStoredScripts() { return storedScripts; } + /** + * @deprecated - Needed for backwards compatibility. + * Use {@link #getStoredScripts()} instead + * + * @return if a stored script and if not found null + */ + @Deprecated + public StoredScriptSource getSource() { + if (storedScripts != null && storedScripts.size() == 1) { + return storedScripts.entrySet().iterator().next().getValue(); + } else { + return null; + } + } + @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); @@ -72,6 +87,11 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public void writeTo(StreamOutput out) throws IOException { + if (storedScripts == null ) { + out.writeVInt(0); + return; + } + out.writeVInt(storedScripts.size()); for (Map.Entry storedScript : storedScripts.entrySet()) { out.writeString(storedScript.getKey()); diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java index 3e4aea7ea116f..b2dea0f921ff8 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java @@ -67,6 +67,10 @@ protected GetStoredScriptsResponse read(StreamInput in) throws IOException { @Override protected void masterOperation(Task task, GetStoredScriptsRequest request, ClusterState state, ActionListener listener) throws Exception { + if (request.id() != null) { + listener.onResponse(new GetStoredScriptsResponse(scriptService.getStoredScripts(state))); + return; + } Map results; diff --git a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java index 36e6eb2900f1c..f6c9ce09d07a4 100644 --- a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java +++ b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java @@ -725,6 +725,12 @@ public interface ClusterAdminClient extends ElasticsearchClient { /** * Get a script from the cluster state */ + @Deprecated + GetStoredScriptsRequestBuilder prepareGetStoredScripts(String id); + + /** + * Get scripts from the cluster state + */ GetStoredScriptsRequestBuilder prepareGetStoredScripts(String... name); /** diff --git a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java index 174829403cc42..73972ba712d2e 100644 --- a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java +++ b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java @@ -1163,6 +1163,12 @@ public GetStoredScriptRequestBuilder prepareGetStoredScript(String id) { return prepareGetStoredScript().setId(id); } + @Override + @Deprecated + public GetStoredScriptsRequestBuilder prepareGetStoredScripts(String id) { + return prepareGetStoredScripts(new String[]{id}); + } + @Override public ActionFuture getStoredScripts(GetStoredScriptsRequest request) { return execute(GetStoredScriptsAction.INSTANCE, request); From 14156e798d69bb0aa716d97bbe840bddff9c7637 Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 13 Aug 2019 22:38:43 -0700 Subject: [PATCH 16/28] Update all code to support old/new interaces. Removed *Scripts* family of classes. --- .../client/RequestConverters.java | 6 +- .../elasticsearch/client/StoredScriptsIT.java | 8 +- .../test/painless/70_get_all.yml | 8 +- .../rest-api-spec/api/delete_script.json | 2 +- .../rest-api-spec/api/get_script.json | 14 ++- .../rest-api-spec/api/get_scripts.json | 15 --- .../rest-api-spec/api/put_script.json | 4 +- .../storedscripts/GetStoredScriptRequest.java | 72 +++++++----- .../GetStoredScriptRequestBuilder.java | 5 +- .../GetStoredScriptResponse.java | 101 +++++++++++------ .../storedscripts/GetStoredScriptsAction.java | 32 ------ .../GetStoredScriptsRequest.java | 78 ------------- .../GetStoredScriptsRequestBuilder.java | 36 ------ .../GetStoredScriptsResponse.java | 101 ----------------- .../TransportGetStoredScriptAction.java | 35 +++++- .../TransportGetStoredScriptsAction.java | 107 ------------------ .../client/ClusterAdminClient.java | 28 +---- .../client/support/AbstractClient.java | 25 +--- .../cluster/RestDeleteStoredScriptAction.java | 9 +- .../cluster/RestGetStoredScriptAction.java | 39 ++++++- .../cluster/RestGetStoredScriptsAction.java | 75 ------------ .../cluster/RestPutStoredScriptAction.java | 18 ++- .../elasticsearch/script/ScriptService.java | 1 - .../GetStoredScriptResponseTests.java | 6 +- .../GetStoredScriptsRequestTests.java | 45 -------- .../elasticsearch/script/StoredScriptsIT.java | 12 +- 26 files changed, 248 insertions(+), 634 deletions(-) delete mode 100644 rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json delete mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java delete mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java delete mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java delete mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java delete mode 100644 server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java delete mode 100644 server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java delete mode 100644 server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java index 78a84b33ff83c..9342df33154c2 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java @@ -645,7 +645,7 @@ private static Request rethrottle(RethrottleRequest rethrottleRequest, String fi } static Request putScript(PutStoredScriptRequest putStoredScriptRequest) throws IOException { - String endpoint = new EndpointBuilder().addPathPartAsIs("_scripts").addPathPart(putStoredScriptRequest.id()).build(); + String endpoint = new EndpointBuilder().addPathPartAsIs("_script").addPathPart(putStoredScriptRequest.id()).build(); Request request = new Request(HttpPost.METHOD_NAME, endpoint); Params params = new Params(); params.withTimeout(putStoredScriptRequest.timeout()); @@ -702,7 +702,7 @@ static Request mtermVectors(MultiTermVectorsRequest mtvrequest) throws IOExcepti } static Request getScript(GetStoredScriptRequest getStoredScriptRequest) { - String endpoint = new EndpointBuilder().addPathPartAsIs("_scripts").addPathPart(getStoredScriptRequest.id()).build(); + String endpoint = new EndpointBuilder().addPathPartAsIs("_script").addPathPart(getStoredScriptRequest.id()).build(); Request request = new Request(HttpGet.METHOD_NAME, endpoint); Params params = new Params(); params.withMasterTimeout(getStoredScriptRequest.masterNodeTimeout()); @@ -711,7 +711,7 @@ static Request getScript(GetStoredScriptRequest getStoredScriptRequest) { } static Request deleteScript(DeleteStoredScriptRequest deleteStoredScriptRequest) { - String endpoint = new EndpointBuilder().addPathPartAsIs("_scripts").addPathPart(deleteStoredScriptRequest.id()).build(); + String endpoint = new EndpointBuilder().addPathPartAsIs("_script").addPathPart(deleteStoredScriptRequest.id()).build(); Request request = new Request(HttpDelete.METHOD_NAME, endpoint); Params params = new Params(); params.withTimeout(deleteStoredScriptRequest.timeout()); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java index 242c2d9237dff..ddd4c4e8e6fe3 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java @@ -92,10 +92,8 @@ public void testPutScript() throws Exception { new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); - Map script = getAsMap("/_scripts/" + id); - assertThat(extractValue("_id", script), equalTo(id)); - assertThat(extractValue("found", script), equalTo(true)); - assertThat(extractValue("script.lang", script), equalTo("painless")); - assertThat(extractValue("script.source", script), equalTo("Math.log(_score * 2) + params.my_modifier")); + Map script = getAsMap("/_script/" + id); + assertThat(extractValue(id + ".script.lang", script), equalTo("painless")); + assertThat(extractValue(id + ".script.source", script), equalTo("Math.log(_score * 2) + params.my_modifier")); } } diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml index 4f7e0a5cfdaf8..7f9b00f6c2ca1 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml @@ -8,18 +8,18 @@ - do: put_script: id: "1" - body: { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value" } } + body: { "script": { "lang": "painless", "source": "_score * doc['myParent.weight'].value" } } - match: { acknowledged: true } - do: put_script: id: "foo" - body: { "script": {"lang": "painless", "source": "_score * 9.9" } } + body: { "script": { "lang": "painless", "source": "_score * 9.9" } } - match: { acknowledged: true } - do: - get_scripts: {} + get_script: {} - - length: {$body: 2} + - length: { $body: 2 } - match: { 1.script: {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } - match: { foo.script: {"lang": "painless", "source": "_score * 9.9"} } diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/delete_script.json b/rest-api-spec/src/main/resources/rest-api-spec/api/delete_script.json index b38b97ae57c2e..3d199feefafb7 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/delete_script.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/delete_script.json @@ -8,7 +8,7 @@ "url":{ "paths":[ { - "path":"/_scripts/{id}", + "path":"/_script/{id}", "methods":[ "DELETE" ], diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json index 14307bea2ef0b..6c695914011f4 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json @@ -8,7 +8,19 @@ "url":{ "paths":[ { - "path":"/_scripts/{id}", + "path":"/_script", + "methods":[ + "GET" + ], + "parts":{ + "id":{ + "type":"string", + "description":"Script ID" + } + } + }, + { + "path":"/_script/{id}", "methods":[ "GET" ], diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json b/rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json deleted file mode 100644 index e254e9e5013ff..0000000000000 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/get_scripts.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "get_scripts": { - "documentation": "http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting.html", - "methods": ["GET"], - "url": { - "path": "/_scripts", - "paths": [ "/_scripts" ], - "parts": { - }, - "params" : { - } - }, - "body": null - } -} \ No newline at end of file diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/put_script.json b/rest-api-spec/src/main/resources/rest-api-spec/api/put_script.json index 750f7fdf4eb62..c3f69f1bc2472 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/put_script.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/put_script.json @@ -8,7 +8,7 @@ "url":{ "paths":[ { - "path":"/_scripts/{id}", + "path":"/_script/{id}", "methods":[ "PUT", "POST" @@ -21,7 +21,7 @@ } }, { - "path":"/_scripts/{id}/{context}", + "path":"/_script/{id}/{context}", "methods":[ "PUT", "POST" diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java index f27c14cc8fb0a..c6fe5a26c813c 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java @@ -21,6 +21,7 @@ import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.support.master.MasterNodeReadRequest; +import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; @@ -30,54 +31,73 @@ public class GetStoredScriptRequest extends MasterNodeReadRequest { - protected String id; + private String[] names; - GetStoredScriptRequest() { - super(); + public GetStoredScriptRequest() { + this(new String[]{}); } - public GetStoredScriptRequest(String id) { - super(); - - this.id = id; + public GetStoredScriptRequest(String... names) { + this.names = names; } public GetStoredScriptRequest(StreamInput in) throws IOException { super(in); - id = in.readString(); + names = in.readStringArray(); + } + + /** + * Returns he names of the scripts. + */ + public String[] names() { + return this.names; + } + + /** + * @deprecated - Needed for backwards compatibility. + * Use {@link #names()} instead + * + * Return the script if there is only one defined, null otherwise + */ + @Deprecated + public String id() { + return names != null && names.length == 1 ? names[0] : null; + } + + /** + * @deprecated - Needed for backwards compatibility. + * Set the script names param instead + */ + @Deprecated + public GetStoredScriptRequest id(String id) { + this.names = new String[] { id }; + + return this; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); - out.writeString(id); + out.writeStringArray(names); } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; - - if (id == null || id.isEmpty()) { - validationException = addValidationError("must specify id for stored script", validationException); - } else if (id.contains("#")) { - validationException = addValidationError("id cannot contain '#' for stored script", validationException); + if (names == null) { + validationException = addValidationError("names is null or empty", validationException); + } else { + for (String name : names) { + if (name == null || !Strings.hasText(name)) { + validationException = addValidationError("name is missing", validationException); + } + } } - return validationException; } - public String id() { - return id; - } - - public GetStoredScriptRequest id(String id) { - this.id = id; - - return this; - } - @Override public String toString() { - return "get script [" + id + "]"; + return "get script"; } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java index 15e96aca88049..76d8d692f092e 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java @@ -25,11 +25,14 @@ public class GetStoredScriptRequestBuilder extends MasterNodeReadOperationRequestBuilder { - public GetStoredScriptRequestBuilder(ElasticsearchClient client, GetStoredScriptAction action) { super(client, action, new GetStoredScriptRequest()); } + public GetStoredScriptRequestBuilder(ElasticsearchClient client, GetStoredScriptAction action, String... names) { + super(client, action, new GetStoredScriptRequest(names)); + } + public GetStoredScriptRequestBuilder setId(String id) { request.id(id); return this; diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java index e0058bba953f0..c242b8e52ada9 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java @@ -25,19 +25,20 @@ import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.ConstructingObjectParser; import org.elasticsearch.common.xcontent.ObjectParser; -import org.elasticsearch.common.xcontent.StatusToXContentObject; +import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; -import org.elasticsearch.rest.RestStatus; import org.elasticsearch.script.StoredScriptSource; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import java.util.Objects; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg; -public class GetStoredScriptResponse extends ActionResponse implements StatusToXContentObject { +public class GetStoredScriptResponse extends ActionResponse implements ToXContentObject { public static final ParseField _ID_PARSE_FIELD = new ParseField("_id"); public static final ParseField FOUND_PARSE_FIELD = new ParseField("found"); @@ -62,69 +63,96 @@ public class GetStoredScriptResponse extends ActionResponse implements StatusToX SCRIPT, ObjectParser.ValueType.OBJECT); } - private String id; - private StoredScriptSource source; + private Map storedScripts; - public GetStoredScriptResponse(StreamInput in) throws IOException { + GetStoredScriptResponse(StreamInput in) throws IOException { super(in); - if (in.readBoolean()) { - source = new StoredScriptSource(in); - } else { - source = null; + int size = in.readVInt(); + storedScripts = new HashMap<>(size); + for (int i = 0 ; i < size ; i++) { + String id = in.readString(); + storedScripts.put(id, new StoredScriptSource(in)); } - id = in.readString(); } GetStoredScriptResponse(String id, StoredScriptSource source) { - this.id = id; - this.source = source; + this.storedScripts = new HashMap<>(); + storedScripts.put(id, source); + } + + GetStoredScriptResponse(Map storedScripts) { + this.storedScripts = storedScripts; } - public String getId() { - return id; + public Map getStoredScripts() { + return storedScripts; } /** + * @deprecated - Needed for backwards compatibility. + * Use {@link #getStoredScripts()} instead + * * @return if a stored script and if not found null */ + @Deprecated public StoredScriptSource getSource() { - return source; - } - - @Override - public RestStatus status() { - return source != null ? RestStatus.OK : RestStatus.NOT_FOUND; + if (storedScripts != null && storedScripts.size() == 1) { + return storedScripts.entrySet().iterator().next().getValue(); + } else { + return null; + } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { +// ScriptMetaData scriptMetaData = new ScriptMetaData(getStoredScripts()); +// return scriptMetaData.toXContent(builder, params); builder.startObject(); - builder.field(_ID_PARSE_FIELD.getPreferredName(), id); - builder.field(FOUND_PARSE_FIELD.getPreferredName(), source != null); - if (source != null) { - builder.field(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); - source.toXContent(builder, params); + Map storedScripts = getStoredScripts(); + if (storedScripts != null) { + for (Map.Entry storedScript : storedScripts.entrySet()) { + builder.startObject(storedScript.getKey()); + builder.field(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); + storedScript.getValue().toXContent(builder, params); + builder.endObject(); + } } - builder.endObject(); return builder; } public static GetStoredScriptResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); + final Map storedScripts = new HashMap<>(); + for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) { + if (token == XContentParser.Token.FIELD_NAME) { + String name = parser.currentName(); + parser.nextToken(); + parser.nextToken(); + StoredScriptSource storedScriptSource = StoredScriptSource.fromXContent(parser, false); + storedScripts.put(name, storedScriptSource); + } + } + return new GetStoredScriptResponse(storedScripts); } +// public static GetStoredScriptResponse fromXContent(XContentParser parser) throws IOException { +// return PARSER.parse(parser, null); +// } + @Override public void writeTo(StreamOutput out) throws IOException { - if (source == null) { - out.writeBoolean(false); - } else { - out.writeBoolean(true); - source.writeTo(out); + if (storedScripts == null ) { + out.writeVInt(0); + return; + } + + out.writeVInt(storedScripts.size()); + for (Map.Entry storedScript : storedScripts.entrySet()) { + out.writeString(storedScript.getKey()); + storedScript.getValue().writeTo(out); } - out.writeString(id); } @Override @@ -132,12 +160,11 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GetStoredScriptResponse that = (GetStoredScriptResponse) o; - return Objects.equals(id, that.id) && - Objects.equals(source, that.source); + return Objects.equals(storedScripts, that.storedScripts); } @Override public int hashCode() { - return Objects.hash(id, source); + return storedScripts.hashCode(); } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java deleted file mode 100644 index debe140d66c51..0000000000000 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsAction.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ - -package org.elasticsearch.action.admin.cluster.storedscripts; - -import org.elasticsearch.action.ActionType; - -public class GetStoredScriptsAction extends ActionType { - - public static final GetStoredScriptsAction INSTANCE = new GetStoredScriptsAction(); - public static final String NAME = "cluster:admin/scripts/get"; - - private GetStoredScriptsAction() { - super(NAME, GetStoredScriptsResponse::new); - } -} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java deleted file mode 100644 index c97f8610de5ad..0000000000000 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ - -package org.elasticsearch.action.admin.cluster.storedscripts; - -import org.elasticsearch.action.ActionRequestValidationException; -import org.elasticsearch.action.support.master.MasterNodeReadRequest; -import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.common.io.stream.StreamOutput; - -import java.io.IOException; - -public class GetStoredScriptsRequest extends MasterNodeReadRequest { - - private String[] names; - - public GetStoredScriptsRequest() { - super(); - } - - public GetStoredScriptsRequest(String... names) { - this.names = names; - } - - public GetStoredScriptsRequest(StreamInput in) throws IOException { - super(in); - names = in.readStringArray(); - } - - /** - * The names of the search templates. - */ - public String[] names() { - return this.names; - } - - /** - * @deprecated - Needed for backwards compatibility. - * * Use {@link #names()} instead - */ - @Deprecated - public String id() { - return names != null && names.length == 1 ? names[0] : null; - } - - @Override - public void writeTo(StreamOutput out) throws IOException { - super.writeTo(out); - out.writeStringArray(names); - } - - @Override - public ActionRequestValidationException validate() { - return null; - } - - @Override - public String toString() { - return "get scripts"; - } - -} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java deleted file mode 100644 index a2522ceb68b3c..0000000000000 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestBuilder.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ - -package org.elasticsearch.action.admin.cluster.storedscripts; - -import org.elasticsearch.action.support.master.MasterNodeReadOperationRequestBuilder; -import org.elasticsearch.client.ElasticsearchClient; - -public class GetStoredScriptsRequestBuilder extends - MasterNodeReadOperationRequestBuilder { - - public GetStoredScriptsRequestBuilder(ElasticsearchClient client, GetStoredScriptsAction action) { - super(client, action, new GetStoredScriptsRequest()); - } - - public GetStoredScriptsRequestBuilder(ElasticsearchClient client, GetStoredScriptsAction action, String... names) { - super(client, action, new GetStoredScriptsRequest(names)); - } -} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java deleted file mode 100644 index 50437902d03bf..0000000000000 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsResponse.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ - -package org.elasticsearch.action.admin.cluster.storedscripts; - -import org.elasticsearch.action.ActionResponse; -import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.common.xcontent.ToXContentObject; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.script.StoredScriptSource; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -public class GetStoredScriptsResponse extends ActionResponse implements ToXContentObject { - - private Map storedScripts; - - GetStoredScriptsResponse(StreamInput in) throws IOException { - super(in); - - int size = in.readVInt(); - storedScripts = new HashMap<>(size); - for (int i = 0 ; i < size ; i++) { - String id = in.readString(); - storedScripts.put(id, new StoredScriptSource(in)); - } - } - - GetStoredScriptsResponse(Map storedScripts) { - this.storedScripts = storedScripts; - } - - public Map getStoredScripts() { - return storedScripts; - } - - /** - * @deprecated - Needed for backwards compatibility. - * Use {@link #getStoredScripts()} instead - * - * @return if a stored script and if not found null - */ - @Deprecated - public StoredScriptSource getSource() { - if (storedScripts != null && storedScripts.size() == 1) { - return storedScripts.entrySet().iterator().next().getValue(); - } else { - return null; - } - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - - Map storedScripts = getStoredScripts(); - if (storedScripts != null) { - for (Map.Entry storedScript : storedScripts.entrySet()) { - builder.startObject(storedScript.getKey()); - builder.field(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); - storedScript.getValue().toXContent(builder, params); - builder.endObject(); - } - } - builder.endObject(); - return builder; - } - - @Override - public void writeTo(StreamOutput out) throws IOException { - if (storedScripts == null ) { - out.writeVInt(0); - return; - } - - out.writeVInt(storedScripts.size()); - for (Map.Entry storedScript : storedScripts.entrySet()) { - out.writeString(storedScript.getKey()); - storedScript.getValue().writeTo(out); - } - } -} diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java index 4de6dfef713dc..1a516309fbc8e 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java @@ -29,12 +29,16 @@ import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.regex.Regex; import org.elasticsearch.script.ScriptService; +import org.elasticsearch.script.StoredScriptSource; import org.elasticsearch.tasks.Task; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; public class TransportGetStoredScriptAction extends TransportMasterNodeReadAction { @@ -63,7 +67,36 @@ protected GetStoredScriptResponse read(StreamInput in) throws IOException { @Override protected void masterOperation(Task task, GetStoredScriptRequest request, ClusterState state, ActionListener listener) throws Exception { - listener.onResponse(new GetStoredScriptResponse(request.id(), scriptService.getStoredScript(state, request))); + if (request.id() != null) { + listener.onResponse(new GetStoredScriptResponse(scriptService.getStoredScripts(state))); + return; + } + + Map results; + + Map storedScripts = scriptService.getStoredScripts(state); + // If we did not ask for a specific name, then we return all templates + if (request.names().length == 0) { + results = storedScripts; + } else { + results = new HashMap<>(); + } + + if (storedScripts != null) { + for (String name : request.names()) { + if (Regex.isSimpleMatchPattern(name)) { + for (Map.Entry entry : storedScripts.entrySet()) { + if (Regex.simpleMatch(name, entry.getKey())) { + results.put(entry.getKey(), entry.getValue()); + } + } + } else if (storedScripts.containsKey(name)) { + results.put(name, storedScripts.get(name)); + } + } + } + + listener.onResponse(new GetStoredScriptResponse(results)); } @Override diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java deleted file mode 100644 index b2dea0f921ff8..0000000000000 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptsAction.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ - -package org.elasticsearch.action.admin.cluster.storedscripts; - -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.support.ActionFilters; -import org.elasticsearch.action.support.master.TransportMasterNodeReadAction; -import org.elasticsearch.cluster.ClusterState; -import org.elasticsearch.cluster.block.ClusterBlockException; -import org.elasticsearch.cluster.block.ClusterBlockLevel; -import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; -import org.elasticsearch.cluster.service.ClusterService; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.common.regex.Regex; -import org.elasticsearch.script.ScriptService; -import org.elasticsearch.script.StoredScriptSource; -import org.elasticsearch.tasks.Task; -import org.elasticsearch.threadpool.ThreadPool; -import org.elasticsearch.transport.TransportService; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -public class TransportGetStoredScriptsAction extends TransportMasterNodeReadAction { - - private final ScriptService scriptService; - - @Inject - public TransportGetStoredScriptsAction(TransportService transportService, ClusterService clusterService, - ThreadPool threadPool, ActionFilters actionFilters, - IndexNameExpressionResolver indexNameExpressionResolver, ScriptService scriptService) { - super(GetStoredScriptsAction.NAME, transportService, clusterService, threadPool, actionFilters, - GetStoredScriptsRequest::new, indexNameExpressionResolver); - this.scriptService = scriptService; - } - - @Override - protected String executor() { - return ThreadPool.Names.SAME; - } - - @Override - protected GetStoredScriptsResponse read(StreamInput in) throws IOException { - return new GetStoredScriptsResponse(in); - } - - @Override - protected void masterOperation(Task task, GetStoredScriptsRequest request, ClusterState state, - ActionListener listener) throws Exception { - if (request.id() != null) { - listener.onResponse(new GetStoredScriptsResponse(scriptService.getStoredScripts(state))); - return; - } - - Map results; - - Map storedScripts = scriptService.getStoredScripts(state); - // If we did not ask for a specific name, then we return all templates - if (request.names().length == 0) { - results = storedScripts; - } else { - results = new HashMap<>(); - } - - if (storedScripts != null) { - for (String name : request.names()) { - if (Regex.isSimpleMatchPattern(name)) { - for (Map.Entry entry : storedScripts.entrySet()) { - if (Regex.simpleMatch(name, entry.getKey())) { - results.put(entry.getKey(), entry.getValue()); - } - } - } else if (storedScripts.containsKey(name)) { - results.put(name, storedScripts.get(name)); - } - } - } - - listener.onResponse(new GetStoredScriptsResponse(results)); - } - - @Override - protected ClusterBlockException checkBlock(GetStoredScriptsRequest request, ClusterState state) { - return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); - } - -} diff --git a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java index f6c9ce09d07a4..25c4c19cdbc8e 100644 --- a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java +++ b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java @@ -96,9 +96,6 @@ import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequestBuilder; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequestBuilder; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequestBuilder; import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksRequest; @@ -710,36 +707,21 @@ public interface ClusterAdminClient extends ElasticsearchClient { /** * Get a script from the cluster state */ + @Deprecated GetStoredScriptRequestBuilder prepareGetStoredScript(String id); /** - * Get a script from the cluster state + * Get scripts from the cluster state */ - void getStoredScript(GetStoredScriptRequest request, ActionListener listener); + GetStoredScriptRequestBuilder prepareGetStoredScript(String... name); /** * Get a script from the cluster state */ - ActionFuture getStoredScript(GetStoredScriptRequest request); + void getStoredScript(GetStoredScriptRequest request, ActionListener listener); /** * Get a script from the cluster state */ - @Deprecated - GetStoredScriptsRequestBuilder prepareGetStoredScripts(String id); - - /** - * Get scripts from the cluster state - */ - GetStoredScriptsRequestBuilder prepareGetStoredScripts(String... name); - - /** - * Get all scripts from the cluster state - */ - void getStoredScripts(GetStoredScriptsRequest request, ActionListener listener); - - /** - * Get all scripts from the cluster state - */ - ActionFuture getStoredScripts(GetStoredScriptsRequest request); + ActionFuture getStoredScript(GetStoredScriptRequest request); } diff --git a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java index 73972ba712d2e..3f26b205c67db 100644 --- a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java +++ b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java @@ -128,10 +128,6 @@ import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequestBuilder; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsAction; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequestBuilder; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptAction; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequest; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequestBuilder; @@ -1164,25 +1160,8 @@ public GetStoredScriptRequestBuilder prepareGetStoredScript(String id) { } @Override - @Deprecated - public GetStoredScriptsRequestBuilder prepareGetStoredScripts(String id) { - return prepareGetStoredScripts(new String[]{id}); - } - - @Override - public ActionFuture getStoredScripts(GetStoredScriptsRequest request) { - return execute(GetStoredScriptsAction.INSTANCE, request); - } - - @Override - public void getStoredScripts(GetStoredScriptsRequest request, - ActionListener listener) { - execute(GetStoredScriptsAction.INSTANCE, request, listener); - } - - @Override - public GetStoredScriptsRequestBuilder prepareGetStoredScripts(String... names) { - return new GetStoredScriptsRequestBuilder(this, GetStoredScriptsAction.INSTANCE, names); + public GetStoredScriptRequestBuilder prepareGetStoredScript(String... names) { + return new GetStoredScriptRequestBuilder(this, GetStoredScriptAction.INSTANCE, names); } @Override diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java index a0258974cfc41..05bcd4e19038c 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java @@ -18,8 +18,11 @@ */ package org.elasticsearch.rest.action.admin.cluster; +import org.apache.logging.log4j.LogManager; import org.elasticsearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest; import org.elasticsearch.client.node.NodeClient; +import org.elasticsearch.common.logging.DeprecationLogger; +import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; @@ -31,8 +34,12 @@ public class RestDeleteStoredScriptAction extends BaseRestHandler { + private static final DeprecationLogger deprecationLogger = + new DeprecationLogger(LogManager.getLogger(RestGetStoredScriptAction.class)); + public RestDeleteStoredScriptAction(RestController controller) { - controller.registerHandler(DELETE, "/_scripts/{id}", this); + controller.registerWithDeprecatedHandler(DELETE, "/_script/{id}", this, + DELETE, "/_scripts/{id}", deprecationLogger); } @Override diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java index f87c6f513b79c..9f4543e09c1ce 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java @@ -18,21 +18,38 @@ */ package org.elasticsearch.rest.action.admin.cluster; +import org.apache.logging.log4j.LogManager; import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptRequest; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse; import org.elasticsearch.client.node.NodeClient; +import org.elasticsearch.common.Strings; +import org.elasticsearch.common.logging.DeprecationLogger; +import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; -import org.elasticsearch.rest.action.RestStatusToXContentListener; +import org.elasticsearch.rest.RestStatus; +import org.elasticsearch.rest.action.RestToXContentListener; +import org.elasticsearch.script.StoredScriptSource; import java.io.IOException; +import java.util.Map; import static org.elasticsearch.rest.RestRequest.Method.GET; +import static org.elasticsearch.rest.RestRequest.Method.HEAD; +import static org.elasticsearch.rest.RestStatus.NOT_FOUND; +import static org.elasticsearch.rest.RestStatus.OK; public class RestGetStoredScriptAction extends BaseRestHandler { + private static final DeprecationLogger deprecationLogger = + new DeprecationLogger(LogManager.getLogger(RestGetStoredScriptAction.class)); + public RestGetStoredScriptAction(RestController controller) { - controller.registerHandler(GET, "/_scripts/{id}", this); + controller.registerHandler(GET, "/_script", this); + controller.registerWithDeprecatedHandler(GET, "/_script/{name}", this, + GET, "/_scripts/{name}", deprecationLogger); + controller.registerHandler(HEAD, "/_script/{name}", this); } @Override @@ -42,9 +59,21 @@ public String getName() { @Override public RestChannelConsumer prepareRequest(final RestRequest request, NodeClient client) throws IOException { - String id = request.param("id"); - GetStoredScriptRequest getRequest = new GetStoredScriptRequest(id); + final String[] names = Strings.splitStringByCommaToArray(request.param("name")); + + GetStoredScriptRequest getRequest = new GetStoredScriptRequest(names); getRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRequest.masterNodeTimeout())); - return channel -> client.admin().cluster().getStoredScript(getRequest, new RestStatusToXContentListener<>(channel)); + + final boolean implicitAll = getRequest.names().length == 0; + + return channel -> client.admin().cluster().getStoredScript(getRequest, new RestToXContentListener<>(channel) { + @Override + protected RestStatus getStatus(final GetStoredScriptResponse response) + { + Map storedScripts = response.getStoredScripts(); + final boolean templateExists = storedScripts != null && !storedScripts.isEmpty(); + return (templateExists || implicitAll) ? OK : NOT_FOUND; + } + }); } } diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java deleted file mode 100644 index 5e272ae5ba1e1..0000000000000 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptsAction.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ -package org.elasticsearch.rest.action.admin.cluster; - -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsRequest; -import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptsResponse; -import org.elasticsearch.client.node.NodeClient; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.rest.BaseRestHandler; -import org.elasticsearch.rest.RestController; -import org.elasticsearch.rest.RestRequest; -import org.elasticsearch.rest.RestStatus; -import org.elasticsearch.rest.action.RestToXContentListener; -import org.elasticsearch.script.StoredScriptSource; - -import java.io.IOException; -import java.util.Map; - -import static org.elasticsearch.rest.RestRequest.Method.GET; -import static org.elasticsearch.rest.RestRequest.Method.HEAD; -import static org.elasticsearch.rest.RestStatus.NOT_FOUND; -import static org.elasticsearch.rest.RestStatus.OK; - -public class RestGetStoredScriptsAction extends BaseRestHandler { - - public RestGetStoredScriptsAction(Settings settings, RestController controller) { - super(settings); - - controller.registerHandler(GET, "/_scripts", this); - controller.registerHandler(GET, "/_script/{name}", this); - controller.registerHandler(HEAD, "/_script/{name}", this); - } - - @Override - public String getName() { - return "get_all_stored_scripts_action"; - } - - @Override - public RestChannelConsumer prepareRequest(final RestRequest request, NodeClient client) throws IOException { - final String[] names = Strings.splitStringByCommaToArray(request.param("name")); - - GetStoredScriptsRequest getRequest = new GetStoredScriptsRequest(names); - getRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRequest.masterNodeTimeout())); - - final boolean implicitAll = getRequest.names().length == 0; - - return channel -> client.admin().cluster().getStoredScripts(getRequest, new RestToXContentListener<>(channel) { - @Override - protected RestStatus getStatus(final GetStoredScriptsResponse response) - { - Map storedScripts = response.getStoredScripts(); - final boolean templateExists = storedScripts != null && !storedScripts.isEmpty(); - return (templateExists || implicitAll) ? OK : NOT_FOUND; - } - }); - } -} diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java index 2e316abc14296..b86f81e46766a 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java @@ -18,9 +18,12 @@ */ package org.elasticsearch.rest.action.admin.cluster; +import org.apache.logging.log4j.LogManager; import org.elasticsearch.action.admin.cluster.storedscripts.PutStoredScriptRequest; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.bytes.BytesReference; +import org.elasticsearch.common.logging.DeprecationLogger; +import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; @@ -35,11 +38,18 @@ public class RestPutStoredScriptAction extends BaseRestHandler { + private static final DeprecationLogger deprecationLogger = + new DeprecationLogger(LogManager.getLogger(RestGetStoredScriptAction.class)); + public RestPutStoredScriptAction(RestController controller) { - controller.registerHandler(POST, "/_scripts/{id}", this); - controller.registerHandler(PUT, "/_scripts/{id}", this); - controller.registerHandler(POST, "/_scripts/{id}/{context}", this); - controller.registerHandler(PUT, "/_scripts/{id}/{context}", this); + controller.registerWithDeprecatedHandler(POST, "/_script/{id}", this, + POST, "/_scripts/{id}", deprecationLogger); + controller.registerWithDeprecatedHandler(PUT, "/_script/{id}", this, + PUT, "/_scripts/{id}", deprecationLogger); + controller.registerWithDeprecatedHandler(POST, "/_script/{id}/{context}", this, + POST, "/_scripts/{id}/{context}", deprecationLogger); + controller.registerWithDeprecatedHandler(PUT, "/_script/{id}/{context}", this, + PUT, "/_scripts/{id}/{context}", deprecationLogger); } @Override diff --git a/server/src/main/java/org/elasticsearch/script/ScriptService.java b/server/src/main/java/org/elasticsearch/script/ScriptService.java index 1425b8746ad6e..b1258b74b0c35 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptService.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptService.java @@ -548,7 +548,6 @@ public Map getStoredScripts(ClusterState state) { } } - public ScriptStats stats() { return scriptMetrics.stats(); } diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java index 8bea7fecc571a..5bd6e64cec2fd 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java @@ -26,6 +26,7 @@ import java.io.IOException; import java.util.Collections; +import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; @@ -38,7 +39,10 @@ protected GetStoredScriptResponse doParseInstance(XContentParser parser) throws @Override protected GetStoredScriptResponse createTestInstance() { - return new GetStoredScriptResponse(randomAlphaOfLengthBetween(1, 10), randomScriptSource()); + Map storedScripts = new HashMap<>(); + storedScripts.put(randomAlphaOfLengthBetween(1, 10), randomScriptSource()); + + return new GetStoredScriptResponse(storedScripts); } @Override diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java deleted file mode 100644 index 4c2dd2b617152..0000000000000 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptsRequestTests.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch 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. - */ - -package org.elasticsearch.action.admin.cluster.storedscripts; - -import org.elasticsearch.common.io.stream.BytesStreamOutput; -import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.test.ESTestCase; - -import java.io.IOException; - -import static org.elasticsearch.test.VersionUtils.randomVersion; -import static org.hamcrest.CoreMatchers.equalTo; - -public class GetStoredScriptsRequestTests extends ESTestCase { - public void testGetIndexedScriptsRequestSerialization() throws IOException { - GetStoredScriptsRequest request = new GetStoredScriptsRequest(); - - BytesStreamOutput out = new BytesStreamOutput(); - out.setVersion(randomVersion(random())); - request.writeTo(out); - - StreamInput in = out.bytes().streamInput(); - in.setVersion(out.getVersion()); - GetStoredScriptsRequest request2 = new GetStoredScriptsRequest(in); - - assertThat(request2, equalTo(request)); - } -} diff --git a/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java b/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java index 3f0f1801735bd..a2771a1c00c3d 100644 --- a/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java +++ b/server/src/test/java/org/elasticsearch/script/StoredScriptsIT.java @@ -18,6 +18,7 @@ */ package org.elasticsearch.script; +import org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentType; @@ -53,16 +54,15 @@ public void testBasics() { assertAcked(client().admin().cluster().preparePutStoredScript() .setId("foobar") .setContent(new BytesArray("{\"script\": {\"lang\": \"" + LANG + "\", \"source\": \"1\"} }"), XContentType.JSON)); - String script = client().admin().cluster().prepareGetStoredScript("foobar") - .get().getSource().getSource(); + String script = client().admin().cluster().prepareGetStoredScript("foobar").get().getSource().getSource(); assertNotNull(script); assertEquals("1", script); assertAcked(client().admin().cluster().prepareDeleteStoredScript() .setId("foobar")); - StoredScriptSource source = client().admin().cluster().prepareGetStoredScript("foobar") - .get().getSource(); - assertNull(source); + GetStoredScriptResponse response = client().admin().cluster().prepareGetStoredScript("foobar") + .get(); + assertEquals(0, response.getStoredScripts().size()); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> client().admin().cluster().preparePutStoredScript() .setId("id#") @@ -81,7 +81,7 @@ public void testGetAllScripts() { .setContent(new BytesArray("{\"script\": {\"lang\": \"" + LANG + "\", \"source\": \"9.9\"} }"), XContentType.JSON)); - Map storedScripts = client().admin().cluster().prepareGetStoredScripts().get().getStoredScripts(); + Map storedScripts = client().admin().cluster().prepareGetStoredScript().get().getStoredScripts(); assertEquals(2, storedScripts.size()); StoredScriptSource source = storedScripts.get("foobar"); From 7ea45075a173cc1ab3d516d453ab45166eb50525 Mon Sep 17 00:00:00 2001 From: ivan Date: Wed, 14 Aug 2019 21:39:27 -0700 Subject: [PATCH 17/28] Change all /_scripts references to /_script --- .../client/RequestConvertersTests.java | 6 ++-- .../documentation/CRUDDocumentationIT.java | 2 +- .../documentation/SearchDocumentationIT.java | 2 +- .../StoredScriptsDocumentationIT.java | 12 +++---- .../test/rest/RequestsWithoutContentIT.java | 2 +- .../bucket/range-aggregation.asciidoc | 2 +- .../bucket/terms-aggregation.asciidoc | 2 +- docs/reference/scripting/using.asciidoc | 10 +++--- docs/reference/search/multi-search.asciidoc | 4 +-- .../reference/search/search-template.asciidoc | 12 +++---- .../test/painless/16_update2.yml | 6 +--- .../test/painless/70_get_all.yml | 4 +-- .../rest-api-spec/api/get_script.json | 20 +++++++++++ .../GetStoredScriptResponse.java | 35 ++++++++++++++----- .../TransportGetStoredScriptAction.java | 5 --- .../cluster/RestDeleteStoredScriptAction.java | 1 - .../cluster/RestGetStoredScriptAction.java | 9 +++-- .../cluster/RestPutStoredScriptAction.java | 1 - 18 files changed, 80 insertions(+), 55 deletions(-) diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/RequestConvertersTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/RequestConvertersTests.java index 8ec5bd1d57c0a..ff8f0d606b7b4 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/RequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/RequestConvertersTests.java @@ -1612,7 +1612,7 @@ public void testPutScript() throws Exception { Request request = RequestConverters.putScript(putStoredScriptRequest); - assertThat(request.getEndpoint(), equalTo("/_scripts/" + id)); + assertThat(request.getEndpoint(), equalTo("/_script/" + id)); assertThat(request.getParameters(), equalTo(expectedParams)); assertNotNull(request.getEntity()); assertToXContentBody(putStoredScriptRequest, request.getEntity()); @@ -1636,7 +1636,7 @@ public void testGetScriptRequest() { setRandomMasterTimeout(getStoredScriptRequest, expectedParams); Request request = RequestConverters.getScript(getStoredScriptRequest); - assertThat(request.getEndpoint(), equalTo("/_scripts/" + getStoredScriptRequest.id())); + assertThat(request.getEndpoint(), equalTo("/_script/" + getStoredScriptRequest.id())); assertThat(request.getMethod(), equalTo(HttpGet.METHOD_NAME)); assertThat(request.getParameters(), equalTo(expectedParams)); assertThat(request.getEntity(), nullValue()); @@ -1650,7 +1650,7 @@ public void testDeleteScriptRequest() { setRandomMasterTimeout(deleteStoredScriptRequest, expectedParams); Request request = RequestConverters.deleteScript(deleteStoredScriptRequest); - assertThat(request.getEndpoint(), equalTo("/_scripts/" + deleteStoredScriptRequest.id())); + assertThat(request.getEndpoint(), equalTo("/_script/" + deleteStoredScriptRequest.id())); assertThat(request.getMethod(), equalTo(HttpDelete.METHOD_NAME)); assertThat(request.getParameters(), equalTo(expectedParams)); assertThat(request.getEntity(), nullValue()); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/CRUDDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/CRUDDocumentationIT.java index 062f90c0eb4db..30fb908590fb9 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/CRUDDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/CRUDDocumentationIT.java @@ -284,7 +284,7 @@ public void testUpdate() throws Exception { IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT); assertSame(RestStatus.CREATED, indexResponse.status()); - Request request = new Request("POST", "/_scripts/increment-field"); + Request request = new Request("POST", "/_script/increment-field"); request.setJsonEntity(Strings.toString(JsonXContent.contentBuilder() .startObject() .startObject("script") diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SearchDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SearchDocumentationIT.java index ff5deb5cbdfcc..fd80446863ce2 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SearchDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SearchDocumentationIT.java @@ -962,7 +962,7 @@ public void onFailure(Exception e) { protected void registerQueryScript(RestClient restClient) throws IOException { // tag::register-script - Request scriptRequest = new Request("POST", "_scripts/title_search"); + Request scriptRequest = new Request("POST", "_script/title_search"); scriptRequest.setJsonEntity( "{" + " \"script\": {" + diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java index ac4f2269f9c79..f980d6f0a02eb 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java @@ -103,7 +103,7 @@ public void testGetStoredScript() throws Exception { // tag::get-stored-script-execute-listener ActionListener listener = - new ActionListener() { + new ActionListener<>() { @Override public void onResponse(GetStoredScriptResponse response) { // <1> @@ -166,7 +166,7 @@ public void testDeleteStoredScript() throws Exception { // tag::delete-stored-script-execute-listener ActionListener listener = - new ActionListener() { + new ActionListener<>() { @Override public void onResponse(AcknowledgedResponse response) { // <1> @@ -254,7 +254,7 @@ public void testPutScript() throws Exception { // tag::put-stored-script-execute-listener ActionListener listener = - new ActionListener() { + new ActionListener<>() { @Override public void onResponse(AcknowledgedResponse response) { // <1> @@ -299,9 +299,9 @@ public void onFailure(Exception e) { client.putScript(request, RequestOptions.DEFAULT); - Map script = getAsMap("/_scripts/id"); - assertThat(extractValue("script.lang", script), equalTo("mustache")); - assertThat(extractValue("script.source", script), equalTo("{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}")); + Map script = getAsMap("/_script/id"); + assertThat(extractValue("id.script.lang", script), equalTo("mustache")); + assertThat(extractValue("id.script.source", script), equalTo("{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}")); } } diff --git a/distribution/archives/integ-test-zip/src/test/java/org/elasticsearch/test/rest/RequestsWithoutContentIT.java b/distribution/archives/integ-test-zip/src/test/java/org/elasticsearch/test/rest/RequestsWithoutContentIT.java index 4d27f156b3826..f8ada87df5acd 100644 --- a/distribution/archives/integ-test-zip/src/test/java/org/elasticsearch/test/rest/RequestsWithoutContentIT.java +++ b/distribution/archives/integ-test-zip/src/test/java/org/elasticsearch/test/rest/RequestsWithoutContentIT.java @@ -78,7 +78,7 @@ public void testSimulatePipelineMissingBody() throws IOException { public void testPutScriptMissingBody() throws IOException { ResponseException responseException = expectThrows(ResponseException.class, () -> - client().performRequest(new Request(randomBoolean() ? "POST" : "PUT", "/_scripts/lang"))); + client().performRequest(new Request(randomBoolean() ? "POST" : "PUT", "/_script/lang"))); assertResponseException(responseException, "request body is required"); } diff --git a/docs/reference/aggregations/bucket/range-aggregation.asciidoc b/docs/reference/aggregations/bucket/range-aggregation.asciidoc index 8ff26c7c92f5c..f5c844359ab8a 100644 --- a/docs/reference/aggregations/bucket/range-aggregation.asciidoc +++ b/docs/reference/aggregations/bucket/range-aggregation.asciidoc @@ -204,7 +204,7 @@ It is also possible to use stored scripts. Here is a simple stored script: [source,js] -------------------------------------------------- -POST /_scripts/convert_currency +POST /_script/convert_currency { "script": { "lang": "painless", diff --git a/docs/reference/aggregations/bucket/terms-aggregation.asciidoc b/docs/reference/aggregations/bucket/terms-aggregation.asciidoc index b40302b6120e9..a29f8ab92073f 100644 --- a/docs/reference/aggregations/bucket/terms-aggregation.asciidoc +++ b/docs/reference/aggregations/bucket/terms-aggregation.asciidoc @@ -572,7 +572,7 @@ This will interpret the `script` parameter as an `inline` script with the defaul [source,js] -------------------------------------------------- -POST /_scripts/my_script +POST /_script/my_script { "script": { "lang": "painless", diff --git a/docs/reference/scripting/using.asciidoc b/docs/reference/scripting/using.asciidoc index 5060c7fc67d2f..e95f50b4419ce 100644 --- a/docs/reference/scripting/using.asciidoc +++ b/docs/reference/scripting/using.asciidoc @@ -134,19 +134,19 @@ The same script in the normal form: === Stored scripts Scripts may be stored in and retrieved from the cluster state using the -`_scripts` end-point. +`_script` end-point. [float] ==== Request examples The following are examples of using a stored script that lives at -`/_scripts/{id}`. +`/_script/{id}`. First, create the script called `calculate-score` in the cluster state: [source,js] ----------------------------------- -POST _scripts/calculate-score +POST _script/calculate-score { "script": { "lang": "painless", @@ -160,7 +160,7 @@ This same script can be retrieved with: [source,js] ----------------------------------- -GET _scripts/calculate-score +GET _script/calculate-score ----------------------------------- // CONSOLE // TEST[continued] @@ -190,7 +190,7 @@ And deleted with: [source,js] ----------------------------------- -DELETE _scripts/calculate-score +DELETE _script/calculate-score ----------------------------------- // CONSOLE // TEST[continued] diff --git a/docs/reference/search/multi-search.asciidoc b/docs/reference/search/multi-search.asciidoc index 42dbd0f5c2a1a..cf4a6968072de 100644 --- a/docs/reference/search/multi-search.asciidoc +++ b/docs/reference/search/multi-search.asciidoc @@ -126,7 +126,7 @@ You can also create search templates: [source,js] ------------------------------------------ -POST /_scripts/my_template_1 +POST /_script/my_template_1 { "script": { "lang": "mustache", @@ -145,7 +145,7 @@ POST /_scripts/my_template_1 [source,js] ------------------------------------------ -POST /_scripts/my_template_2 +POST /_script/my_template_2 { "script": { "lang": "mustache", diff --git a/docs/reference/search/search-template.asciidoc b/docs/reference/search/search-template.asciidoc index 950477aa7d320..570ab0a7a25d3 100644 --- a/docs/reference/search/search-template.asciidoc +++ b/docs/reference/search/search-template.asciidoc @@ -42,7 +42,7 @@ You can store a search template using the stored scripts API. [source,js] ------------------------------------------ -POST _scripts/ +POST _script/ { "script": { "lang": "mustache", @@ -78,7 +78,7 @@ This template can be retrieved by [source,js] ------------------------------------------ -GET _scripts/ +GET _script/ ------------------------------------------ // CONSOLE // TEST[continued] @@ -88,15 +88,13 @@ which is rendered as: [source,js] ------------------------------------------ { - "script" : { + "" : { "lang" : "mustache", "source" : "{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}", "options": { "content_type" : "application/json; charset=UTF-8" } - }, - "_id": "", - "found": true + } } ------------------------------------------ // TESTRESPONSE @@ -105,7 +103,7 @@ This template can be deleted by [source,js] ------------------------------------------ -DELETE _scripts/ +DELETE _script/ ------------------------------------------ // CONSOLE // TEST[continued] diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml index 999733ff14be7..4a6bc23bf1947 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml @@ -12,16 +12,12 @@ - do: get_script: id: "1" - - match: { found: true } - - match: { _id: "1" } - - match: { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } + - match: { "1" : { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } } - do: catch: missing get_script: id: "2" - - match: { found: false } - - match: { _id: "2" } - is_false: script - do: diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml index 7f9b00f6c2ca1..a92674c754e5b 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml @@ -2,8 +2,8 @@ "Get all scripts": - skip: - version: " - 6.99.99" - reason: this uses a new API that has been added in 7.0 + version: " - 7.99.99" + reason: this uses a new API that has been added in 8.0 - do: put_script: diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json index 6c695914011f4..e4096d781c344 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json @@ -30,6 +30,22 @@ "description":"Script ID" } } + }, + { + "path":"/_scripts/{id}", + "methods":[ + "GET" + ], + "parts":{ + "id":{ + "type":"string", + "description":"Script ID" + } + }, + "deprecated":{ + "version":"8.0.0", + "description":"The path is now singular" + } } ] }, @@ -37,6 +53,10 @@ "master_timeout":{ "type":"time", "description":"Specify timeout for connection to master" + }, + "new_format": { + "type" : "boolean", + "description" : "Use the new format" } } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java index c242b8e52ada9..72d4449347b40 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java @@ -40,9 +40,9 @@ public class GetStoredScriptResponse extends ActionResponse implements ToXContentObject { - public static final ParseField _ID_PARSE_FIELD = new ParseField("_id"); - public static final ParseField FOUND_PARSE_FIELD = new ParseField("found"); - public static final ParseField SCRIPT = new ParseField("script"); + private static final ParseField _ID_PARSE_FIELD = new ParseField("_id"); + private static final ParseField FOUND_PARSE_FIELD = new ParseField("found"); + private static final ParseField SCRIPT = new ParseField("script"); private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("GetStoredScriptResponse", @@ -106,8 +106,9 @@ public StoredScriptSource getSource() { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { -// ScriptMetaData scriptMetaData = new ScriptMetaData(getStoredScripts()); -// return scriptMetaData.toXContent(builder, params); + if (params.paramAsBoolean("new_format", false)) { + return toXContentPre80(builder, params); + } builder.startObject(); Map storedScripts = getStoredScripts(); @@ -137,9 +138,27 @@ public static GetStoredScriptResponse fromXContent(XContentParser parser) throws return new GetStoredScriptResponse(storedScripts); } -// public static GetStoredScriptResponse fromXContent(XContentParser parser) throws IOException { -// return PARSER.parse(parser, null); -// } + private XContentBuilder toXContentPre80(XContentBuilder builder, Params params) throws IOException { + builder.startObject(); + + Map.Entry entry = storedScripts.entrySet().iterator().next(); + String id = entry.getKey(); + StoredScriptSource source = entry.getValue(); + + builder.field(_ID_PARSE_FIELD.getPreferredName(), id); + builder.field(FOUND_PARSE_FIELD.getPreferredName(), source != null); + if (source != null) { + builder.field(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); + source.toXContent(builder, params); + } + + builder.endObject(); + return builder; + } + + public static GetStoredScriptResponse fromXContentPre80(XContentParser parser) throws IOException { + return PARSER.parse(parser, null); + } @Override public void writeTo(StreamOutput out) throws IOException { diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java index 1a516309fbc8e..28ac7178ac8b2 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java @@ -67,11 +67,6 @@ protected GetStoredScriptResponse read(StreamInput in) throws IOException { @Override protected void masterOperation(Task task, GetStoredScriptRequest request, ClusterState state, ActionListener listener) throws Exception { - if (request.id() != null) { - listener.onResponse(new GetStoredScriptResponse(scriptService.getStoredScripts(state))); - return; - } - Map results; Map storedScripts = scriptService.getStoredScripts(state); diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java index 05bcd4e19038c..57d76a40bba06 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestDeleteStoredScriptAction.java @@ -22,7 +22,6 @@ import org.elasticsearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.logging.DeprecationLogger; -import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java index 9f4543e09c1ce..ef5c869430800 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java @@ -24,7 +24,6 @@ import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.logging.DeprecationLogger; -import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; @@ -47,19 +46,19 @@ public class RestGetStoredScriptAction extends BaseRestHandler { public RestGetStoredScriptAction(RestController controller) { controller.registerHandler(GET, "/_script", this); - controller.registerWithDeprecatedHandler(GET, "/_script/{name}", this, + controller.registerWithDeprecatedHandler(GET, "/_script/{id}", this, GET, "/_scripts/{name}", deprecationLogger); - controller.registerHandler(HEAD, "/_script/{name}", this); + controller.registerHandler(HEAD, "/_script/{id}", this); } @Override public String getName() { - return "get_stored_scripts_action"; + return "get_stored_script_action"; } @Override public RestChannelConsumer prepareRequest(final RestRequest request, NodeClient client) throws IOException { - final String[] names = Strings.splitStringByCommaToArray(request.param("name")); + final String[] names = Strings.splitStringByCommaToArray(request.param("id")); GetStoredScriptRequest getRequest = new GetStoredScriptRequest(names); getRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRequest.masterNodeTimeout())); diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java index b86f81e46766a..91e3d2d13194c 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPutStoredScriptAction.java @@ -23,7 +23,6 @@ import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.logging.DeprecationLogger; -import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; From b0ba004555e136a0105ef8b7315c2de9ad3517e6 Mon Sep 17 00:00:00 2001 From: ivan Date: Thu, 15 Aug 2019 00:25:50 -0700 Subject: [PATCH 18/28] convert /_scripts/painless as well --- .../client/RestHighLevelClientTests.java | 2 +- .../painless-execute-script.asciidoc | 6 +++--- .../painless/ContextDocGenerator.java | 4 ++-- .../painless/action/PainlessContextAction.java | 8 ++++---- .../painless/action/PainlessExecuteAction.java | 6 +++--- ..._context.json => script_painless_context.json} | 13 +++++++++++-- .../test/painless/70_execute_painless_scripts.yml | 8 ++++---- .../test/painless/71_context_api.yml | 4 ++-- .../resources/rest-api-spec/api/get_script.json | 8 +------- ..._execute.json => script_painless_execute.json} | 15 +++++++++++++-- 10 files changed, 44 insertions(+), 30 deletions(-) rename modules/lang-painless/src/test/resources/rest-api-spec/api/{scripts_painless_context.json => script_painless_context.json} (57%) rename rest-api-spec/src/main/resources/rest-api-spec/api/{scripts_painless_execute.json => script_painless_execute.json} (64%) diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java index d0d6f674064ab..8846f81d61ced 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java @@ -746,7 +746,7 @@ public void testApiNamingConventions() throws Exception { "indices.get_upgrade", "indices.put_alias", "render_search_template", - "scripts_painless_execute" + "script_painless_execute" }; //These API are not required for high-level client feature completeness String[] notRequiredApi = new String[] { diff --git a/docs/painless/painless-guide/painless-execute-script.asciidoc b/docs/painless/painless-guide/painless-execute-script.asciidoc index fc5a6bf71d14a..0aaa4384d3b72 100644 --- a/docs/painless/painless-guide/painless-execute-script.asciidoc +++ b/docs/painless/painless-guide/painless-execute-script.asciidoc @@ -32,7 +32,7 @@ Request: [source,js] ---------------------------------------------------------------- -POST /_scripts/painless/_execute +POST /_script/painless/_execute { "script": { "source": "params.count / params.total", @@ -82,7 +82,7 @@ PUT /my-index } } -POST /_scripts/painless/_execute +POST /_script/painless/_execute { "script": { "source": "doc['field'].value.length() <= params.max_length", @@ -142,7 +142,7 @@ PUT /my-index } -POST /_scripts/painless/_execute +POST /_script/painless/_execute { "script": { "source": "doc['rank'].value / params.max_rank", diff --git a/modules/lang-painless/src/doc/java/org/elasticsearch/painless/ContextDocGenerator.java b/modules/lang-painless/src/doc/java/org/elasticsearch/painless/ContextDocGenerator.java index f09dd4f521ade..e16be46c180b2 100644 --- a/modules/lang-painless/src/doc/java/org/elasticsearch/painless/ContextDocGenerator.java +++ b/modules/lang-painless/src/doc/java/org/elasticsearch/painless/ContextDocGenerator.java @@ -105,7 +105,7 @@ public static void main(String[] args) throws IOException { @SuppressForbidden(reason = "retrieving data from an internal API not exposed as part of the REST client") private static List getContextInfos() throws IOException { URLConnection getContextNames = new URL( - "http://" + System.getProperty("cluster.uri") + "/_scripts/painless/_context").openConnection(); + "http://" + System.getProperty("cluster.uri") + "/_script/painless/_context").openConnection(); XContentParser parser = JsonXContent.jsonXContent.createParser(null, null, getContextNames.getInputStream()); parser.nextToken(); parser.nextToken(); @@ -118,7 +118,7 @@ private static List getContextInfos() throws IOException { for (String contextName : contextNames) { URLConnection getContextInfo = new URL( - "http://" + System.getProperty("cluster.uri") + "/_scripts/painless/_context?context=" + contextName).openConnection(); + "http://" + System.getProperty("cluster.uri") + "/_script/painless/_context?context=" + contextName).openConnection(); parser = JsonXContent.jsonXContent.createParser(null, null, getContextInfo.getInputStream()); contextInfos.add(PainlessContextInfo.fromXContent(parser)); ((HttpURLConnection)getContextInfo).disconnect(); diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextAction.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextAction.java index 9075b9e030df8..3c04805ed7138 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextAction.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextAction.java @@ -58,8 +58,8 @@ * Internal REST API for querying context information about Painless whitelists. * Commands include the following: *
    - *
  • GET /_scripts/painless/_context -- retrieves a list of contexts
  • - *
  • GET /_scripts/painless/_context?context=%name% -- + *
  • GET /_script/painless/_context -- retrieves a list of contexts
  • + *
  • GET /_script/painless/_context?context=%name% -- * retrieves all available information about the API for this specific context
  • *
*/ @@ -195,12 +195,12 @@ protected void doExecute(Task task, Request request, ActionListener li public static class RestAction extends BaseRestHandler { public RestAction(RestController controller) { - controller.registerHandler(GET, "/_scripts/painless/_context", this); + controller.registerHandler(GET, "/_script/painless/_context", this); } @Override public String getName() { - return "_scripts_painless_context"; + return "_script_painless_context"; } @Override diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java index 17302c6554791..75479ff182211 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessExecuteAction.java @@ -564,13 +564,13 @@ private static Response prepareRamIndex(Request request, public static class RestAction extends BaseRestHandler { public RestAction(RestController controller) { - controller.registerHandler(GET, "/_scripts/painless/_execute", this); - controller.registerHandler(POST, "/_scripts/painless/_execute", this); + controller.registerHandler(GET, "/_script/painless/_execute", this); + controller.registerHandler(POST, "/_script/painless/_execute", this); } @Override public String getName() { - return "_scripts_painless_execute"; + return "_script_painless_execute"; } @Override diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/api/scripts_painless_context.json b/modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json similarity index 57% rename from modules/lang-painless/src/test/resources/rest-api-spec/api/scripts_painless_context.json rename to modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json index 31ef7ae8d489a..c8131540bcc92 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/api/scripts_painless_context.json +++ b/modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json @@ -1,12 +1,21 @@ { - "scripts_painless_context": { + "script_painless_context": { "stability": "experimental", "url": { "paths": [ { - "path": "/_scripts/painless/_context", + "path": "/_script/painless/_context", "methods": ["GET"], "parts": {} + }, + { + "path": "/_scripts/painless/_context", + "methods": ["GET"], + "parts": {}, + "deprecated":{ + "version":"8.0.0", + "description":"The path is now singular" + } } ] }, diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_execute_painless_scripts.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_execute_painless_scripts.yml index 5a994425c5dc2..997e79914d33b 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_execute_painless_scripts.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_execute_painless_scripts.yml @@ -15,7 +15,7 @@ setup: --- "Execute with defaults": - do: - scripts_painless_execute: + script_painless_execute: body: script: source: "params.count / params.total" @@ -27,7 +27,7 @@ setup: --- "Execute with painless_test context": - do: - scripts_painless_execute: + script_painless_execute: body: script: source: "params.var1 - params.var2" @@ -40,7 +40,7 @@ setup: --- "Execute with filter context": - do: - scripts_painless_execute: + script_painless_execute: body: script: source: "doc['field'].value.length() <= params.max_length" @@ -56,7 +56,7 @@ setup: --- "Execute with score context": - do: - scripts_painless_execute: + script_painless_execute: body: script: source: "doc['rank'].value / params.max_rank" diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/71_context_api.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/71_context_api.yml index 0413661fc586c..e3c01ffe67ab5 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/71_context_api.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/71_context_api.yml @@ -1,13 +1,13 @@ "Action to list contexts": - do: - scripts_painless_context: {} + script_painless_context: {} - match: { contexts.0: aggregation_selector} - match: { contexts.22: update} --- "Action to get all API values for score context": - do: - scripts_painless_context: + script_painless_context: context: score - match: { name: score } - match: { classes.6.name: java.lang.Appendable } diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json index e4096d781c344..6b03928496e14 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json @@ -11,13 +11,7 @@ "path":"/_script", "methods":[ "GET" - ], - "parts":{ - "id":{ - "type":"string", - "description":"Script ID" - } - } + ] }, { "path":"/_script/{id}", diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/scripts_painless_execute.json b/rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json similarity index 64% rename from rest-api-spec/src/main/resources/rest-api-spec/api/scripts_painless_execute.json rename to rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json index 9f761fb452ba1..2d4bbdd447550 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/scripts_painless_execute.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json @@ -1,5 +1,5 @@ { - "scripts_painless_execute":{ + "script_painless_execute":{ "documentation":{ "url":"https://www.elastic.co/guide/en/elasticsearch/painless/master/painless-execute-api.html", "description":"Allows an arbitrary script to be executed and a result to be returned" @@ -8,11 +8,22 @@ "url":{ "paths":[ { - "path":"/_scripts/painless/_execute", + "path":"/_script/painless/_execute", "methods":[ "GET", "POST" ] + }, + { + "path":"/_scripts/painless/_execute", + "methods":[ + "GET", + "POST" + ], + "deprecated":{ + "version":"8.0.0", + "description":"The path is now singular" + } } ] }, From e5b6492d3b09fa0c86bae7a11c1012bc61e11e7b Mon Sep 17 00:00:00 2001 From: ivan Date: Thu, 15 Aug 2019 13:47:12 -0700 Subject: [PATCH 19/28] Remove deprecated paths due to potential bug in integration tests --- .../api/script_painless_context.json | 9 --------- .../resources/rest-api-spec/api/get_script.json | 16 ---------------- .../api/script_painless_execute.json | 11 ----------- 3 files changed, 36 deletions(-) diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json b/modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json index c8131540bcc92..97c1137930dbe 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json +++ b/modules/lang-painless/src/test/resources/rest-api-spec/api/script_painless_context.json @@ -7,15 +7,6 @@ "path": "/_script/painless/_context", "methods": ["GET"], "parts": {} - }, - { - "path": "/_scripts/painless/_context", - "methods": ["GET"], - "parts": {}, - "deprecated":{ - "version":"8.0.0", - "description":"The path is now singular" - } } ] }, diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json index 6b03928496e14..f32d64bae0986 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/get_script.json @@ -24,22 +24,6 @@ "description":"Script ID" } } - }, - { - "path":"/_scripts/{id}", - "methods":[ - "GET" - ], - "parts":{ - "id":{ - "type":"string", - "description":"Script ID" - } - }, - "deprecated":{ - "version":"8.0.0", - "description":"The path is now singular" - } } ] }, diff --git a/rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json b/rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json index 2d4bbdd447550..90a6431391aff 100644 --- a/rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json +++ b/rest-api-spec/src/main/resources/rest-api-spec/api/script_painless_execute.json @@ -13,17 +13,6 @@ "GET", "POST" ] - }, - { - "path":"/_scripts/painless/_execute", - "methods":[ - "GET", - "POST" - ], - "deprecated":{ - "version":"8.0.0", - "description":"The path is now singular" - } } ] }, From ac4605bcd5841022d2ac671aaefe1237d8fadec1 Mon Sep 17 00:00:00 2001 From: ivan Date: Wed, 21 Aug 2019 16:18:53 -0700 Subject: [PATCH 20/28] Changes based on PR comments. Consistent naming, remove redundancies, trimmed ctors. --- .../elasticsearch/client/StoredScriptsIT.java | 4 +- .../StoredScriptsDocumentationIT.java | 4 +- .../reference/search/search-template.asciidoc | 4 +- .../script/mustache/SearchTemplateIT.java | 7 +- .../test/painless/16_update2.yml | 3 +- .../test/painless/70_get_all.yml | 7 +- .../storedscripts/GetStoredScriptRequest.java | 52 ++++++---- .../GetStoredScriptRequestBuilder.java | 6 +- .../GetStoredScriptResponse.java | 84 ++++++++++------ .../TransportGetStoredScriptAction.java | 6 +- .../client/support/AbstractClient.java | 9 +- .../cluster/RestGetStoredScriptAction.java | 19 +++- .../GetStoredScriptResponseTests.java | 4 +- .../SharedClusterSnapshotRestoreIT.java | 4 +- .../cluster/storedscripts/10_get_script.yml | 96 +++++++++++++++++++ 15 files changed, 235 insertions(+), 74 deletions(-) create mode 100644 server/src/test/resources/org/elasticsearch/action/admin/cluster/storedscripts/10_get_script.yml diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java index ddd4c4e8e6fe3..6d6669dc91a8d 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java @@ -93,7 +93,7 @@ public void testPutScript() throws Exception { assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); Map script = getAsMap("/_script/" + id); - assertThat(extractValue(id + ".script.lang", script), equalTo("painless")); - assertThat(extractValue(id + ".script.source", script), equalTo("Math.log(_score * 2) + params.my_modifier")); + assertThat(extractValue(id + ".lang", script), equalTo("painless")); + assertThat(extractValue(id + ".source", script), equalTo("Math.log(_score * 2) + params.my_modifier")); } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java index f980d6f0a02eb..c426bf1649a7f 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java @@ -300,8 +300,8 @@ public void onFailure(Exception e) { client.putScript(request, RequestOptions.DEFAULT); Map script = getAsMap("/_script/id"); - assertThat(extractValue("id.script.lang", script), equalTo("mustache")); - assertThat(extractValue("id.script.source", script), equalTo("{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}")); + assertThat(extractValue("id.lang", script), equalTo("mustache")); + assertThat(extractValue("id.source", script), equalTo("{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}")); } } diff --git a/docs/reference/search/search-template.asciidoc b/docs/reference/search/search-template.asciidoc index 570ab0a7a25d3..2c1875f7ddb4d 100644 --- a/docs/reference/search/search-template.asciidoc +++ b/docs/reference/search/search-template.asciidoc @@ -78,7 +78,7 @@ This template can be retrieved by [source,js] ------------------------------------------ -GET _script/ +GET _script/?new_format=true ------------------------------------------ // CONSOLE // TEST[continued] @@ -88,7 +88,7 @@ which is rendered as: [source,js] ------------------------------------------ { - "" : { + "" : { "lang" : "mustache", "source" : "{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}", "options": { diff --git a/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateIT.java b/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateIT.java index 3ff2bb649a79b..48d8b5512dbdc 100644 --- a/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateIT.java +++ b/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateIT.java @@ -35,6 +35,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.NoSuchElementException; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; @@ -170,6 +171,7 @@ public void testIndexedTemplateClient() throws Exception { GetStoredScriptResponse getResponse = client().admin().cluster() .prepareGetStoredScript("testTemplate").get(); + assertEquals(1, getResponse.getStoredScripts().size()); assertNotNull(getResponse.getSource()); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); @@ -192,8 +194,9 @@ public void testIndexedTemplateClient() throws Exception { assertAcked(client().admin().cluster().prepareDeleteStoredScript("testTemplate")); - getResponse = client().admin().cluster().prepareGetStoredScript("testTemplate").get(); - assertNull(getResponse.getSource()); + final GetStoredScriptResponse response = client().admin().cluster().prepareGetStoredScript("testTemplate").get(); + assertEquals(0, response.getStoredScripts().size()); + expectThrows(NoSuchElementException.class, () -> response.getSource()); } public void testIndexedTemplate() throws Exception { diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml index 4a6bc23bf1947..b17e7f8e31636 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/16_update2.yml @@ -12,7 +12,8 @@ - do: get_script: id: "1" - - match: { "1" : { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } } + new_format: true + - match: { "1" : { "lang": "painless", "source": "_score * doc['myParent.weight'].value"} } - do: catch: missing diff --git a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml index a92674c754e5b..6cb17544d94cc 100644 --- a/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml +++ b/modules/lang-painless/src/test/resources/rest-api-spec/test/painless/70_get_all.yml @@ -18,8 +18,9 @@ - match: { acknowledged: true } - do: - get_script: {} + get_script: + new_format: true - length: { $body: 2 } - - match: { 1.script: {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } - - match: { foo.script: {"lang": "painless", "source": "_score * 9.9"} } + - match: { 1: {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } + - match: { foo: {"lang": "painless", "source": "_score * 9.9"} } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java index c6fe5a26c813c..7f2fccd3673cd 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java @@ -19,6 +19,7 @@ package org.elasticsearch.action.admin.cluster.storedscripts; +import org.elasticsearch.Version; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.support.master.MasterNodeReadRequest; import org.elasticsearch.common.Strings; @@ -31,46 +32,57 @@ public class GetStoredScriptRequest extends MasterNodeReadRequest { - private String[] names; + private String[] ids; public GetStoredScriptRequest() { this(new String[]{}); } - public GetStoredScriptRequest(String... names) { - this.names = names; + public GetStoredScriptRequest(String... ids) { + this.ids = ids; } public GetStoredScriptRequest(StreamInput in) throws IOException { super(in); - names = in.readStringArray(); + if (in.getVersion().onOrAfter(Version.V_7_4_0)) { + this.ids = in.readStringArray(); + } else { + this.ids = new String[] { in.readString() }; + } } /** - * Returns he names of the scripts. + * Returns the ids of the scripts. */ - public String[] names() { - return this.names; + public String[] ids() { + return this.ids; + } + + public GetStoredScriptRequest ids(String... ids) { + this.ids = ids; + + return this; } /** * @deprecated - Needed for backwards compatibility. - * Use {@link #names()} instead + * Use {@link #ids()} instead * - * Return the script if there is only one defined, null otherwise + * Return the only script */ @Deprecated public String id() { - return names != null && names.length == 1 ? names[0] : null; + assert(ids.length == 1); + return ids[0]; } /** * @deprecated - Needed for backwards compatibility. - * Set the script names param instead + * Set the script ids param instead */ @Deprecated public GetStoredScriptRequest id(String id) { - this.names = new String[] { id }; + this.ids = new String[] { id }; return this; } @@ -78,18 +90,22 @@ public GetStoredScriptRequest id(String id) { @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); - out.writeStringArray(names); + if (out.getVersion().onOrAfter(Version.V_7_4_0)) { + out.writeStringArray(ids); + } else { + out.writeString(ids[0]); + } } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; - if (names == null) { - validationException = addValidationError("names is null or empty", validationException); + if (ids == null) { + validationException = addValidationError("ids is null or empty", validationException); } else { - for (String name : names) { + for (String name : ids) { if (name == null || !Strings.hasText(name)) { - validationException = addValidationError("name is missing", validationException); + validationException = addValidationError("id is missing", validationException); } } } @@ -98,6 +114,6 @@ public ActionRequestValidationException validate() { @Override public String toString() { - return "get script"; + return "get script[ " + String.join(", ", ids) + "]"; } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java index 76d8d692f092e..cac4cbc6ea5cc 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestBuilder.java @@ -29,10 +29,12 @@ public GetStoredScriptRequestBuilder(ElasticsearchClient client, GetStoredScript super(client, action, new GetStoredScriptRequest()); } - public GetStoredScriptRequestBuilder(ElasticsearchClient client, GetStoredScriptAction action, String... names) { - super(client, action, new GetStoredScriptRequest(names)); + public GetStoredScriptRequestBuilder setIds(String... ids) { + request.ids(ids); + return this; } + @Deprecated public GetStoredScriptRequestBuilder setId(String id) { request.id(id); return this; diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java index 72d4449347b40..5ce01367114cb 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java @@ -19,6 +19,7 @@ package org.elasticsearch.action.admin.cluster.storedscripts; +import org.elasticsearch.Version; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.io.stream.StreamInput; @@ -63,25 +64,36 @@ public class GetStoredScriptResponse extends ActionResponse implements ToXConten SCRIPT, ObjectParser.ValueType.OBJECT); } - private Map storedScripts; + private final Map storedScripts; + private final String[] requestedIds; GetStoredScriptResponse(StreamInput in) throws IOException { super(in); - int size = in.readVInt(); - storedScripts = new HashMap<>(size); - for (int i = 0 ; i < size ; i++) { + if (in.getVersion().onOrAfter(Version.V_7_4_0)) { + storedScripts = in.readMap(StreamInput::readString, StoredScriptSource::new); + } else { + StoredScriptSource source; + if (in.readBoolean()) { + source = new StoredScriptSource(in); + } else { + source = null; + } String id = in.readString(); - storedScripts.put(id, new StoredScriptSource(in)); + storedScripts = new HashMap<>(1); + storedScripts.put(id, source); } + requestedIds = new String[0]; } GetStoredScriptResponse(String id, StoredScriptSource source) { this.storedScripts = new HashMap<>(); storedScripts.put(id, source); + requestedIds = new String[]{ id }; } - GetStoredScriptResponse(Map storedScripts) { + GetStoredScriptResponse(String[] requestedIds, Map storedScripts) { + this.requestedIds = requestedIds; this.storedScripts = storedScripts; } @@ -97,27 +109,21 @@ public Map getStoredScripts() { */ @Deprecated public StoredScriptSource getSource() { - if (storedScripts != null && storedScripts.size() == 1) { - return storedScripts.entrySet().iterator().next().getValue(); - } else { - return null; - } + return storedScripts.entrySet().iterator().next().getValue(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - if (params.paramAsBoolean("new_format", false)) { + if (!params.paramAsBoolean("new_format", false)) { return toXContentPre80(builder, params); } - builder.startObject(); + builder.startObject(); Map storedScripts = getStoredScripts(); if (storedScripts != null) { for (Map.Entry storedScript : storedScripts.entrySet()) { - builder.startObject(storedScript.getKey()); - builder.field(StoredScriptSource.SCRIPT_PARSE_FIELD.getPreferredName()); + builder.field(storedScript.getKey()); storedScript.getValue().toXContent(builder, params); - builder.endObject(); } } builder.endObject(); @@ -129,21 +135,24 @@ public static GetStoredScriptResponse fromXContent(XContentParser parser) throws for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) { if (token == XContentParser.Token.FIELD_NAME) { String name = parser.currentName(); - parser.nextToken(); - parser.nextToken(); + assert parser.nextToken() == XContentParser.Token.START_OBJECT; StoredScriptSource storedScriptSource = StoredScriptSource.fromXContent(parser, false); storedScripts.put(name, storedScriptSource); } } - return new GetStoredScriptResponse(storedScripts); + return new GetStoredScriptResponse(storedScripts.keySet().toArray(String[]::new), storedScripts); } + @Deprecated private XContentBuilder toXContentPre80(XContentBuilder builder, Params params) throws IOException { builder.startObject(); - Map.Entry entry = storedScripts.entrySet().iterator().next(); - String id = entry.getKey(); - StoredScriptSource source = entry.getValue(); + String id = requestedIds[0]; + StoredScriptSource source = null; + if (!storedScripts.isEmpty()) { + Map.Entry entry = storedScripts.entrySet().iterator().next(); + source = entry.getValue(); + } builder.field(_ID_PARSE_FIELD.getPreferredName(), id); builder.field(FOUND_PARSE_FIELD.getPreferredName(), source != null); @@ -156,21 +165,36 @@ private XContentBuilder toXContentPre80(XContentBuilder builder, Params params) return builder; } + /** + * Used to test backwards compatibility since the original format is the default prior to 8.0 + */ + @Deprecated public static GetStoredScriptResponse fromXContentPre80(XContentParser parser) throws IOException { return PARSER.parse(parser, null); } @Override public void writeTo(StreamOutput out) throws IOException { - if (storedScripts == null ) { - out.writeVInt(0); - return; - } + if (out.getVersion().onOrAfter(Version.V_7_4_0)) { + if (storedScripts == null ) { + out.writeVInt(0); + return; + } - out.writeVInt(storedScripts.size()); - for (Map.Entry storedScript : storedScripts.entrySet()) { - out.writeString(storedScript.getKey()); - storedScript.getValue().writeTo(out); + out.writeVInt(storedScripts.size()); + for (Map.Entry storedScript : storedScripts.entrySet()) { + out.writeString(storedScript.getKey()); + storedScript.getValue().writeTo(out); + } + } else { + Map.Entry entry = storedScripts.entrySet().iterator().next(); + if (entry.getValue() == null) { + out.writeBoolean(false); + } else { + out.writeBoolean(true); + entry.getValue().writeTo(out); + } + out.writeString(entry.getKey()); } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java index 28ac7178ac8b2..6a12672e3650d 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportGetStoredScriptAction.java @@ -71,14 +71,14 @@ protected void masterOperation(Task task, GetStoredScriptRequest request, Cluste Map storedScripts = scriptService.getStoredScripts(state); // If we did not ask for a specific name, then we return all templates - if (request.names().length == 0) { + if (request.ids().length == 0) { results = storedScripts; } else { results = new HashMap<>(); } if (storedScripts != null) { - for (String name : request.names()) { + for (String name : request.ids()) { if (Regex.isSimpleMatchPattern(name)) { for (Map.Entry entry : storedScripts.entrySet()) { if (Regex.simpleMatch(name, entry.getKey())) { @@ -91,7 +91,7 @@ protected void masterOperation(Task task, GetStoredScriptRequest request, Cluste } } - listener.onResponse(new GetStoredScriptResponse(results)); + listener.onResponse(new GetStoredScriptResponse(request.ids(), results)); } @Override diff --git a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java index 3f26b205c67db..c4439b363c764 100644 --- a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java +++ b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java @@ -1155,13 +1155,14 @@ public GetStoredScriptRequestBuilder prepareGetStoredScript() { } @Override - public GetStoredScriptRequestBuilder prepareGetStoredScript(String id) { - return prepareGetStoredScript().setId(id); + public GetStoredScriptRequestBuilder prepareGetStoredScript(String... ids) { + return prepareGetStoredScript().setIds(ids); } @Override - public GetStoredScriptRequestBuilder prepareGetStoredScript(String... names) { - return new GetStoredScriptRequestBuilder(this, GetStoredScriptAction.INSTANCE, names); + @Deprecated + public GetStoredScriptRequestBuilder prepareGetStoredScript(String id) { + return prepareGetStoredScript().setId(id); } @Override diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java index ef5c869430800..ae7836bb6da10 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java @@ -24,6 +24,7 @@ import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.logging.DeprecationLogger; +import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; @@ -32,7 +33,11 @@ import org.elasticsearch.script.StoredScriptSource; import java.io.IOException; +import java.util.Collections; import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; import static org.elasticsearch.rest.RestRequest.Method.GET; import static org.elasticsearch.rest.RestRequest.Method.HEAD; @@ -41,13 +46,18 @@ public class RestGetStoredScriptAction extends BaseRestHandler { + private static final String NEW_FORMAT = "new_format"; + private static final Set allowedResponseParameters = Collections + .unmodifiableSet(Stream.concat(Collections.singleton(NEW_FORMAT).stream(), Settings.FORMAT_PARAMS.stream()) + .collect(Collectors.toSet())); + private static final DeprecationLogger deprecationLogger = new DeprecationLogger(LogManager.getLogger(RestGetStoredScriptAction.class)); public RestGetStoredScriptAction(RestController controller) { controller.registerHandler(GET, "/_script", this); controller.registerWithDeprecatedHandler(GET, "/_script/{id}", this, - GET, "/_scripts/{name}", deprecationLogger); + GET, "/_scripts/{id}", deprecationLogger); controller.registerHandler(HEAD, "/_script/{id}", this); } @@ -63,7 +73,7 @@ public RestChannelConsumer prepareRequest(final RestRequest request, NodeClient GetStoredScriptRequest getRequest = new GetStoredScriptRequest(names); getRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRequest.masterNodeTimeout())); - final boolean implicitAll = getRequest.names().length == 0; + final boolean implicitAll = getRequest.ids().length == 0; return channel -> client.admin().cluster().getStoredScript(getRequest, new RestToXContentListener<>(channel) { @Override @@ -75,4 +85,9 @@ protected RestStatus getStatus(final GetStoredScriptResponse response) } }); } + + @Override + protected Set responseParams() { + return allowedResponseParameters; + } } diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java index 5bd6e64cec2fd..b2cedba05a58c 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java @@ -34,7 +34,7 @@ public class GetStoredScriptResponseTests extends AbstractSerializingTestCase storedScripts = new HashMap<>(); storedScripts.put(randomAlphaOfLengthBetween(1, 10), randomScriptSource()); - return new GetStoredScriptResponse(storedScripts); + return new GetStoredScriptResponse(storedScripts.keySet().toArray(String[]::new), storedScripts); } @Override diff --git a/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java b/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java index b11cf9107e30b..099b2e56ae9f6 100644 --- a/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java +++ b/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java @@ -109,6 +109,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.NoSuchElementException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -784,7 +785,8 @@ public void testIncludeGlobalState() throws Exception { getIndexTemplatesResponse = client().admin().indices().prepareGetTemplates().get(); assertIndexTemplateMissing(getIndexTemplatesResponse, "test-template"); assertFalse(client().admin().cluster().prepareGetPipeline("barbaz").get().isFound()); - assertNull(client().admin().cluster().prepareGetStoredScript("foobar").get().getSource()); + final GetStoredScriptResponse getStoredScriptResponse = client().admin().cluster().prepareGetStoredScript("foobar").get(); + expectThrows(NoSuchElementException.class, () -> getStoredScriptResponse.getSource()); assertThat(client.prepareSearch("test-idx").setSize(0).get().getHits().getTotalHits().value, equalTo(100L)); } diff --git a/server/src/test/resources/org/elasticsearch/action/admin/cluster/storedscripts/10_get_script.yml b/server/src/test/resources/org/elasticsearch/action/admin/cluster/storedscripts/10_get_script.yml new file mode 100644 index 0000000000000..fa393c4049d05 --- /dev/null +++ b/server/src/test/resources/org/elasticsearch/action/admin/cluster/storedscripts/10_get_script.yml @@ -0,0 +1,96 @@ +--- +"Get script, default format": + - do: + put_script: + id: "1" + body: { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value" } } + - match: { acknowledged: true } + + - do: + get_script: + id: "1" + - match: { found: true } + - match: { _id: "1" } + - match: { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } + +--- +"Get script, new format": + - + - skip: + version: " - 7.99.99" + reason: this uses a new API that has been added in 8.0 + + - do: + put_script: + id: "1" + body: { "script": {"lang": "painless", "source": "_score * doc['myParent.weight'].value" } } + - match: { acknowledged: true } + + - do: + get_script: + id: "1" + new_format: true + - match: { "1" : { "lang": "painless", "source": "_score * doc['myParent.weight'].value"} } + +--- +"Get script with wildcard": + + - skip: + version: " - 7.99.99" + reason: this uses a new API that has been added in 8.0 + - do: + put_script: + id: "foo" + body: { "script": {} } + - match: { acknowledged: true } + + - do: + put_script: + id: "foo" + body: { "script": {} } + - match: { acknowledged: true } + + - do: + put_script: + id: "bar" + body: { "script": {} } + - match: { acknowledged: true } + + - do: + put_script: + id: "baz" + body: { "script": {} } + - match: { acknowledged: true } + + - do: + get_script: + id: "ba*" + new_format: true + - length: { $body: 2 } + +--- +"Get all scripts": + + - skip: + version: " - 7.99.99" + reason: this uses a new API that has been added in 8.0 + + - do: + put_script: + id: "1" + body: { "script": { "lang": "painless", "source": "_score * doc['myParent.weight'].value" } } + - match: { acknowledged: true } + + - do: + put_script: + id: "foo" + body: { "script": { "lang": "painless", "source": "_score * 9.9" } } + - match: { acknowledged: true } + + - do: + get_script: + new_format: true + + - length: { $body: 2 } + - match: { 1: {"lang": "painless", "source": "_score * doc['myParent.weight'].value"} } + - match: { foo: {"lang": "painless", "source": "_score * 9.9"} } From ff19531106e29147b7523f203720c3f9d9a77cd7 Mon Sep 17 00:00:00 2001 From: ivan Date: Mon, 2 Sep 2019 15:41:37 -0700 Subject: [PATCH 21/28] make original format the default --- .../elasticsearch/client/StoredScriptsIT.java | 6 ++++-- .../StoredScriptsDocumentationIT.java | 4 ++-- .../storedscripts/GetStoredScriptResponse.java | 17 +++++++++-------- .../GetStoredScriptResponseTests.java | 2 +- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java index 6d6669dc91a8d..0a57208e10ffd 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java @@ -93,7 +93,9 @@ public void testPutScript() throws Exception { assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); Map script = getAsMap("/_script/" + id); - assertThat(extractValue(id + ".lang", script), equalTo("painless")); - assertThat(extractValue(id + ".source", script), equalTo("Math.log(_score * 2) + params.my_modifier")); + assertThat(extractValue("_id", script), equalTo(id)); + assertThat(extractValue("found", script), equalTo(true)); + assertThat(extractValue("script.lang", script), equalTo("painless")); + assertThat(extractValue("script.source", script), equalTo("Math.log(_score * 2) + params.my_modifier")); } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java index c426bf1649a7f..757651bb9943b 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java @@ -300,8 +300,8 @@ public void onFailure(Exception e) { client.putScript(request, RequestOptions.DEFAULT); Map script = getAsMap("/_script/id"); - assertThat(extractValue("id.lang", script), equalTo("mustache")); - assertThat(extractValue("id.source", script), equalTo("{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}")); + assertThat(extractValue("script.lang", script), equalTo("mustache")); + assertThat(extractValue("script.source", script), equalTo("{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}")); } } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java index 5ce01367114cb..1c8f47e80756c 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java @@ -130,7 +130,16 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws return builder; } + /** + * The original format is the default prior to 8.0 and needed for backwards compatibility + * @see #fromXContentNewFormat(XContentParser) + */ + @Deprecated public static GetStoredScriptResponse fromXContent(XContentParser parser) throws IOException { + return PARSER.parse(parser, null); + } + + public static GetStoredScriptResponse fromXContentNewFormat(XContentParser parser) throws IOException { final Map storedScripts = new HashMap<>(); for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) { if (token == XContentParser.Token.FIELD_NAME) { @@ -165,14 +174,6 @@ private XContentBuilder toXContentPre80(XContentBuilder builder, Params params) return builder; } - /** - * Used to test backwards compatibility since the original format is the default prior to 8.0 - */ - @Deprecated - public static GetStoredScriptResponse fromXContentPre80(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - @Override public void writeTo(StreamOutput out) throws IOException { if (out.getVersion().onOrAfter(Version.V_7_4_0)) { diff --git a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java index b2cedba05a58c..1512c135f98d9 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java @@ -34,7 +34,7 @@ public class GetStoredScriptResponseTests extends AbstractSerializingTestCase Date: Mon, 2 Sep 2019 16:30:47 -0700 Subject: [PATCH 22/28] bump up the version --- .../admin/cluster/storedscripts/GetStoredScriptRequest.java | 4 ++-- .../admin/cluster/storedscripts/GetStoredScriptResponse.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java index 7f2fccd3673cd..fd06205783801 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java @@ -44,7 +44,7 @@ public GetStoredScriptRequest(String... ids) { public GetStoredScriptRequest(StreamInput in) throws IOException { super(in); - if (in.getVersion().onOrAfter(Version.V_7_4_0)) { + if (in.getVersion().onOrAfter(Version.V_7_5_0)) { this.ids = in.readStringArray(); } else { this.ids = new String[] { in.readString() }; @@ -90,7 +90,7 @@ public GetStoredScriptRequest id(String id) { @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); - if (out.getVersion().onOrAfter(Version.V_7_4_0)) { + if (out.getVersion().onOrAfter(Version.V_7_5_0)) { out.writeStringArray(ids); } else { out.writeString(ids[0]); diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java index 1c8f47e80756c..e246051b76432 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java @@ -70,7 +70,7 @@ public class GetStoredScriptResponse extends ActionResponse implements ToXConten GetStoredScriptResponse(StreamInput in) throws IOException { super(in); - if (in.getVersion().onOrAfter(Version.V_7_4_0)) { + if (in.getVersion().onOrAfter(Version.V_7_5_0)) { storedScripts = in.readMap(StreamInput::readString, StoredScriptSource::new); } else { StoredScriptSource source; @@ -176,7 +176,7 @@ private XContentBuilder toXContentPre80(XContentBuilder builder, Params params) @Override public void writeTo(StreamOutput out) throws IOException { - if (out.getVersion().onOrAfter(Version.V_7_4_0)) { + if (out.getVersion().onOrAfter(Version.V_7_5_0)) { if (storedScripts == null ) { out.writeVInt(0); return; From 086d9acee11d5808562baa06f36272b833f2be16 Mon Sep 17 00:00:00 2001 From: ivan Date: Mon, 2 Sep 2019 23:31:41 -0700 Subject: [PATCH 23/28] fix new format bug --- .../admin/cluster/storedscripts/GetStoredScriptResponse.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java index e246051b76432..7c882ba9e4e1d 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java @@ -114,7 +114,8 @@ public StoredScriptSource getSource() { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - if (!params.paramAsBoolean("new_format", false)) { + boolean isSingleId = requestedIds.length == 1 && storedScripts.size() == 1; + if (!params.paramAsBoolean("new_format", false) && isSingleId) { return toXContentPre80(builder, params); } From 3103e1d0fc7bd5dab5b77c786f203e482647e9fc Mon Sep 17 00:00:00 2001 From: ivan Date: Wed, 11 Sep 2019 23:17:36 -0700 Subject: [PATCH 24/28] disable bwc tests --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index a826ecb4475e2..75a56938e3f8e 100644 --- a/build.gradle +++ b/build.gradle @@ -176,8 +176,8 @@ task verifyVersions { * after the backport of the backcompat code is complete. */ -boolean bwc_tests_enabled = true -final String bwc_tests_disabled_issue = "" /* place a PR link here when committing bwc changes */ +boolean bwc_tests_enabled = false +final String bwc_tests_disabled_issue = "https://github.com/elastic/elasticsearch/pull/28368" /* place a PR link here when committing bwc changes */ if (bwc_tests_enabled == false) { if (bwc_tests_disabled_issue.isEmpty()) { throw new GradleException("bwc_tests_disabled_issue must be set when bwc_tests_enabled == false") From f7c76b2b5529e07c6cf2d9c619e36f341e3274c7 Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 2 Jun 2020 16:40:50 -0700 Subject: [PATCH 25/28] update more legacy paths --- docs/reference/scripting/using.asciidoc | 4 ++-- .../painless/action/PainlessContextAction.java | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/reference/scripting/using.asciidoc b/docs/reference/scripting/using.asciidoc index b09bdc099ee7b..b4ae4f0051e0d 100644 --- a/docs/reference/scripting/using.asciidoc +++ b/docs/reference/scripting/using.asciidoc @@ -159,11 +159,11 @@ POST _script/calculate-score You may also specify a context as part of the url path to compile a stored script against that specific context in the form of -`/_scripts/{id}/{context}`: +`/_script/{id}/{context}`: [source,console] ----------------------------------- -POST _scripts/calculate-score/score +POST _script/calculate-score/score { "script": { "lang": "painless", diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextAction.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextAction.java index 34a2e26f885fe..c963c4ff08f23 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextAction.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextAction.java @@ -57,15 +57,15 @@ * Internal REST API for querying context information about Painless whitelists. * Commands include the following: *
    - *
  • GET /_scripts/painless/_context -- retrieves a list of contexts
  • - *
  • GET /_scripts/painless/_context?context=%name% -- + *
  • GET /_script/painless/_context -- retrieves a list of contexts
  • + *
  • GET /_script/painless/_context?context=%name% -- * retrieves all available information about the API for this specific context
  • *
*/ public class PainlessContextAction extends ActionType { public static final PainlessContextAction INSTANCE = new PainlessContextAction(); - private static final String NAME = "cluster:admin/scripts/painless/context"; + private static final String NAME = "cluster:admin/script/painless/context"; private static final String SCRIPT_CONTEXT_NAME_PARAM = "context"; From 67f24ba86504ca4288ec8a4b95d721d628c3fdf4 Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 2 Jun 2020 18:30:40 -0700 Subject: [PATCH 26/28] remove renamed file --- .../java/org/elasticsearch/client/RestHighLevelClientTests.java | 2 +- .../elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java | 1 + .../elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java | 0 3 files changed, 2 insertions(+), 1 deletion(-) delete mode 100644 server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java index 390859e68028b..2f60f985a2ba6 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java @@ -800,7 +800,7 @@ public void testApiNamingConventions() throws Exception { "indices.get_upgrade", "indices.put_alias", "render_search_template", - "script_painless_execute" + "script_painless_execute", "indices.create_data_stream", "indices.get_data_stream", "indices.delete_data_stream", diff --git a/server/src/internalClusterTest/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java b/server/src/internalClusterTest/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java index ad1ed73029936..850be081717bc 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java @@ -104,6 +104,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.NoSuchElementException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; diff --git a/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java b/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java deleted file mode 100644 index e69de29bb2d1d..0000000000000 From 10794af3ee3c410434943565ecc2a6e83eeb061e Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 2 Jun 2020 21:16:37 -0700 Subject: [PATCH 27/28] more name changes --- docs/reference/scripting/using.asciidoc | 2 +- modules/lang-painless/build.gradle | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/reference/scripting/using.asciidoc b/docs/reference/scripting/using.asciidoc index b4ae4f0051e0d..81cb23a357ac2 100644 --- a/docs/reference/scripting/using.asciidoc +++ b/docs/reference/scripting/using.asciidoc @@ -217,7 +217,7 @@ DELETE _script/calculate-score [float] [[modules-scripting-search-templates]] === Search templates -You can also use the `_scripts` API to store **search templates**. Search +You can also use the `_script` API to store **search templates**. Search templates save specific <> with placeholder values, called template parameters. diff --git a/modules/lang-painless/build.gradle b/modules/lang-painless/build.gradle index c20887cea9ee8..3be651ab0f0b4 100644 --- a/modules/lang-painless/build.gradle +++ b/modules/lang-painless/build.gradle @@ -49,7 +49,7 @@ dependencyLicenses { restResources { restApi { includeCore '_common', 'cluster', 'nodes', 'indices', 'index', 'search', 'get', 'bulk', 'update', - 'scripts_painless_execute', 'put_script', 'delete_script' + 'script_painless_execute', 'put_script', 'delete_script' } } From 4d395383cd0853d0838d191a2129728366234e87 Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 2 Jun 2020 23:32:36 -0700 Subject: [PATCH 28/28] cleanup API --- .../org/elasticsearch/client/StoredScriptsIT.java | 2 +- .../documentation/StoredScriptsDocumentationIT.java | 2 +- .../script/mustache/SearchTemplateIT.java | 8 +++----- .../org/elasticsearch/script/StoredScriptsIT.java | 2 +- .../snapshots/SharedClusterSnapshotRestoreIT.java | 5 ++--- .../storedscripts/GetStoredScriptResponse.java | 12 +++++++++++- .../org/elasticsearch/client/ClusterAdminClient.java | 6 ------ .../elasticsearch/client/support/AbstractClient.java | 6 ------ .../admin/cluster/RestGetStoredScriptAction.java | 4 ++-- 9 files changed, 21 insertions(+), 26 deletions(-) diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java index 0a57208e10ffd..f814e58d8d771 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/StoredScriptsIT.java @@ -56,7 +56,7 @@ public void testGetStoredScript() throws Exception { GetStoredScriptResponse getResponse = execute(getRequest, highLevelClient()::getScript, highLevelClient()::getScriptAsync); - assertThat(getResponse.getSource(), equalTo(scriptSource)); + assertThat(getResponse.getStoredScript("calculate-score"), equalTo(scriptSource)); } public void testDeleteStoredScript() throws Exception { diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java index 6fb1d82329667..3c411687dc47d 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java @@ -94,7 +94,7 @@ public void testGetStoredScript() throws Exception { // end::get-stored-script-execute // tag::get-stored-script-response - StoredScriptSource storedScriptSource = getResponse.getSource(); // <1> + StoredScriptSource storedScriptSource = getResponse.getStoredScript("calculate-score"); // <1> String lang = storedScriptSource.getLang(); // <2> String source = storedScriptSource.getSource(); // <3> diff --git a/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateIT.java b/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateIT.java index 552b96d94a231..aef493605fcb1 100644 --- a/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateIT.java +++ b/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateIT.java @@ -35,7 +35,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; -import java.util.NoSuchElementException; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; @@ -172,7 +171,7 @@ public void testIndexedTemplateClient() throws Exception { GetStoredScriptResponse getResponse = client().admin().cluster() .prepareGetStoredScript("testTemplate").get(); assertEquals(1, getResponse.getStoredScripts().size()); - assertNotNull(getResponse.getSource()); + assertNotNull(getResponse.getStoredScript("testTemplate")); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); bulkRequestBuilder.add(client().prepareIndex("test").setId("1").setSource("{\"theField\":\"foo\"}", XContentType.JSON)); @@ -195,8 +194,7 @@ public void testIndexedTemplateClient() throws Exception { assertAcked(client().admin().cluster().prepareDeleteStoredScript("testTemplate")); final GetStoredScriptResponse response = client().admin().cluster().prepareGetStoredScript("testTemplate").get(); - assertEquals(0, response.getStoredScripts().size()); - expectThrows(NoSuchElementException.class, () -> response.getSource()); + assertNull(response.getStoredScript("testTemplate")); } public void testIndexedTemplate() throws Exception { @@ -294,7 +292,7 @@ public void testIndexedTemplateOverwrite() throws Exception { ); GetStoredScriptResponse getResponse = client().admin().cluster().prepareGetStoredScript("git01").get(); - assertNotNull(getResponse.getSource()); + assertNotNull(getResponse.getStoredScript("git01")); Map templateParams = new HashMap<>(); templateParams.put("P_Keyword1", "dev"); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/script/StoredScriptsIT.java b/server/src/internalClusterTest/java/org/elasticsearch/script/StoredScriptsIT.java index a2771a1c00c3d..2f08845d9dfd1 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/script/StoredScriptsIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/script/StoredScriptsIT.java @@ -54,7 +54,7 @@ public void testBasics() { assertAcked(client().admin().cluster().preparePutStoredScript() .setId("foobar") .setContent(new BytesArray("{\"script\": {\"lang\": \"" + LANG + "\", \"source\": \"1\"} }"), XContentType.JSON)); - String script = client().admin().cluster().prepareGetStoredScript("foobar").get().getSource().getSource(); + String script = client().admin().cluster().prepareGetStoredScript("foobar").get().getStoredScript("foobar").getSource(); assertNotNull(script); assertEquals("1", script); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java b/server/src/internalClusterTest/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java index 850be081717bc..a273acb6a6d88 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java @@ -104,7 +104,6 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.NoSuchElementException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; @@ -718,7 +717,7 @@ public void testIncludeGlobalState() throws Exception { if (testScript) { logger.info("--> check that script is restored"); GetStoredScriptResponse getStoredScriptResponse = client().admin().cluster().prepareGetStoredScript("foobar").get(); - assertNotNull(getStoredScriptResponse.getSource()); + assertNotNull(getStoredScriptResponse.getStoredScript("foobar")); } createIndex("test-idx"); @@ -768,7 +767,7 @@ public void testIncludeGlobalState() throws Exception { assertIndexTemplateMissing(getIndexTemplatesResponse, "test-template"); assertFalse(client().admin().cluster().prepareGetPipeline("barbaz").get().isFound()); final GetStoredScriptResponse getStoredScriptResponse = client().admin().cluster().prepareGetStoredScript("foobar").get(); - expectThrows(NoSuchElementException.class, () -> getStoredScriptResponse.getSource()); + assertNull(getStoredScriptResponse.getStoredScript("foobar")); assertThat(client.prepareSearch("test-idx").setSize(0).get().getHits().getTotalHits().value, equalTo(100L)); } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java index f2bab6aacaf18..eaae803a1dabf 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptResponse.java @@ -101,9 +101,19 @@ public Map getStoredScripts() { return storedScripts; } + /** + * Helper method to return a single stored script + * + * @param id the id of the script + * @return the script source or null if not found + */ + public StoredScriptSource getStoredScript(String id) { + return storedScripts.get(id); + } + /** * @deprecated - Needed for backwards compatibility. - * Use {@link #getStoredScripts()} instead + * Use {@link #getStoredScript(String)} ()} instead * * @return if a stored script and if not found null */ diff --git a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java index 81984c39622f4..e32eaaa215807 100644 --- a/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java +++ b/server/src/main/java/org/elasticsearch/client/ClusterAdminClient.java @@ -704,12 +704,6 @@ public interface ClusterAdminClient extends ElasticsearchClient { */ GetStoredScriptRequestBuilder prepareGetStoredScript(); - /** - * Get a script from the cluster state - */ - @Deprecated - GetStoredScriptRequestBuilder prepareGetStoredScript(String id); - /** * Get scripts from the cluster state */ diff --git a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java index a00f22945a09a..1ca2d46d043da 100644 --- a/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java +++ b/server/src/main/java/org/elasticsearch/client/support/AbstractClient.java @@ -1153,12 +1153,6 @@ public GetStoredScriptRequestBuilder prepareGetStoredScript(String... ids) { return prepareGetStoredScript().setIds(ids); } - @Override - @Deprecated - public GetStoredScriptRequestBuilder prepareGetStoredScript(String id) { - return prepareGetStoredScript().setId(id); - } - @Override public PutStoredScriptRequestBuilder preparePutStoredScript() { return new PutStoredScriptRequestBuilder(this, PutStoredScriptAction.INSTANCE); diff --git a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java index f5ac1a97d20fc..38afab5d0406e 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java +++ b/server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetStoredScriptAction.java @@ -74,8 +74,8 @@ public RestChannelConsumer prepareRequest(final RestRequest request, NodeClient protected RestStatus getStatus(final GetStoredScriptResponse response) { Map storedScripts = response.getStoredScripts(); - final boolean templateExists = storedScripts != null && !storedScripts.isEmpty(); - return (templateExists || implicitAll) ? RestStatus.OK : RestStatus.NOT_FOUND; + final boolean scriptExists = storedScripts != null && !storedScripts.isEmpty(); + return (scriptExists || implicitAll) ? RestStatus.OK : RestStatus.NOT_FOUND; } }); }