/
Note.java
1252 lines (1100 loc) · 37.3 KB
/
Note.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.notebook;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.zeppelin.common.JsonSerializable;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.display.AngularObject;
import org.apache.zeppelin.display.AngularObjectRegistry;
import org.apache.zeppelin.display.Input;
import org.apache.zeppelin.interpreter.ExecutionContext;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterFactory;
import org.apache.zeppelin.interpreter.InterpreterGroup;
import org.apache.zeppelin.interpreter.InterpreterNotFoundException;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterSetting;
import org.apache.zeppelin.interpreter.InterpreterSettingManager;
import org.apache.zeppelin.interpreter.ManagedInterpreterGroup;
import org.apache.zeppelin.interpreter.remote.RemoteAngularObject;
import org.apache.zeppelin.interpreter.remote.RemoteAngularObjectRegistry;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.notebook.utility.IdHashes;
import org.apache.zeppelin.scheduler.ExecutorFactory;
import org.apache.zeppelin.scheduler.Job.Status;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.apache.zeppelin.user.Credentials;
import org.apache.zeppelin.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Represent the note of Zeppelin. All the note and its paragraph operations are done
* via this class.
*/
public class Note implements JsonSerializable {
private static final Logger LOGGER = LoggerFactory.getLogger(Note.class);
// serialize Paragraph#runtimeInfos and Note#path to frontend but not to note file
private static final ExclusionStrategy NOTE_GSON_EXCLUSION_STRATEGY =
new NoteJsonExclusionStrategy(ZeppelinConfiguration.create());
private static class NoteJsonExclusionStrategy implements ExclusionStrategy {
private Set<String> noteExcludeFields = new HashSet<>();
private Set<String> paragraphExcludeFields = new HashSet<>();
public NoteJsonExclusionStrategy(ZeppelinConfiguration zConf) {
String[] excludeFields = zConf.getNoteFileExcludedFields();
for (String field : excludeFields) {
if (field.startsWith("Paragraph")) {
paragraphExcludeFields.add(field.substring(10));
} else {
noteExcludeFields.add(field);
}
}
}
@Override
public boolean shouldSkipField(FieldAttributes field) {
if(field.getName().equals("path")) {
return true;
}
if (field.getDeclaringClass().equals(Paragraph.class)) {
return paragraphExcludeFields.contains(field.getName());
} else {
return noteExcludeFields.contains(field.getName());
}
}
@Override
public boolean shouldSkipClass(Class<?> aClass) {
return false;
}
}
private static final Gson GSON = new GsonBuilder()
.setPrettyPrinting()
.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.registerTypeAdapter(Date.class, new NotebookImportDeserializer())
.registerTypeAdapterFactory(Input.TypeAdapterFactory)
.setExclusionStrategies(NOTE_GSON_EXCLUSION_STRATEGY)
.create();
private static final DateTimeFormatter DATE_TIME_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss");
private CopyOnWriteArrayList<Paragraph> paragraphs = new CopyOnWriteArrayList<>();
private String name = "";
private String id;
private String defaultInterpreterGroup;
private String version;
private Map<String, Object> noteParams = new LinkedHashMap<>();
private Map<String, Input> noteForms = new LinkedHashMap<>();
private Map<String, List<AngularObject>> angularObjects = new HashMap<>();
/*
* note configurations.
* - looknfeel - cron
*/
private Map<String, Object> config = new HashMap<>();
/*
* note information.
* - cron : cron expression validity.
*/
private Map<String, Object> info = new HashMap<>();
// The front end needs to judge TRASH_FOLDER according to the path,
// But it doesn't need to be saved in note json. So we will exclude this when saving
// note to NotebookRepo.
private String path;
/********************************** transient fields ******************************************/
private transient boolean loaded = false;
private transient boolean saved = false;
private transient boolean removed = false;
private transient InterpreterFactory interpreterFactory;
private transient InterpreterSettingManager interpreterSettingManager;
private transient ParagraphJobListener paragraphJobListener;
private transient List<NoteEventListener> noteEventListeners = new ArrayList<>();
private transient Credentials credentials;
private transient ZeppelinConfiguration zConf = ZeppelinConfiguration.create();
public Note() {
generateId();
}
public Note(String path, String defaultInterpreterGroup, InterpreterFactory factory,
InterpreterSettingManager interpreterSettingManager, ParagraphJobListener paragraphJobListener,
Credentials credentials, List<NoteEventListener> noteEventListener) {
setPath(path);
this.defaultInterpreterGroup = defaultInterpreterGroup;
this.interpreterFactory = factory;
this.interpreterSettingManager = interpreterSettingManager;
this.paragraphJobListener = paragraphJobListener;
this.noteEventListeners = noteEventListener;
this.credentials = credentials;
this.version = Util.getVersion();
generateId();
setCronSupported(zConf);
}
public Note(NoteInfo noteInfo) {
this.id = noteInfo.getId();
setPath(noteInfo.getPath());
}
public String getPath() {
return path;
}
public String getParentPath() {
int pos = path.lastIndexOf('/');
if (pos == 0) {
return "/";
} else {
return path.substring(0, pos);
}
}
private String getName(String path) {
int pos = path.lastIndexOf('/');
return path.substring(pos + 1);
}
private void generateId() {
id = IdHashes.generateId();
}
public boolean isLoaded() {
return loaded;
}
public void setLoaded(boolean loaded) {
this.loaded = loaded;
}
/**
* Release note memory
*/
public void unLoad() {
if (isRunning() || isParagraphRunning()) {
LOGGER.warn("Unable to unload note because it is in RUNNING");
} else {
this.setLoaded(false);
this.paragraphs = null;
this.config = null;
this.info = null;
this.noteForms = null;
this.noteParams = null;
this.angularObjects = null;
}
}
public boolean isParagraphRunning() {
if (paragraphs != null) {
for (Paragraph p : paragraphs) {
if (p.isRunning()) {
return true;
}
}
}
return false;
}
public boolean isPersonalizedMode() {
Object v = getConfig().get("personalizedMode");
return null != v && "true".equals(v);
}
public void setPersonalizedMode(Boolean value) {
String valueString;
if (value.booleanValue()) {
valueString = "true";
} else {
valueString = "false";
}
config.put("personalizedMode", valueString);
clearUserParagraphs(value);
}
private void clearUserParagraphs(boolean isPersonalized) {
if (!isPersonalized) {
for (Paragraph p : paragraphs) {
p.clearUserParagraphs();
}
}
}
public String getId() {
return id;
}
@VisibleForTesting
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setPath(String path) {
if (!path.startsWith("/")) {
this.path = "/" + path;
} else {
this.path = path;
}
this.name = getName(path);
}
public void setVersion(String version) {
this.version = version;
}
public String getDefaultInterpreterGroup() {
if (StringUtils.isBlank(defaultInterpreterGroup)) {
defaultInterpreterGroup = ZeppelinConfiguration.create()
.getString(ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_GROUP_DEFAULT);
}
return defaultInterpreterGroup;
}
public void setDefaultInterpreterGroup(String defaultInterpreterGroup) {
this.defaultInterpreterGroup = defaultInterpreterGroup;
}
public Map<String, Object> getNoteParams() {
return noteParams;
}
public void setNoteParams(Map<String, Object> noteParams) {
this.noteParams = noteParams;
}
public Map<String, Input> getNoteForms() {
return noteForms;
}
public void setNoteForms(Map<String, Input> noteForms) {
this.noteForms = noteForms;
}
public void setName(String name) {
this.name = name;
// for the notes before 0.9, get path from name.
if (this.path == null) {
if (name.startsWith("/")) {
this.path = name;
} else {
this.path = "/" + name;
}
} else {
int pos = this.path.lastIndexOf('/');
this.path = this.path.substring(0, pos + 1) + this.name;
}
}
public InterpreterFactory getInterpreterFactory() {
return interpreterFactory;
}
public void setInterpreterFactory(InterpreterFactory interpreterFactory) {
this.interpreterFactory = interpreterFactory;
}
void setInterpreterSettingManager(InterpreterSettingManager interpreterSettingManager) {
this.interpreterSettingManager = interpreterSettingManager;
}
InterpreterSettingManager getInterpreterSettingManager() {
return this.interpreterSettingManager;
}
void setParagraphJobListener(ParagraphJobListener paragraphJobListener) {
this.paragraphJobListener = paragraphJobListener;
}
public boolean isCronSupported(ZeppelinConfiguration config) {
if (config.isZeppelinNotebookCronEnable()) {
config.getZeppelinNotebookCronFolders();
if (StringUtils.isBlank(config.getZeppelinNotebookCronFolders())) {
return true;
} else {
for (String folder : config.getZeppelinNotebookCronFolders().split(",")) {
if (this.path.startsWith(folder)) {
return true;
}
}
}
}
return false;
}
public void setCronSupported(ZeppelinConfiguration config) {
getConfig().put("isZeppelinNotebookCronEnable", isCronSupported(config));
}
public Credentials getCredentials() {
return credentials;
}
public void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
Map<String, List<AngularObject>> getAngularObjects() {
return angularObjects;
}
public List<AngularObject> getAngularObjects(String intpGroupId) {
if (!angularObjects.containsKey(intpGroupId)) {
return new ArrayList<>();
}
return angularObjects.get(intpGroupId);
}
/**
* Add or update the note AngularObject.
*/
public void addOrUpdateAngularObject(String intpGroupId, AngularObject angularObject) {
List<AngularObject> angularObjectList;
if (!angularObjects.containsKey(intpGroupId)) {
angularObjectList = new ArrayList<>();
angularObjects.put(intpGroupId, angularObjectList);
} else {
angularObjectList = angularObjects.get(intpGroupId);
// Delete existing AngularObject
Iterator<AngularObject> iter = angularObjectList.iterator();
while(iter.hasNext()){
String noteId = "";
String paragraphId = "";
String name = "";
Object object = iter.next();
if (object instanceof AngularObject) {
AngularObject ao = (AngularObject)object;
noteId = ao.getNoteId();
paragraphId = ao.getParagraphId();
name = ao.getName();
} else if (object instanceof RemoteAngularObject) {
RemoteAngularObject rao = (RemoteAngularObject)object;
noteId = rao.getNoteId();
paragraphId = rao.getParagraphId();
name = rao.getName();
} else {
continue;
}
if (StringUtils.equals(noteId, angularObject.getNoteId())
&& StringUtils.equals(paragraphId, angularObject.getParagraphId())
&& StringUtils.equals(name, angularObject.getName())) {
iter.remove();
}
}
}
angularObjectList.add(angularObject);
}
/**
* Delete the note AngularObject.
*/
public void deleteAngularObject(String intpGroupId, String noteId, String paragraphId, String name) {
List<AngularObject> angularObjectList;
if (angularObjects.containsKey(intpGroupId)) {
angularObjectList = angularObjects.get(intpGroupId);
// Delete existing AngularObject
Iterator<AngularObject> iter = angularObjectList.iterator();
while(iter.hasNext()){
String noteIdCandidate = "";
String paragraphIdCandidate = "";
String nameCandidate = "";
Object object = iter.next();
if (object instanceof AngularObject) {
AngularObject ao = (AngularObject)object;
noteIdCandidate = ao.getNoteId();
paragraphIdCandidate = ao.getParagraphId();
nameCandidate = ao.getName();
} else if (object instanceof RemoteAngularObject) {
RemoteAngularObject rao = (RemoteAngularObject) object;
noteIdCandidate = rao.getNoteId();
paragraphIdCandidate = rao.getParagraphId();
nameCandidate = rao.getName();
} else {
continue;
}
if (StringUtils.equals(noteId, noteIdCandidate)
&& StringUtils.equals(paragraphId, paragraphIdCandidate)
&& StringUtils.equals(name, nameCandidate)) {
iter.remove();
}
}
}
}
/**
* Create a new paragraph and add it to the end of the note.
*/
public Paragraph addNewParagraph(AuthenticationInfo authenticationInfo) {
return insertNewParagraph(paragraphs.size(), authenticationInfo);
}
/**
* Clone paragraph and add it to note.
*
* @param srcParagraph source paragraph
*/
void addCloneParagraph(Paragraph srcParagraph, AuthenticationInfo subject) {
// Keep paragraph original ID
Paragraph newParagraph = new Paragraph(srcParagraph.getId(), this, paragraphJobListener);
Map<String, Object> config = new HashMap<>(srcParagraph.getConfig());
Map<String, Object> param = srcParagraph.settings.getParams();
Map<String, Input> form = srcParagraph.settings.getForms();
LOGGER.debug("srcParagraph user: {}", srcParagraph.getUser());
newParagraph.setAuthenticationInfo(subject);
newParagraph.setConfig(config);
newParagraph.settings.setParams(param);
newParagraph.settings.setForms(form);
newParagraph.setText(srcParagraph.getText());
newParagraph.setTitle(srcParagraph.getTitle());
LOGGER.debug("newParagraph user: {}", newParagraph.getUser());
try {
String resultJson = GSON.toJson(srcParagraph.getReturn());
InterpreterResult result = InterpreterResult.fromJson(resultJson);
newParagraph.setReturn(result, null);
} catch (Exception e) {
// 'result' part of Note consists of exception, instead of actual interpreter results
LOGGER.warn("Paragraph {} has a result with exception. {}", srcParagraph.getId(), e.getMessage());
}
paragraphs.add(newParagraph);
try {
fireParagraphCreateEvent(newParagraph);
} catch (IOException e) {
e.printStackTrace();
}
}
public void fireParagraphCreateEvent(Paragraph p) throws IOException {
for (NoteEventListener listener : noteEventListeners) {
listener.onParagraphCreate(p);
}
}
public void fireParagraphRemoveEvent(Paragraph p) throws IOException {
for (NoteEventListener listener : noteEventListeners) {
listener.onParagraphRemove(p);
}
}
public void fireParagraphUpdateEvent(Paragraph p) throws IOException {
for (NoteEventListener listener : noteEventListeners) {
listener.onParagraphUpdate(p);
}
}
/**
* Create a new paragraph and insert it to the note in given index.
*
* @param index index of paragraphs
*/
public Paragraph insertNewParagraph(int index, AuthenticationInfo authenticationInfo) {
Paragraph paragraph = new Paragraph(this, paragraphJobListener);
if (null != interpreterSettingManager) {
// Set the default parameter configuration for the paragraph
// based on `interpreter-setting.json` config
Map<String, Object> config =
interpreterSettingManager.getConfigSetting(defaultInterpreterGroup);
paragraph.setConfig(config);
}
paragraph.setAuthenticationInfo(authenticationInfo);
setParagraphMagic(paragraph, index);
insertParagraph(paragraph, index);
return paragraph;
}
public void addParagraph(Paragraph paragraph) {
insertParagraph(paragraph, paragraphs.size());
}
private void insertParagraph(Paragraph paragraph, int index) {
paragraphs.add(index, paragraph);
try {
fireParagraphCreateEvent(paragraph);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Remove paragraph by id.
*
* @param paragraphId ID of paragraph
* @return a paragraph that was deleted, or <code>null</code> otherwise
*/
public Paragraph removeParagraph(String user, String paragraphId) {
removeAllAngularObjectInParagraph(user, paragraphId);
interpreterSettingManager.removeResourcesBelongsToParagraph(getId(), paragraphId);
for (Paragraph p : paragraphs) {
if (p.getId().equals(paragraphId)) {
paragraphs.remove(p);
try {
fireParagraphRemoveEvent(p);
} catch (IOException e) {
LOGGER.error("Fail to fire ParagraphRemoveEvent", e);
}
return p;
}
}
return null;
}
public void clearParagraphOutputFields(Paragraph p) {
p.setReturn(null, null);
p.cleanRuntimeInfos();
p.cleanOutputBuffer();
}
public Paragraph clearPersonalizedParagraphOutput(String paragraphId, String user) {
for (Paragraph p : paragraphs) {
if (!p.getId().equals(paragraphId)) {
continue;
}
p = p.getUserParagraphMap().get(user);
clearParagraphOutputFields(p);
return p;
}
return null;
}
/**
* Clear paragraph output by id.
*
* @param paragraphId ID of paragraph
* @return Paragraph
*/
public Paragraph clearParagraphOutput(String paragraphId) {
for (Paragraph p : paragraphs) {
if (!p.getId().equals(paragraphId)) {
continue;
}
clearParagraphOutputFields(p);
return p;
}
return null;
}
/**
* Clear all paragraph output of note
*/
public void clearAllParagraphOutput() {
for (Paragraph p : paragraphs) {
p.setReturn(null, null);
}
}
/**
* Move paragraph into the new index (order from 0 ~ n-1).
*
* @param paragraphId ID of paragraph
* @param index new index
*/
public void moveParagraph(String paragraphId, int index) {
moveParagraph(paragraphId, index, false);
}
/**
* Move paragraph into the new index (order from 0 ~ n-1).
*
* @param paragraphId ID of paragraph
* @param index new index
* @param throwWhenIndexIsOutOfBound whether throw IndexOutOfBoundException
* when index is out of bound
*/
public void moveParagraph(String paragraphId, int index, boolean throwWhenIndexIsOutOfBound) {
int oldIndex;
Paragraph p = null;
if (index < 0 || index >= paragraphs.size()) {
if (throwWhenIndexIsOutOfBound) {
throw new IndexOutOfBoundsException(
"paragraph size is " + paragraphs.size() + " , index is " + index);
} else {
return;
}
}
for (int i = 0; i < paragraphs.size(); i++) {
if (paragraphs.get(i).getId().equals(paragraphId)) {
oldIndex = i;
if (oldIndex == index) {
return;
}
p = paragraphs.remove(i);
}
}
if (p != null) {
paragraphs.add(index, p);
}
}
public boolean isLastParagraph(String paragraphId) {
if (!paragraphs.isEmpty()) {
if (paragraphId.equals(paragraphs.get(paragraphs.size() - 1).getId())) {
return true;
}
return false;
}
/** because empty list, cannot remove nothing right? */
return true;
}
public int getParagraphCount() {
return paragraphs.size();
}
public Paragraph getParagraph(String paragraphId) {
for (Paragraph p : paragraphs) {
if (p.getId().equals(paragraphId)) {
return p;
}
}
return null;
}
public Paragraph getParagraph(int index) {
return paragraphs.get(index);
}
public Paragraph getLastParagraph() {
return paragraphs.get(paragraphs.size() - 1);
}
private void setParagraphMagic(Paragraph p, int index) {
if (!paragraphs.isEmpty()) {
String replName;
if (index == 0) {
replName = paragraphs.get(0).getIntpText();
} else {
replName = paragraphs.get(index - 1).getIntpText();
}
if (p.isValidInterpreter(replName) && StringUtils.isNotEmpty(replName)) {
p.setText("%" + replName + "\n");
}
}
}
/**
* Run all the paragraphs of this note in different kinds of ways:
* - blocking/non-blocking
* - isolated/non-isolated
*
* @param authInfo
* @param blocking
* @param isolated
* @throws Exception
*/
public void runAll(AuthenticationInfo authInfo,
boolean blocking,
boolean isolated,
Map<String, Object> params) throws Exception {
if (isRunning()) {
throw new Exception("Unable to run note:" + id + " because it is still in RUNNING state.");
}
setIsolatedMode(isolated);
setRunning(true);
setStartTime(DATE_TIME_FORMATTER.format(LocalDateTime.now()));
if (blocking) {
try {
runAllSync(authInfo, isolated, params);
} finally {
setRunning(false);
setIsolatedMode(false);
clearStartTime();
}
} else {
ExecutorFactory.singleton().getNoteJobExecutor().submit(() -> {
try {
runAllSync(authInfo, isolated, params);
} catch (Exception e) {
LOGGER.warn("Fail to run note: {}", id, e);
} finally {
setRunning(false);
setIsolatedMode(false);
clearStartTime();
}
});
}
}
/**
* Run all the paragraphs in sync(blocking) way.
*
* @param authInfo
* @param isolated
*/
private void runAllSync(AuthenticationInfo authInfo, boolean isolated, Map<String, Object> params) throws Exception {
try {
for (Paragraph p : getParagraphs()) {
if (!p.isEnabled()) {
continue;
}
p.setAuthenticationInfo(authInfo);
Map<String, Object> originalParams = p.settings.getParams();
try {
if (params != null && !params.isEmpty()) {
p.settings.setParams(params);
}
Interpreter interpreter = p.getBindedInterpreter();
if (interpreter != null) {
// set interpreter property to execution.mode to be note
// so that it could use the correct scheduler. see ZEPPELIN-4832
interpreter.setProperty(".execution.mode", "note");
interpreter.setProperty(".noteId", id);
}
// Must run each paragraph in blocking way.
if (!run(p.getId(), true)) {
LOGGER.warn("Skip running the remain notes because paragraph {} fails", p.getId());
return;
}
} catch (InterpreterNotFoundException e) {
// ignore, because the following run method will fail if interpreter not found.
} finally {
// reset params to the original value
p.settings.setParams(originalParams);
}
}
} catch (Exception e) {
throw e;
} finally {
if (isolated) {
LOGGER.info("Releasing interpreters used by this note: {}", id);
for (InterpreterSetting setting : getUsedInterpreterSettings()) {
setting.closeInterpreters(getExecutionContext());
for (Paragraph p : paragraphs) {
p.setInterpreter(null);
}
}
}
}
}
/**
* Run a single paragraph in non-blocking way.
*
* @param paragraphId
* @return
*/
public boolean run(String paragraphId) {
return run(paragraphId, false);
}
/**
* Run a single paragraph.
*
* @param paragraphId ID of paragraph
* @param blocking Whether run this paragraph in blocking way
*/
public boolean run(String paragraphId, boolean blocking) {
return run(paragraphId, null, blocking, null);
}
/**
* Run a single paragraph. Return true only when paragraph run successfully.
*
* @param paragraphId
* @param blocking
* @param ctxUser
* @return
*/
public boolean run(String paragraphId,
String interpreterGroupId,
boolean blocking,
String ctxUser) {
Paragraph p = getParagraph(paragraphId);
if (isPersonalizedMode() && ctxUser != null)
p = p.getUserParagraph(ctxUser);
p.setListener(this.paragraphJobListener);
return p.execute(interpreterGroupId, blocking);
}
/**
* Return true if there is a running or pending paragraph
*/
public boolean haveRunningOrPendingParagraphs() {
for (Paragraph p : paragraphs) {
Status status = p.getStatus();
if (status.isRunning() || status.isPending()) {
return true;
}
}
return false;
}
public boolean isTrash() {
return this.path.startsWith("/" + NoteManager.TRASH_FOLDER);
}
public List<InterpreterCompletion> completion(String paragraphId,
String buffer,
int cursor,
AuthenticationInfo authInfo) {
Paragraph p = getParagraph(paragraphId);
p.setListener(this.paragraphJobListener);
p.setAuthenticationInfo(authInfo);
return p.completion(buffer, cursor);
}
public CopyOnWriteArrayList<Paragraph> getParagraphs() {
return this.paragraphs;
}
// TODO(zjffdu) how does this used ?
private void snapshotAngularObjectRegistry(String user) {
angularObjects = new HashMap<>();
List<InterpreterSetting> settings = getBindedInterpreterSettings(Lists.newArrayList(user));
if (settings == null || settings.size() == 0) {
return;
}
for (InterpreterSetting setting : settings) {
InterpreterGroup intpGroup = setting.getInterpreterGroup(getExecutionContext());
if (intpGroup != null) {
AngularObjectRegistry registry = intpGroup.getAngularObjectRegistry();
angularObjects.put(intpGroup.getId(), registry.getAllWithGlobal(id));
}
}
}
private void removeAllAngularObjectInParagraph(String user, String paragraphId) {
angularObjects = new HashMap<>();
List<InterpreterSetting> settings = getBindedInterpreterSettings(Lists.newArrayList(user));
if (settings == null || settings.isEmpty()) {
return;
}
for (InterpreterSetting setting : settings) {
if (setting.getInterpreterGroup(getExecutionContext()) == null) {
continue;
}
InterpreterGroup intpGroup = setting.getInterpreterGroup(getExecutionContext());
AngularObjectRegistry registry = intpGroup.getAngularObjectRegistry();
if (registry instanceof RemoteAngularObjectRegistry) {
// remove paragraph scope object
((RemoteAngularObjectRegistry) registry).removeAllAndNotifyRemoteProcess(id, paragraphId);
// remove app scope object
List<ApplicationState> appStates = getParagraph(paragraphId).getAllApplicationStates();
if (appStates != null) {
for (ApplicationState app : appStates) {
((RemoteAngularObjectRegistry) registry)
.removeAllAndNotifyRemoteProcess(id, app.getId());
}
}
} else {
registry.removeAll(id, paragraphId);
// remove app scope object
List<ApplicationState> appStates = getParagraph(paragraphId).getAllApplicationStates();
if (appStates != null) {
for (ApplicationState app : appStates) {
registry.removeAll(id, app.getId());
}
}
}
}
}
public List<InterpreterSetting> getBindedInterpreterSettings(List<String> userAndRoles) {
// use LinkedHashSet because order matters, the first one represent the default interpreter setting.
Set<InterpreterSetting> settings = new LinkedHashSet<>();
// add the default interpreter group
InterpreterSetting defaultIntpSetting =
interpreterSettingManager.getByName(getDefaultInterpreterGroup());
if (defaultIntpSetting != null) {
settings.add(defaultIntpSetting);
}
// add the interpreter setting with the same group of default interpreter group
if (defaultIntpSetting != null) {
for (InterpreterSetting intpSetting : interpreterSettingManager.get()) {
if (intpSetting.getGroup().equals(defaultIntpSetting.getGroup())) {
if (intpSetting.isUserAuthorized(userAndRoles)) {
settings.add(intpSetting);
}
}
}
}
// add interpreter group used by each paragraph
for (Paragraph p : getParagraphs()) {
try {
Interpreter intp = p.getBindedInterpreter();
InterpreterSetting interpreterSetting = (
(ManagedInterpreterGroup) intp.getInterpreterGroup()).getInterpreterSetting();
if (interpreterSetting.isUserAuthorized(userAndRoles)) {
settings.add(interpreterSetting);
}
} catch (InterpreterNotFoundException e) {
// ignore this
}
}
return new ArrayList<>(settings);
}