├── .gitignore ├── LICENSE ├── README.md ├── data └── zips.json ├── docs ├── zeppelin-mongo-config.png ├── zeppelin-mongo-examples.png ├── zeppelin-mongo-interpreter-install.png ├── zeppelin-mongodb-interpreter-monitor.png └── zeppelin-mongodb-interpreter.png ├── pom.xml └── src ├── main ├── java │ └── org │ │ └── apache │ │ └── zeppelin │ │ └── mongodb │ │ └── MongoDbInterpreter.java └── resources │ ├── interpreter-setting.json │ └── shell_extension.js └── test └── java └── org └── apache └── zeppelin └── mongodb └── MongoDbInterpreterTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | target/ 4 | pom.xml.tag 5 | pom.xml.releaseBackup 6 | pom.xml.versionsBackup 7 | pom.xml.next 8 | release.properties 9 | dependency-reduced-pom.xml 10 | buildNumber.properties 11 | .mvn/timing.properties 12 | .classpath 13 | .project 14 | .settings/ 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # zeppelin-mongodb-interpreter 2 | MongoDB interpreter for Apache Zeppelin. 3 | 4 | __Supported versions of MongoDB: >= 3.0__ 5 | 6 | 7 | > If you are interested, there is a Docker image for Zeppelin with MongoDB interpreter: https://hub.docker.com/r/cthiebault/zeppelin-mongodb/ 8 | 9 | ## Build 10 | 11 | Requirement: Zeppelin must be in your local repo. 12 | 13 | ```sh 14 | mvn clean package 15 | ``` 16 | 17 | ## Download 18 | 19 | If you cannot build the jar, you can download it in the [release page](https://github.com/bbonnin/zeppelin-mongodb-interpreter/releases) 20 | 21 | ## Deployment 22 | 23 | * Update `$ZEPPELIN_HOME/conf/zeppeln-site.xml` 24 | ```xml 25 | 26 | zeppelin.interpreters 27 | ...,org.apache.zeppelin.mongodb.MongoDbInterpreter 28 | 29 | ``` 30 | * Create `$ZEPPELIN_HOME/interpreter/mongodb` 31 | * Copy interpreter jar in `$ZEPPELIN_HOME/interpreter/mongodb` 32 | 33 | 34 | > In some cases, mongodb is not visible in the list of the available interpreters. In this case, after the previous steps, you can create a new interpreter and in the interpreter group selection, you should be able to select mongodb. 35 | 36 | ![Create](docs/zeppelin-mongo-interpreter-install.png) 37 | 38 | 39 | 40 | ## Configuration 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 |
ParameterDefault valueDescription
mongo.shell.pathmongoMongo shell path
mongo.shell.command.timeout60000Mongo command timeout
mongo.shell.command.table.limit1000Limit of documents displayed in a table
mongo.server.databasetestMongDB database name
mongo.server.hostlocalhostHost of the MongDB server
mongo.server.port27017Port of the MongDB server
mongo.server.usernameUsername for authentication
mongo.server.passwordPassword for authentication
mongo.server.authentdatabaseDatabase used for authentication
54 | 55 | ## How to use 56 | 57 | In Zeppelin, use `%mongodb` in a paragraph. 58 | After that, you can type the same Javascript code you use when you write scripts for the Mongo shell. 59 | For more information, please consult: https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/ 60 | 61 | There are several functions that have been added to help you in Zeppelin: 62 | * printTable(cursor, fields, flattenArray): to print a table (i.e. it uses `%table`). Arguments: 63 | * cursor: a DBQuery or DBCommandCursor instance 64 | * fields: an array of field names to put in the table (can be null) 65 | * flattenArray: if true, the arrays in the documents will also be flatten (false by default) 66 | * DBQuery.prototype.table: to print a table (it invokes the previous function) 67 | * DBCommandCursor.prototype.table: same as above 68 | 69 | Examples: 70 | ```javascript 71 | %mongodb 72 | 73 | // Display a table 74 | db.zipcodes.find({ "city":"CHICAGO", "state": "IL" }).table() 75 | ``` 76 | 77 | ```javascript 78 | %mongodb 79 | 80 | var states = db.zipcodes.aggregate( [ 81 | { $group: { _id: "$state", totalPop: { $sum: "$pop" } } }, 82 | { $match: { totalPop: { $lt: 1000*1000 } } }, 83 | { $sort: { totalPop: 1 } } 84 | ] ) 85 | 86 | // Build a 'table' 87 | print("%table state\ttotalPop") 88 | states.forEach(state => { print(state._id + "\t" + state.totalPop) }) 89 | ``` 90 | 91 | 92 | ## Examples 93 | 94 | * Configuration: 95 | ![Configuration](docs/zeppelin-mongo-config.png) 96 | 97 | * Queries (these examples come from: https://docs.mongodb.com/manual/tutorial/aggregation-zip-code-data-set/) 98 | ![Examples](docs/zeppelin-mongo-examples.png) 99 | 100 | 101 | -------------------------------------------------------------------------------- /docs/zeppelin-mongo-config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbonnin/zeppelin-mongodb-interpreter/24f0a352355ae3ae61e3d5797e22dff0d629fc9d/docs/zeppelin-mongo-config.png -------------------------------------------------------------------------------- /docs/zeppelin-mongo-examples.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbonnin/zeppelin-mongodb-interpreter/24f0a352355ae3ae61e3d5797e22dff0d629fc9d/docs/zeppelin-mongo-examples.png -------------------------------------------------------------------------------- /docs/zeppelin-mongo-interpreter-install.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbonnin/zeppelin-mongodb-interpreter/24f0a352355ae3ae61e3d5797e22dff0d629fc9d/docs/zeppelin-mongo-interpreter-install.png -------------------------------------------------------------------------------- /docs/zeppelin-mongodb-interpreter-monitor.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbonnin/zeppelin-mongodb-interpreter/24f0a352355ae3ae61e3d5797e22dff0d629fc9d/docs/zeppelin-mongodb-interpreter-monitor.png -------------------------------------------------------------------------------- /docs/zeppelin-mongodb-interpreter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbonnin/zeppelin-mongodb-interpreter/24f0a352355ae3ae61e3d5797e22dff0d629fc9d/docs/zeppelin-mongodb-interpreter.png -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 9 | 10 | 11 | org.apache.zeppelin 12 | zeppelin-mongodb 13 | jar 14 | 0.9.0-preview1 15 | Zeppelin: MongoDB interpreter 16 | http://www.apache.org 17 | 18 | 19 | UTF-8 20 | 0.9.0-preview1 21 | 4.11 22 | 23 | 24 | 25 | 26 | org.apache.zeppelin 27 | zeppelin-interpreter 28 | ${project.version} 29 | provided 30 | 31 | 32 | 33 | junit 34 | junit 35 | ${junit.version} 36 | test 37 | 38 | 39 | 40 | 41 | 42 | 43 | maven-compiler-plugin 44 | 3.3 45 | 46 | 1.7 47 | 1.7 48 | 49 | 50 | 51 | maven-assembly-plugin 52 | 2.6 53 | 54 | 55 | jar-with-dependencies 56 | 57 | 58 | 59 | 60 | make-assembly 61 | package 62 | 63 | single 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /src/main/java/org/apache/zeppelin/mongodb/MongoDbInterpreter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.zeppelin.mongodb; 18 | 19 | import java.io.ByteArrayOutputStream; 20 | import java.io.File; 21 | import java.io.IOException; 22 | import java.util.HashMap; 23 | import java.util.Map; 24 | import java.util.Properties; 25 | import java.util.Scanner; 26 | 27 | import org.apache.commons.exec.CommandLine; 28 | import org.apache.commons.exec.DefaultExecutor; 29 | import org.apache.commons.exec.ExecuteException; 30 | import org.apache.commons.exec.ExecuteWatchdog; 31 | import org.apache.commons.exec.Executor; 32 | import org.apache.commons.exec.PumpStreamHandler; 33 | import org.apache.commons.io.FileUtils; 34 | import org.apache.commons.lang.StringUtils; 35 | import org.apache.zeppelin.interpreter.Interpreter; 36 | import org.apache.zeppelin.interpreter.InterpreterContext; 37 | import org.apache.zeppelin.interpreter.InterpreterResult; 38 | import org.apache.zeppelin.interpreter.InterpreterResult.Code; 39 | import org.apache.zeppelin.scheduler.Scheduler; 40 | import org.apache.zeppelin.scheduler.SchedulerFactory; 41 | import org.slf4j.Logger; 42 | import org.slf4j.LoggerFactory; 43 | 44 | /** 45 | * MongoDB interpreter. It uses the mongo shell to interpret the commands. 46 | * 47 | */ 48 | public class MongoDbInterpreter extends Interpreter { 49 | 50 | private static final Logger LOGGER = LoggerFactory.getLogger(MongoDbInterpreter.class); 51 | 52 | private static final String SHELL_EXTENSION = 53 | new Scanner(MongoDbInterpreter.class.getResourceAsStream("/shell_extension.js"), "UTF-8") 54 | .useDelimiter("\\A").next(); 55 | 56 | private long commandTimeout = 60000; 57 | 58 | private String dbAddress; 59 | 60 | private Map runningProcesses = new HashMap<>(); 61 | 62 | 63 | public MongoDbInterpreter(Properties property) { 64 | super(property); 65 | } 66 | 67 | @Override 68 | public void open() { 69 | commandTimeout = Long.parseLong(getProperty("mongo.shell.command.timeout")); 70 | if (StringUtils.isEmpty(getProperty("mongo.server.uri"))) 71 | dbAddress = getProperty("mongo.server.host") + ":" 72 | + getProperty("mongo.server.port") + "/" 73 | + getProperty("mongo.server.database"); 74 | else 75 | dbAddress = getProperty("mongo.server.uri"); 76 | } 77 | 78 | @Override 79 | public void close() { 80 | //Nothing to do 81 | } 82 | 83 | @Override 84 | public FormType getFormType() { 85 | return FormType.SIMPLE; 86 | } 87 | 88 | @Override 89 | public InterpreterResult interpret(String script, InterpreterContext context) { 90 | LOGGER.debug("Run MongoDB script: {}", script); 91 | 92 | if (StringUtils.isEmpty(script)) { 93 | return new InterpreterResult(Code.SUCCESS); 94 | } 95 | 96 | // Write script in a temporary file 97 | // The script is enriched with extensions 98 | final File scriptFile = new File(getScriptFileName(context.getParagraphId())); 99 | try { 100 | FileUtils.write(scriptFile, 101 | SHELL_EXTENSION 102 | .replace("__ZEPPELIN_TABLE_LIMIT__", getProperty("mongo.shell.command.table.limit")) + 103 | script); 104 | } 105 | catch (IOException e) { 106 | LOGGER.error("Can not write script in temp file", e); 107 | return new InterpreterResult(Code.ERROR, e.getMessage()); 108 | } 109 | 110 | InterpreterResult result = new InterpreterResult(InterpreterResult.Code.SUCCESS); 111 | 112 | final DefaultExecutor executor = new DefaultExecutor(); 113 | final ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); 114 | executor.setStreamHandler(new PumpStreamHandler(context.out, errorStream)); 115 | executor.setWatchdog(new ExecuteWatchdog(commandTimeout)); //ExecuteWatchdog.INFINITE_TIMEOUT 116 | 117 | final CommandLine cmdLine = CommandLine.parse(getProperty("mongo.shell.path")); 118 | cmdLine.addArgument("--quiet", false); 119 | 120 | if (StringUtils.isEmpty(getProperty("mongo.server.uri"))) { 121 | if (!StringUtils.isEmpty(getProperty("mongo.server.username"))) { 122 | cmdLine.addArgument("-u", false); 123 | cmdLine.addArgument(getProperty("mongo.server.username"), false); 124 | cmdLine.addArgument("-p", false); 125 | cmdLine.addArgument(getProperty("mongo.server.password"), false); 126 | 127 | if (!StringUtils.isEmpty(getProperty("mongo.server.authentdatabase"))) { 128 | cmdLine.addArgument("--authenticationDatabase", false); 129 | cmdLine.addArgument(getProperty("mongo.server.authentdatabase"), false); 130 | } 131 | } 132 | } 133 | 134 | cmdLine.addArgument(dbAddress, false); 135 | cmdLine.addArgument(scriptFile.getAbsolutePath(), false); 136 | 137 | try { 138 | executor.execute(cmdLine); 139 | runningProcesses.put(context.getParagraphId(), executor); 140 | } 141 | catch (ExecuteException e) { 142 | LOGGER.error("Can not run script in paragraph {}", context.getParagraphId(), e); 143 | 144 | final int exitValue = e.getExitValue(); 145 | Code code = Code.ERROR; 146 | String msg = errorStream.toString(); 147 | if (exitValue == 143) { 148 | code = Code.INCOMPLETE; 149 | msg = msg + "Paragraph received a SIGTERM.\n"; 150 | LOGGER.info("The paragraph {} stopped executing: {}", context.getParagraphId(), msg); 151 | } 152 | msg += "ExitValue: " + exitValue; 153 | result = new InterpreterResult(code, msg); 154 | } 155 | catch (IOException e) { 156 | LOGGER.error("Can not run script in paragraph {}", context.getParagraphId(), e); 157 | result = new InterpreterResult(Code.ERROR, e.getMessage()); 158 | } 159 | finally { 160 | FileUtils.deleteQuietly(scriptFile); 161 | } 162 | 163 | return result; 164 | } 165 | 166 | @Override 167 | public int getProgress(InterpreterContext context) { 168 | return 0; 169 | } 170 | 171 | @Override 172 | public void cancel(InterpreterContext context) { 173 | stopProcess(context.getParagraphId()); 174 | FileUtils.deleteQuietly(new File(getScriptFileName(context.getParagraphId()))); 175 | } 176 | 177 | @Override 178 | public Scheduler getScheduler() { 179 | return SchedulerFactory.singleton().createOrGetParallelScheduler("mongo", 10); 180 | } 181 | 182 | private String getScriptFileName(String paragraphId) { 183 | return System.getProperty("java.io.tmpdir") + File.separator + 184 | "zeppelin-mongo-" + paragraphId + ".js"; 185 | } 186 | 187 | private void stopProcess(String paragraphId) { 188 | if (runningProcesses.containsKey(paragraphId)) { 189 | final Executor executor = runningProcesses.get(paragraphId); 190 | final ExecuteWatchdog watchdog = executor.getWatchdog(); 191 | watchdog.destroyProcess(); 192 | } 193 | } 194 | 195 | } 196 | -------------------------------------------------------------------------------- /src/main/resources/interpreter-setting.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "group": "mongodb", 4 | "name": "mongodb", 5 | "className": "org.apache.zeppelin.mongodb.MongoDbInterpreter", 6 | "properties": { 7 | "mongo.server.uri": { 8 | "envName": null, 9 | "propertyName": "mongo.server.uri", 10 | "defaultValue": "", 11 | "description": "MongoDB Connection String" 12 | }, 13 | "mongo.shell.path": { 14 | "envName": null, 15 | "propertyName": "mongo.shell.path", 16 | "defaultValue": "mongo", 17 | "description": "MongoDB shell path" 18 | }, 19 | "mongo.shell.command.table.limit": { 20 | "envName": null, 21 | "propertyName": "mongo.shell.command.table.limit", 22 | "defaultValue": "1000", 23 | "description": "Limit of documents displayed in a table" 24 | }, 25 | "mongo.shell.command.timeout": { 26 | "envName": null, 27 | "propertyName": "mongo.shell.command.timeout", 28 | "defaultValue": "60000", 29 | "description": "MongoDB shell command timeout" 30 | }, 31 | "mongo.server.host": { 32 | "envName": null, 33 | "propertyName": "mongo.server.host", 34 | "defaultValue": "localhost", 35 | "description": "MongoDB server host to connect to" 36 | }, 37 | "mongo.server.port": { 38 | "envName": null, 39 | "propertyName": "mongo.server.port", 40 | "defaultValue": "27017", 41 | "description": "MongoDB server port to connect to" 42 | }, 43 | "mongo.server.database": { 44 | "envName": null, 45 | "propertyName": "mongo.server.database", 46 | "defaultValue": "test", 47 | "description": "MongoDB database name" 48 | }, 49 | "mongo.server.authentdatabase": { 50 | "envName": null, 51 | "propertyName": "mongo.server.authentdatabase", 52 | "defaultValue": "", 53 | "description": "MongoDB database name for authentication" 54 | }, 55 | "mongo.server.username": { 56 | "envName": null, 57 | "propertyName": "mongo.server.username", 58 | "defaultValue": "", 59 | "description": "Username for authentication" 60 | }, 61 | "mongo.server.password": { 62 | "envName": null, 63 | "propertyName": "mongo.server.password", 64 | "defaultValue": "", 65 | "description": "Password for authentication" 66 | } 67 | } 68 | } 69 | ] 70 | -------------------------------------------------------------------------------- /src/main/resources/shell_extension.js: -------------------------------------------------------------------------------- 1 | var _ZEPPELIN_TABLE_LIMIT_ = __ZEPPELIN_TABLE_LIMIT__; 2 | 3 | function flattenObject(obj, flattenArray) { 4 | var toReturn = {}; 5 | 6 | for (var i in obj) { 7 | if (!obj.hasOwnProperty(i)) continue; 8 | 9 | //if ((typeof obj[i]) == 'object') { 10 | if (toString.call( obj[i] ) === '[object Object]' || 11 | toString.call( obj[i] ) === '[object BSON]' || 12 | (flattenArray && toString.call( obj[i] ) === '[object Array]')) { 13 | var flatObject = flattenObject(obj[i]); 14 | for (var x in flatObject) { 15 | if (!flatObject.hasOwnProperty(x)) continue; 16 | 17 | toReturn[i + '.' + x] = flatObject[x]; 18 | } 19 | } else if (toString.call( obj[i] ) === '[object Array]') { 20 | toReturn[i] = tojson(obj[i], null, true); 21 | } else { 22 | toReturn[i] = obj[i]; 23 | } 24 | } 25 | return toReturn; 26 | } 27 | 28 | function printTable(dbquery, fields, flattenArray) { 29 | 30 | var iterator = dbquery; 31 | 32 | if (toString.call( dbquery ) === '[object Array]') { 33 | iterator = (function() { 34 | var index = 0, 35 | data = dbquery, 36 | length = data.length; 37 | 38 | return { 39 | next: function() { 40 | if (!this.hasNext()) { 41 | return null; 42 | } 43 | return data[index++]; 44 | }, 45 | hasNext: function() { 46 | return index < length; 47 | } 48 | } 49 | }()); 50 | } 51 | 52 | // Flatten all the documents and get all the fields to build a table with all fields 53 | var docs = []; 54 | var createFieldSet = fields == null || fields.length == 0; 55 | var fieldSet = fields ? [].concat(fields) : []; //new Set(fields); 56 | 57 | while (iterator.hasNext()) { 58 | var doc = iterator.next(); 59 | doc = flattenObject(doc, flattenArray); 60 | docs.push(doc); 61 | if (createFieldSet) { 62 | for (var i in doc) { 63 | if (doc.hasOwnProperty(i) && fieldSet.indexOf(i) === -1) { 64 | fieldSet.push(i); 65 | } 66 | } 67 | } 68 | } 69 | 70 | fields = fieldSet; 71 | 72 | var header = "%table "; 73 | fields.forEach(function (field) { header += field + "\t" }) 74 | print(header.substring(0, header.length - 1)); 75 | 76 | docs.forEach(function (doc) { 77 | var row = ""; 78 | fields.forEach(function (field) { row += doc[field] + "\t" }) 79 | print(row.substring(0, row.length - 1)); 80 | }); 81 | } 82 | 83 | DBQuery.prototype.table = function (fields, flattenArray) { 84 | if (this._limit > _ZEPPELIN_TABLE_LIMIT_) { 85 | this.limit(_ZEPPELIN_TABLE_LIMIT_); 86 | } 87 | printTable(this, fields, flattenArray); 88 | } 89 | 90 | DBCommandCursor.prototype.table = DBQuery.prototype.table; 91 | 92 | 93 | -------------------------------------------------------------------------------- /src/test/java/org/apache/zeppelin/mongodb/MongoDbInterpreterTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.zeppelin.mongodb; 18 | 19 | import static org.junit.Assert.assertTrue; 20 | 21 | import java.io.File; 22 | import java.io.IOException; 23 | import java.nio.ByteBuffer; 24 | import java.util.Properties; 25 | import java.util.Scanner; 26 | 27 | import org.apache.commons.io.FileUtils; 28 | import org.apache.zeppelin.interpreter.InterpreterContext; 29 | import org.apache.zeppelin.interpreter.InterpreterOutput; 30 | import org.apache.zeppelin.interpreter.InterpreterOutputListener; 31 | import org.apache.zeppelin.interpreter.InterpreterResult; 32 | import org.apache.zeppelin.interpreter.InterpreterResult.Code; 33 | import org.apache.zeppelin.interpreter.InterpreterResultMessageOutput; 34 | import org.junit.Before; 35 | import org.junit.BeforeClass; 36 | import org.junit.Test; 37 | 38 | /** 39 | * As there is no 'mongo' on the build platform, these tests simulates some basic behavior. 40 | * 41 | */ 42 | public class MongoDbInterpreterTest implements InterpreterOutputListener { 43 | 44 | private static final String SHELL_EXTENSION = 45 | new Scanner(MongoDbInterpreter.class.getResourceAsStream("/shell_extension.js"), "UTF-8") 46 | .useDelimiter("\\A").next(); 47 | 48 | private static final boolean IS_WINDOWS = System.getProperty("os.name") 49 | .startsWith("Windows"); 50 | 51 | private static final String MONGO_SHELL = System.getProperty("java.io.tmpdir") + 52 | File.separator + "mongo-test." + (IS_WINDOWS ? "bat" : "sh"); 53 | 54 | private final Properties props = new Properties(); 55 | private final MongoDbInterpreter interpreter = new MongoDbInterpreter(props); 56 | private final InterpreterOutput out = new InterpreterOutput(this); 57 | private final InterpreterContext context = InterpreterContext.builder() 58 | .setInterpreterOut(out).setNoteId("test").setNoteName("test").build(); 59 | 60 | private ByteBuffer buffer; 61 | 62 | @BeforeClass 63 | public static void setup() { 64 | // Create a fake 'mongo' 65 | final File mongoFile = new File(MONGO_SHELL); 66 | try { 67 | FileUtils.write(mongoFile, (IS_WINDOWS ? "@echo off\ntype \"%2%\"" : "cat \"$2\"")); 68 | FileUtils.forceDeleteOnExit(mongoFile); 69 | } 70 | catch (IOException e) { 71 | } 72 | } 73 | 74 | @Before 75 | public void init() { 76 | buffer = ByteBuffer.allocate(10000); 77 | props.put("mongo.shell.path", (IS_WINDOWS ? "" : "sh ") + MONGO_SHELL); 78 | props.put("mongo.shell.command.table.limit", "10000"); 79 | } 80 | 81 | @Test 82 | public void testSuccess() { 83 | final String userScript = "print('hello')"; 84 | 85 | final InterpreterResult res = interpreter.interpret(userScript, context); 86 | 87 | assertTrue("Check SUCCESS: " + res.message(), res.code() == Code.SUCCESS); 88 | 89 | try { 90 | out.flush(); 91 | } catch (IOException e) {} 92 | 93 | 94 | final String resultScript = new String(getBufferBytes()); 95 | 96 | final String expectedScript = SHELL_EXTENSION.replace( 97 | "__ZEPPELIN_TABLE_LIMIT__", interpreter.getProperty("mongo.shell.command.table.limit")) + 98 | userScript; 99 | 100 | // The script that is executed must contain the functions provided by this interpreter 101 | assertTrue("Check SCRIPT", resultScript.equals(expectedScript)); 102 | } 103 | 104 | @Test 105 | public void testBadConf() { 106 | props.setProperty("mongo.shell.path", "/bad/path/to/mongo"); 107 | final InterpreterResult res = interpreter.interpret("print('hello')", context); 108 | 109 | assertTrue(res.code() == Code.ERROR); 110 | } 111 | 112 | @Override 113 | public void onUpdateAll(InterpreterOutput interpreterOutput) { 114 | 115 | } 116 | 117 | @Override 118 | public void onAppend(int i, InterpreterResultMessageOutput interpreterResultMessageOutput, byte[] bytes) { 119 | buffer.put(bytes); 120 | } 121 | 122 | @Override 123 | public void onUpdate(int i, InterpreterResultMessageOutput interpreterResultMessageOutput) { 124 | 125 | } 126 | 127 | private byte[] getBufferBytes() { 128 | buffer.flip(); 129 | final byte[] bufferBytes = new byte[buffer.remaining()]; 130 | buffer.get(bufferBytes); 131 | return bufferBytes; 132 | } 133 | 134 | } 135 | --------------------------------------------------------------------------------