diff --git a/gradle/missing-javadoc.gradle b/gradle/missing-javadoc.gradle index a9e64a1a93da5..d39a9f74dd3de 100644 --- a/gradle/missing-javadoc.gradle +++ b/gradle/missing-javadoc.gradle @@ -143,6 +143,7 @@ configure([ project(":plugins:analysis-smartcn"), project(":plugins:analysis-stempel"), project(":plugins:analysis-ukrainian"), + project(":plugins:api"), project(":plugins:discovery-azure-classic"), project(":plugins:discovery-ec2"), project(":plugins:discovery-ec2:qa:amazon-ec2"), diff --git a/gradle/run.gradle b/gradle/run.gradle index 5a1fed06c0ef7..550614f4c8266 100644 --- a/gradle/run.gradle +++ b/gradle/run.gradle @@ -34,6 +34,7 @@ apply plugin: 'opensearch.testclusters' testClusters { runTask { testDistribution = 'archive' + plugin(':plugins:api') } } diff --git a/plugins/api/README.md b/plugins/api/README.md new file mode 100644 index 0000000000000..c04b120ec7673 --- /dev/null +++ b/plugins/api/README.md @@ -0,0 +1,63 @@ +## OpenSearch API Plugin + +A plugin that returns the OpenSearch API in the OpenAPI format. + +### Build and Test + +```sh +./gradlew :plugins:api:build +``` + +You can run various test suites individually. + +```sh +./gradlew :plugins:api:test # unit tests +./gradlew :plugins:api:integTest # integration tests +./gradlew :plugins:api:yamlRestTest # YAML REST tests +``` + +### Run + +Modify `gradle/run.gradle`. + +```gradle +testClusters { + runTask { + plugin(':plugins:api') + } +} +``` + + +When you run OpenSearch with `./gradlew run"` you should see the plugin loaded in the logs. + +``` +[2023-09-27T08:35:48,627][INFO ][o.o.p.PluginsService] [runTask-0] loaded plugin [api] +``` + +### Try + +```sh +$ curl http://localhost:9200/_plugins/api +``` + +Returns an OpenAPI spec. + +```json +{ + "openapi": "3.0.1", + "info": { + "title": "opensearch", + "description": "The OpenSearch Project: https://opensearch.org/", + "version": "3.0.0-SNAPSHOT" + }, + "paths": { + "/_nodes": { + "get": {} + }, + "/_cluster/state/:metric": { + "get": {} + }, + ... + } +``` diff --git a/plugins/api/build.gradle b/plugins/api/build.gradle new file mode 100644 index 0000000000000..4cb52a76731f8 --- /dev/null +++ b/plugins/api/build.gradle @@ -0,0 +1,50 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + * + * Modifications Copyright OpenSearch Contributors. See + * GitHub history for details. + */ + +import org.opensearch.gradle.LoggedExec +import org.opensearch.gradle.info.BuildParams + +apply plugin: 'opensearch.build' +apply plugin: 'opensearch.publish' +apply plugin: 'opensearch.testclusters' +apply plugin: 'opensearch.yaml-rest-test' +apply plugin: 'opensearch.rest-test' + +opensearchplugin { + description 'The API plugin returns an OpenAPI spec.' + classname 'org.opensearch.plugin.api.APIPlugin' +} + +ext { + failOnJavadocWarning = false +} + +dependencies { + api "commons-logging:commons-logging:${versions.commonslogging}" + api "org.apache.logging.log4j:log4j-1.2-api:${versions.log4j}" +} + +restResources { + restApi { + includeCore '_common', 'cat' + } +} + +thirdPartyAudit.enabled = false +testingConventions.enabled = false + +tasks.named("integTest").configure { + it.dependsOn(project.tasks.named("bundlePlugin")) +} + +testClusters.integTest { + plugin(project.tasks.bundlePlugin.archiveFile) +} diff --git a/plugins/api/licenses/commons-logging-1.2.jar.sha1 b/plugins/api/licenses/commons-logging-1.2.jar.sha1 new file mode 100644 index 0000000000000..f40f0242448e8 --- /dev/null +++ b/plugins/api/licenses/commons-logging-1.2.jar.sha1 @@ -0,0 +1 @@ +4bfc12adfe4842bf07b657f0369c4cb522955686 \ No newline at end of file diff --git a/plugins/api/licenses/commons-logging-LICENSE.txt b/plugins/api/licenses/commons-logging-LICENSE.txt new file mode 100644 index 0000000000000..57bc88a15a0ee --- /dev/null +++ b/plugins/api/licenses/commons-logging-LICENSE.txt @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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. + diff --git a/plugins/api/licenses/commons-logging-NOTICE.txt b/plugins/api/licenses/commons-logging-NOTICE.txt new file mode 100644 index 0000000000000..72eb32a902458 --- /dev/null +++ b/plugins/api/licenses/commons-logging-NOTICE.txt @@ -0,0 +1,5 @@ +Apache Commons CLI +Copyright 2001-2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). diff --git a/plugins/api/licenses/log4j-1.2-api-2.21.0.jar.sha1 b/plugins/api/licenses/log4j-1.2-api-2.21.0.jar.sha1 new file mode 100644 index 0000000000000..39d9177cb2fac --- /dev/null +++ b/plugins/api/licenses/log4j-1.2-api-2.21.0.jar.sha1 @@ -0,0 +1 @@ +12bad3819a9570807f3c97315930699584c12152 \ No newline at end of file diff --git a/plugins/api/licenses/log4j-LICENSE.txt b/plugins/api/licenses/log4j-LICENSE.txt new file mode 100644 index 0000000000000..6279e5206de13 --- /dev/null +++ b/plugins/api/licenses/log4j-LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 1999-2005 The Apache Software Foundation + + Licensed 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. diff --git a/plugins/api/licenses/log4j-NOTICE.txt b/plugins/api/licenses/log4j-NOTICE.txt new file mode 100644 index 0000000000000..0375732360047 --- /dev/null +++ b/plugins/api/licenses/log4j-NOTICE.txt @@ -0,0 +1,5 @@ +Apache log4j +Copyright 2007 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). \ No newline at end of file diff --git a/plugins/api/src/main/java/org/opensearch/plugin/api/APIPlugin.java b/plugins/api/src/main/java/org/opensearch/plugin/api/APIPlugin.java new file mode 100644 index 0000000000000..a19f0b540b2a2 --- /dev/null +++ b/plugins/api/src/main/java/org/opensearch/plugin/api/APIPlugin.java @@ -0,0 +1,60 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +package org.opensearch.plugin.api; + +import org.opensearch.action.ActionRequest; +import org.opensearch.cluster.metadata.IndexNameExpressionResolver; +import org.opensearch.cluster.node.DiscoveryNodes; +import org.opensearch.common.settings.ClusterSettings; +import org.opensearch.common.settings.IndexScopedSettings; +import org.opensearch.common.settings.Settings; +import org.opensearch.common.settings.SettingsFilter; +import org.opensearch.core.action.ActionResponse; +import org.opensearch.plugin.api.action.APIAction; +import org.opensearch.plugin.api.action.TransportAPIAction; +import org.opensearch.plugins.ActionPlugin; +import org.opensearch.plugins.Plugin; +import org.opensearch.rest.RestController; +import org.opensearch.rest.RestHandler; + +import java.util.List; +import java.util.function.Supplier; + +import static java.util.Collections.singletonList; + +/** + * A plugin that returns the OpenAPI spec for the current OpenSearch instance. + */ +public class APIPlugin extends Plugin implements ActionPlugin { + /** + * Instantiate this plugin. + */ + public APIPlugin() { + + } + + @Override + public List> getActions() { + return singletonList(new ActionHandler<>(APIAction.INSTANCE, TransportAPIAction.class)); + } + + @Override + public List getRestHandlers( + final Settings settings, + final RestController restController, + final ClusterSettings clusterSettings, + final IndexScopedSettings indexScopedSettings, + final SettingsFilter settingsFilter, + final IndexNameExpressionResolver indexNameExpressionResolver, + final Supplier nodesInCluster + ) { + + return singletonList(new RestAPIAction(restController)); + } +} diff --git a/plugins/api/src/main/java/org/opensearch/plugin/api/RestAPIAction.java b/plugins/api/src/main/java/org/opensearch/plugin/api/RestAPIAction.java new file mode 100644 index 0000000000000..df1e7aa404b04 --- /dev/null +++ b/plugins/api/src/main/java/org/opensearch/plugin/api/RestAPIAction.java @@ -0,0 +1,77 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +package org.opensearch.plugin.api; + +import org.opensearch.client.node.NodeClient; +import org.opensearch.core.rest.RestStatus; +import org.opensearch.core.xcontent.XContentBuilder; +import org.opensearch.plugin.api.action.APIAction; +import org.opensearch.plugin.api.action.APIRequest; +import org.opensearch.plugin.api.action.APIResponse; +import org.opensearch.rest.BaseRestHandler; +import org.opensearch.rest.BytesRestResponse; +import org.opensearch.rest.RestController; +import org.opensearch.rest.RestRequest; +import org.opensearch.rest.RestResponse; +import org.opensearch.rest.action.RestBuilderListener; + +import java.io.IOException; +import java.util.List; + +import static java.util.Arrays.asList; +import static java.util.Collections.unmodifiableList; +import static org.opensearch.rest.RestRequest.Method.GET; + +/** + * A REST handler. + */ +public class RestAPIAction extends BaseRestHandler { + RestController restController; + + RestAPIAction(RestController restController) { + this.restController = restController; + } + + /** + * + * @return + */ + @Override + public String getName() { + return "api"; + } + + /** + * + * @return + */ + @Override + public List routes() { + return unmodifiableList(asList(new Route(GET, "/_plugins/api"))); + } + + /** + * + * @param request the request to execute + * @param client client for executing actions on the local node + * @return + * @throws IOException + */ + @Override + protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { + return channel -> client.execute(APIAction.INSTANCE, new APIRequest(), new RestBuilderListener(channel) { + @Override + public RestResponse buildResponse(APIResponse response, XContentBuilder builder) throws Exception { + response.setRestController(restController); + response.toXContent(builder, request); + return new BytesRestResponse(RestStatus.OK, builder); + } + }); + } +} diff --git a/plugins/api/src/main/java/org/opensearch/plugin/api/action/APIAction.java b/plugins/api/src/main/java/org/opensearch/plugin/api/action/APIAction.java new file mode 100644 index 0000000000000..dfe465be65372 --- /dev/null +++ b/plugins/api/src/main/java/org/opensearch/plugin/api/action/APIAction.java @@ -0,0 +1,21 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +package org.opensearch.plugin.api.action; + +import org.opensearch.action.ActionType; + +public class APIAction extends ActionType { + + public static final String NAME = "api"; + public static final APIAction INSTANCE = new APIAction(); + + public APIAction() { + super(NAME, APIResponse::new); + } +} diff --git a/plugins/api/src/main/java/org/opensearch/plugin/api/action/APIRequest.java b/plugins/api/src/main/java/org/opensearch/plugin/api/action/APIRequest.java new file mode 100644 index 0000000000000..654454b3cc97f --- /dev/null +++ b/plugins/api/src/main/java/org/opensearch/plugin/api/action/APIRequest.java @@ -0,0 +1,37 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +package org.opensearch.plugin.api.action; + +import org.opensearch.action.ActionRequest; +import org.opensearch.action.ActionRequestValidationException; +import org.opensearch.core.common.io.stream.StreamInput; + +import java.io.IOException; + +public class APIRequest extends ActionRequest { + + /** + * + */ + public APIRequest() {} + + /** + * + * @param in + * @throws IOException + */ + APIRequest(StreamInput in) throws IOException { + super(in); + } + + @Override + public ActionRequestValidationException validate() { + return null; + } +} diff --git a/plugins/api/src/main/java/org/opensearch/plugin/api/action/APIRequestBuilder.java b/plugins/api/src/main/java/org/opensearch/plugin/api/action/APIRequestBuilder.java new file mode 100644 index 0000000000000..7a24db8722386 --- /dev/null +++ b/plugins/api/src/main/java/org/opensearch/plugin/api/action/APIRequestBuilder.java @@ -0,0 +1,19 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +package org.opensearch.plugin.api.action; + +import org.opensearch.action.ActionRequestBuilder; +import org.opensearch.client.OpenSearchClient; + +public class APIRequestBuilder extends ActionRequestBuilder { + + public APIRequestBuilder(OpenSearchClient client, APIAction action) { + super(client, action, new APIRequest()); + } +} diff --git a/plugins/api/src/main/java/org/opensearch/plugin/api/action/APIResponse.java b/plugins/api/src/main/java/org/opensearch/plugin/api/action/APIResponse.java new file mode 100644 index 0000000000000..8b4a49e6c3df1 --- /dev/null +++ b/plugins/api/src/main/java/org/opensearch/plugin/api/action/APIResponse.java @@ -0,0 +1,84 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +package org.opensearch.plugin.api.action; + +import org.opensearch.Build; +import org.opensearch.Version; +import org.opensearch.action.main.MainResponse; +import org.opensearch.core.action.ActionResponse; +import org.opensearch.core.common.io.stream.StreamInput; +import org.opensearch.core.common.io.stream.StreamOutput; +import org.opensearch.core.xcontent.ToXContentObject; +import org.opensearch.core.xcontent.XContentBuilder; +import org.opensearch.rest.RestController; + +import java.io.IOException; + +public class APIResponse extends ActionResponse implements ToXContentObject { + + private Version version; + private Build build; + private RestController restController; + + APIResponse() { + + } + + APIResponse(StreamInput in) throws IOException { + super(in); + version = in.readVersion(); + build = in.readBuild(); + } + + APIResponse(Version version, Build build) { + this.version = version; + this.build = build; + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + out.writeVersion(version); + out.writeBuild(build); + } + + public Version getVersion() { + return version; + } + + public Build getBuild() { + return build; + } + + public void setRestController(RestController restController) { + this.restController = restController; + } + + @Override + public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { + builder.startObject(); + + builder.field("openapi", "3.0.1"); + + builder.startObject("info") + .field("title", build.getDistribution()) + .field("description", MainResponse.TAGLINE) + .field("version", build.getQualifiedVersion()) + .endObject(); + + restController.toXContent(builder, params); + + builder.endObject(); + return builder; + } + + @Override + public String toString() { + return "APIResponse{" + '\'' + ", version=" + version + '\'' + ", build=" + build + '}'; + } +} diff --git a/plugins/api/src/main/java/org/opensearch/plugin/api/action/TransportAPIAction.java b/plugins/api/src/main/java/org/opensearch/plugin/api/action/TransportAPIAction.java new file mode 100644 index 0000000000000..76d64e0f73902 --- /dev/null +++ b/plugins/api/src/main/java/org/opensearch/plugin/api/action/TransportAPIAction.java @@ -0,0 +1,32 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +package org.opensearch.plugin.api.action; + +import org.opensearch.Build; +import org.opensearch.Version; +import org.opensearch.action.support.ActionFilters; +import org.opensearch.action.support.HandledTransportAction; +import org.opensearch.common.inject.Inject; +import org.opensearch.common.settings.Settings; +import org.opensearch.core.action.ActionListener; +import org.opensearch.tasks.Task; +import org.opensearch.transport.TransportService; + +public class TransportAPIAction extends HandledTransportAction { + + @Inject + public TransportAPIAction(Settings settings, TransportService transportService, ActionFilters actionFilters) { + super(APIAction.NAME, transportService, actionFilters, APIRequest::new); + } + + @Override + protected void doExecute(Task task, APIRequest request, ActionListener listener) { + listener.onResponse(new APIResponse(Version.CURRENT, Build.CURRENT)); + } +} diff --git a/plugins/api/src/main/java/org/opensearch/plugin/api/package-info.java b/plugins/api/src/main/java/org/opensearch/plugin/api/package-info.java new file mode 100644 index 0000000000000..2f5e43a724005 --- /dev/null +++ b/plugins/api/src/main/java/org/opensearch/plugin/api/package-info.java @@ -0,0 +1,12 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +/** + * A plugin that returns an OpenAPI spec. + */ +package org.opensearch.plugin.api; diff --git a/plugins/api/src/main/plugin-metadata/plugin-security.policy b/plugins/api/src/main/plugin-metadata/plugin-security.policy new file mode 100644 index 0000000000000..120d1d8fbdb3a --- /dev/null +++ b/plugins/api/src/main/plugin-metadata/plugin-security.policy @@ -0,0 +1,11 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +grant { + +}; diff --git a/plugins/api/src/test/java/org/opensearch/plugin/api/APIPluginIT.java b/plugins/api/src/test/java/org/opensearch/plugin/api/APIPluginIT.java new file mode 100644 index 0000000000000..13fedea9ec643 --- /dev/null +++ b/plugins/api/src/test/java/org/opensearch/plugin/api/APIPluginIT.java @@ -0,0 +1,46 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ +package org.opensearch.plugin.api; + +import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; + +import org.apache.http.util.EntityUtils; +import org.opensearch.client.Request; +import org.opensearch.client.Response; +import org.opensearch.plugins.Plugin; +import org.opensearch.test.OpenSearchIntegTestCase; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Collection; +import java.util.Collections; + +@ThreadLeakScope(ThreadLeakScope.Scope.NONE) +@OpenSearchIntegTestCase.ClusterScope(scope = OpenSearchIntegTestCase.Scope.SUITE) +public class APIPluginIT extends OpenSearchIntegTestCase { + + @Override + protected Collection> nodePlugins() { + return Collections.singletonList(APIPlugin.class); + } + + public void testPluginInstalled() throws IOException { + Response response = createRestClient().performRequest(new Request("GET", "/_cat/plugins")); + String body = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); + + logger.info("response body: {}", body.toString()); + assertTrue(body.contains("api")); + } + + public void testPluginGetAPI() throws IOException { + Response response = createRestClient().performRequest(new Request("GET", "/_plugins/api")); + String body = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); + logger.info("response body: {}", body); + assertTrue(body.startsWith("{\"openapi\":\"3.0.1\"")); + } +} diff --git a/plugins/api/src/test/java/org/opensearch/plugin/api/APIPluginTests.java b/plugins/api/src/test/java/org/opensearch/plugin/api/APIPluginTests.java new file mode 100644 index 0000000000000..17d1b544d4ca5 --- /dev/null +++ b/plugins/api/src/test/java/org/opensearch/plugin/api/APIPluginTests.java @@ -0,0 +1,17 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ +package org.opensearch.plugin.api; + +import org.opensearch.test.OpenSearchTestCase; + +public class APIPluginTests extends OpenSearchTestCase { + public void testConstructor() { + APIPlugin plugin = new APIPlugin(); + assertNotNull(plugin); + } +} diff --git a/plugins/api/src/yamlRestTest/java/org/opensearch/api/APIClientYamlTestSuiteIT.java b/plugins/api/src/yamlRestTest/java/org/opensearch/api/APIClientYamlTestSuiteIT.java new file mode 100644 index 0000000000000..9c60ad16333b9 --- /dev/null +++ b/plugins/api/src/yamlRestTest/java/org/opensearch/api/APIClientYamlTestSuiteIT.java @@ -0,0 +1,26 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ +package org.opensearch.plugins.api; + +import com.carrotsearch.randomizedtesting.annotations.Name; +import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; + +import org.opensearch.test.rest.yaml.ClientYamlTestCandidate; +import org.opensearch.test.rest.yaml.OpenSearchClientYamlSuiteTestCase; + +public class APIClientYamlTestSuiteIT extends OpenSearchClientYamlSuiteTestCase { + + public APIClientYamlTestSuiteIT(@Name("yaml") ClientYamlTestCandidate testCandidate) { + super(testCandidate); + } + + @ParametersFactory + public static Iterable parameters() throws Exception { + return OpenSearchClientYamlSuiteTestCase.createParameters(); + } +} diff --git a/plugins/api/src/yamlRestTest/resources/rest-api-spec/api/api.json b/plugins/api/src/yamlRestTest/resources/rest-api-spec/api/api.json new file mode 100644 index 0000000000000..763b201f0e375 --- /dev/null +++ b/plugins/api/src/yamlRestTest/resources/rest-api-spec/api/api.json @@ -0,0 +1,20 @@ +{ + "api":{ + "documentation":{ + "url":"", + "description":"Returns REST API spec." + }, + "stability":"experimental", + "url":{ + "paths":[ + { + "path":"/_plugins/api", + "methods":[ + "GET" + ] + } + ] + }, + "params":{} + } + } \ No newline at end of file diff --git a/plugins/api/src/yamlRestTest/resources/rest-api-spec/test/10_basic.yml b/plugins/api/src/yamlRestTest/resources/rest-api-spec/test/10_basic.yml new file mode 100644 index 0000000000000..feb883fb11b6e --- /dev/null +++ b/plugins/api/src/yamlRestTest/resources/rest-api-spec/test/10_basic.yml @@ -0,0 +1,8 @@ +"Test that the plugin is loaded in OpenSearch": + - do: + cat.plugins: + local: true + h: component + + - match: + $body: /^api\n$/ diff --git a/plugins/api/src/yamlRestTest/resources/rest-api-spec/test/20_api.yml b/plugins/api/src/yamlRestTest/resources/rest-api-spec/test/20_api.yml new file mode 100644 index 0000000000000..72f31250b86bb --- /dev/null +++ b/plugins/api/src/yamlRestTest/resources/rest-api-spec/test/20_api.yml @@ -0,0 +1,12 @@ +"Test that the plugin returns an API spec": + - do: + api: {} + + - match: { info.title: "opensearch" } + - match: { info.version: /.*-SNAPSHOT/ } + - match: { info.description: "The OpenSearch Project: https://opensearch.org/" } + + - match: { paths./_plugins/api.get: {} } + + - match: { paths./:index/_upgrade.post: {} } + - match: { paths./:index/_upgrade.get: {} } diff --git a/server/src/main/java/org/opensearch/common/path/PathTrie.java b/server/src/main/java/org/opensearch/common/path/PathTrie.java index 7cb7b46acfafe..eeff853566c1c 100644 --- a/server/src/main/java/org/opensearch/common/path/PathTrie.java +++ b/server/src/main/java/org/opensearch/common/path/PathTrie.java @@ -37,6 +37,7 @@ import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; +import java.util.Stack; import java.util.function.BiFunction; import java.util.function.Supplier; @@ -405,4 +406,28 @@ public T next() { } }; } + + public Iterator retrieveAll() { + Stack stack = new Stack<>(); + stack.add(root); + + return new Iterator() { + @Override + public boolean hasNext() { + return !stack.empty(); + } + + @Override + public T next() { + while (!stack.empty()) { + TrieNode node = stack.pop(); + stack.addAll(node.children.values()); + if (node.value != null) { + return node.value; + } + } + throw new NoSuchElementException("encountered a terminal node without a value"); + } + }; + } } diff --git a/server/src/main/java/org/opensearch/rest/MethodHandlers.java b/server/src/main/java/org/opensearch/rest/MethodHandlers.java index 8c29bf2e66036..6269891312abd 100644 --- a/server/src/main/java/org/opensearch/rest/MethodHandlers.java +++ b/server/src/main/java/org/opensearch/rest/MethodHandlers.java @@ -48,6 +48,13 @@ final class MethodHandlers { private final String path; private final Map methodHandlers; + /** + * Complete path of the method handlers. + */ + public String getPath() { + return path; + } + MethodHandlers(String path, RestHandler handler, RestRequest.Method... methods) { this.path = path; this.methodHandlers = new HashMap<>(methods.length); diff --git a/server/src/main/java/org/opensearch/rest/RestController.java b/server/src/main/java/org/opensearch/rest/RestController.java index ac30f999d0da7..ba8b3b5cafa41 100644 --- a/server/src/main/java/org/opensearch/rest/RestController.java +++ b/server/src/main/java/org/opensearch/rest/RestController.java @@ -53,6 +53,7 @@ import org.opensearch.core.rest.RestStatus; import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.MediaTypeRegistry; +import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.http.HttpServerTransport; import org.opensearch.identity.IdentityService; @@ -69,6 +70,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; @@ -89,7 +91,7 @@ * * @opensearch.api */ -public class RestController implements HttpServerTransport.Dispatcher { +public class RestController implements HttpServerTransport.Dispatcher, ToXContentObject { private static final Logger logger = LogManager.getLogger(RestController.class); private static final DeprecationLogger deprecationLogger = DeprecationLogger.getLogger(RestController.class); @@ -571,6 +573,30 @@ private Set getValidHandlerMethodSet(String rawPath) { return validMethods; } + @Override + public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { + builder.startObject("paths"); + + Iterator all = handlers.retrieveAll(); + + while (all.hasNext()) { + MethodHandlers handlers = all.next(); + builder.startObject(handlers.getPath().replace("{", ":").replace("}", "")); + for (RestRequest.Method method : handlers.getValidMethods()) { + builder.startObject(method.name().toLowerCase(Locale.ROOT)) + // .field("summary", "") + // .field("description", "") + // .startObject("responses", "") + // .endObject()) + .endObject(); + } + builder.endObject(); + } + + builder.endObject(); + return builder; + } + private static final class ResourceHandlingHttpChannel implements RestChannel { private final RestChannel delegate; private final CircuitBreakerService circuitBreakerService;