jongyoul commented on code in PR #4339:
URL: https://github.com/apache/zeppelin/pull/4339#discussion_r850101928


##########
zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/RunNotebookInterpreter.java:
##########
@@ -0,0 +1,294 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF 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.apache.zeppelin.interpreter;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.exception.ExceptionUtils;
+import org.apache.zeppelin.interpreter.remote.RemoteInterpreterProcessListener;
+import org.apache.zeppelin.notebook.Notebook;
+import org.apache.zeppelin.notebook.Paragraph;
+import org.apache.zeppelin.user.AuthenticationInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.*;
+
+
+public class RunNotebookInterpreter extends AbstractInterpreter {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(RunNotebookInterpreter.class);
+
+  private InterpreterGroup intpGroup;
+  private Notebook notebook;
+  private RemoteInterpreterProcessListener interpreterProcessListener;
+
+  public RunNotebookInterpreter(InterpreterSettingManager 
interpreterSettingManager) {
+    super(new Properties());
+    this.notebook = interpreterSettingManager.getNotebook();
+    this.interpreterProcessListener = 
interpreterSettingManager.getRemoteInterpreterProcessListener();
+
+    InterpreterInfo interpreterInfo = new InterpreterInfo(
+            RunNotebookInterpreter.class.getName(), "_run", false,
+            Maps.newHashMap(), Maps.newHashMap());
+    InterpreterSetting intpSetting = new InterpreterSetting.Builder()
+            .setGroup("__internal__")
+            .setId("__internal__run")
+            .setName("__internal__run")
+            .setIntepreterSettingManager(interpreterSettingManager)
+            .setInterpreterInfos(Lists.newArrayList(interpreterInfo))
+            .create();
+    this.intpGroup = new ManagedInterpreterGroup("_run", intpSetting);
+  }
+
+  @Override
+  public ZeppelinContext getZeppelinContext() {
+    return null;
+  }
+
+  @Override
+  protected InterpreterResult internalInterpret(String st, InterpreterContext 
context) throws InterpreterException {
+    String[] lines = st.trim().split("\n");
+    int outputIndex = 0;
+    List<InterpreterResultMessage> allResultMessages = new ArrayList<>();
+    String lastParagraphId = null;
+    try {
+      // create paragraph to the current note.
+      Paragraph lastParagraph = notebook.processNote(context.getNoteId(), note 
->
+              note.addNewParagraph(AuthenticationInfo.ANONYMOUS));
+      lastParagraphId = lastParagraph.getId();
+      for (String line : lines) {
+        String[] tokens = line.split("\\s");
+        if (tokens.length == 0) {
+          return new InterpreterResult(InterpreterResult.Code.ERROR,
+                  String.format("Invalid usage: %s, please use %run <note_id> 
<param_1> <param_2> ...", line));
+        }
+
+        String noteId = tokens[0];
+        if (context.getNoteId().equals(noteId)) {
+          return new InterpreterResult(InterpreterResult.Code.ERROR,
+                  "Run current note itself in %run is not allowed");
+        }
+
+        Map<String, String> params = 
parseParams(line.substring(noteId.length()).trim());
+
+        InterpreterResult result = runNote(context, lastParagraph, noteId, 
params, outputIndex);
+        outputIndex += result.message().size();
+        allResultMessages.addAll(result.message());
+        if (result.code != InterpreterResult.Code.SUCCESS) {
+          return new InterpreterResult(result.code, allResultMessages);
+        }
+      }
+      return new InterpreterResult(InterpreterResult.Code.SUCCESS, 
allResultMessages);
+    } catch (InvalidParameterFormatException e) {
+      return new InterpreterResult(InterpreterResult.Code.ERROR, 
e.getMessage());
+    } catch (IOException e) {
+      return new InterpreterResult(InterpreterResult.Code.ERROR, 
ExceptionUtils.getStackTrace(e));
+    } finally {
+      if (lastParagraphId != null) {
+        try {
+          String finalLastParagraphId = lastParagraphId;
+          notebook.processNote(context.getNoteId(), note -> {
+            note.removeParagraph("anonymous", finalLastParagraphId);
+            return null;
+          });
+        } catch (IOException e) {
+          LOGGER.error(String.format("Fail to remove paragraph: %s", 
lastParagraphId), e);
+        }
+      }
+    }
+  }
+
+  private InterpreterResult runNote(InterpreterContext context,
+                                    Paragraph lastParagraph,
+                                    String noteId,
+                                    Map<String, String> params,
+                                    int outputStartIndex) {
+    List<InterpreterResultMessage> allResultMessages = new ArrayList<>();
+    try {
+      // copy execution note
+      boolean isSuccess = notebook.processNote(noteId, note -> {
+        if (note == null) {
+          allResultMessages.add(new 
InterpreterResultMessage(InterpreterResult.Type.TEXT,
+                  String.format("Note `%s` doesn't exist", noteId)));
+          return false;
+        }
+        int outputIndex = outputStartIndex;
+        for (Paragraph p : note.getParagraphs()) {
+          if (StringUtils.isBlank(p.getScriptText())) {
+            // skip empty paragraph
+            continue;
+          }
+          lastParagraph.setTitle(p.getTitle());
+          lastParagraph.setText(p.getText());
+          lastParagraph.setConfig(p.getConfig());
+          lastParagraph.settings.setParams(new 
HashMap<>(p.settings.getParams()));
+          lastParagraph.settings.getParams().putAll(params);
+          lastParagraph.settings.setForms(new 
HashMap<>(p.settings.getForms()));
+          lastParagraph.run();
+          InterpreterResult result = lastParagraph.getReturn();
+          for (InterpreterResultMessage resultMessage : result.message()) {
+            interpreterProcessListener.onOutputUpdated(context.getNoteId(), 
context.getParagraphId(), outputIndex ++,
+                    resultMessage.getType(), resultMessage.getData());
+            allResultMessages.add(resultMessage);
+          }
+          if (result.code != InterpreterResult.Code.SUCCESS) {
+            return false;
+          }
+        }
+        return true;
+      });
+
+      if (isSuccess) {
+        return new InterpreterResult(InterpreterResult.Code.SUCCESS, 
allResultMessages);
+      } else {
+        return new InterpreterResult(InterpreterResult.Code.ERROR, 
allResultMessages);
+      }
+    } catch (IOException e) {
+      return new InterpreterResult(InterpreterResult.Code.ERROR, 
ExceptionUtils.getStackTrace(e));
+    }
+  }
+
+  @VisibleForTesting
+  public static Map<String, String> parseParams(String text) throws 
InvalidParameterFormatException {

Review Comment:
   Just curious. Why don't we use regex to handle it? It also handle some 
exceptional cases but I wonder if we need to handle that case or not.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscr...@zeppelin.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to