-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathNameServer.java
More file actions
1637 lines (1505 loc) · 62.9 KB
/
Copy pathNameServer.java
File metadata and controls
1637 lines (1505 loc) · 62.9 KB
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
/*******************************************************************************
* Copyright 2015 Defense Health Agency (DHA)
*
* If your use of this software does not include any GPLv2 components:
* 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.
* ----------------------------------------------------------------------------
* If your use of this software includes any GPLv2 components:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*******************************************************************************/
package prerna.semoss.web.services.local;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import com.github.f4b6a3.uuid.alt.GUID;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.google.gson.ToNumberPolicy;
import com.google.gson.internal.LinkedTreeMap;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.StreamingOutput;
import prerna.auth.User;
import prerna.auth.utils.SecurityEngineUtils;
import prerna.auth.utils.SecurityInsightUtils;
import prerna.auth.utils.SecurityQueryUtils;
import prerna.engine.api.IDatabaseEngine;
import prerna.om.Insight;
import prerna.om.InsightStore;
import prerna.om.ThreadStore;
import prerna.reactor.IReactor;
import prerna.reactor.ReactorFactory;
import prerna.reactor.agent.mcp.MCPErrorCode;
import prerna.reactor.agent.mcp.MCPUtility;
import prerna.reactor.agent.run.AgentRunService;
import prerna.reactor.agent.stream.AgentRunStreamService;
import prerna.sablecc2.PixelRunner;
import prerna.sablecc2.PixelStreamUtility;
import prerna.sablecc2.PixelUtility;
import prerna.sablecc2.comm.PixelJobManager;
import prerna.sablecc2.comm.PixelJobRunner;
import prerna.sablecc2.comm.PixelJobStatus;
import prerna.sablecc2.om.execptions.SemossMCPException;
import prerna.semoss.web.services.remote.CentralNameServer;
import prerna.util.ChromeDriverUtility;
import prerna.util.Constants;
import prerna.util.PlaySheetRDFMapBasedEnum;
import prerna.util.Utility;
import prerna.util.gson.GsonUtility;
import prerna.web.services.util.WebUtility;
@Path("/engine")
@PermitAll
public class NameServer {
private static final Logger classLogger = LogManager.getLogger(NameServer.class);
private static final String ERROR_TYPE = "errorType";
private static final String INSIGHT_NOT_FOUND = "INSIGHT_NOT_FOUND";
private static final String EXPRESSION_NOT_FOUND = "EXPRESSION_NOT_FOUND";
////////////////////////////////////////////////////////////////////////////////
@GET
@Path("playsheets")
@Produces("application/json")
public StreamingOutput getPlaySheets(@Context HttpServletRequest request) {
Map<String, String> hashTable = new HashMap<>();
List<String> sheetNames = PlaySheetRDFMapBasedEnum.getAllSheetNames();
sheetNames = WebUtility.inputSanitizer(sheetNames);
for (int i = 0; i < sheetNames.size(); i++) {
hashTable.put(sheetNames.get(i), PlaySheetRDFMapBasedEnum.getClassFromName(sheetNames.get(i)));
}
return WebUtility.getSO(hashTable);
}
@Path("i-{insightID}")
public Object getInsightDataFrame(@PathParam("insightID") String insightID,
@QueryParam("dataFrameType") String dataFrameType, @Context HttpServletRequest request) {
// eventually I want to pick this from session
// but for now let us pick it from the insight store
dataFrameType = WebUtility.inputSanitizer(dataFrameType);
insightID = WebUtility.inputSanitizer(insightID);
classLogger.debug("Processing pixel runner request for insight: {}", insightID);
Insight existingInsight = null;
if (insightID != null && !insightID.isEmpty() && !insightID.startsWith("new")) {
existingInsight = InsightStore.getInstance().get(insightID);
if (existingInsight == null) {
Map<String, String> errorHash = new HashMap<>();
errorHash.put(Constants.ERROR_MESSAGE, "Existing insight based on passed insightID is not found");
// return Response.status(400).entity(WebUtility.getSO(errorHash)).build();
return WebUtility.getResponse(errorHash, 400);
}
// else if(!existingInsight.hasInstantiatedDataMaker()) {
// synchronized(existingInsight) {
// if(!existingInsight.hasInstantiatedDataMaker()) {
//// IDataMaker dm = null;
//// // check if the insight is from a csv
//// if(!existingInsight.isDbInsight()) {
//// // it better end up being created here since it must be serialized as a
// tinker
//// InsightCache inCache =
// CacheFactory.getInsightCache(CacheFactory.CACHE_TYPE.CSV_CACHE);
//// dm = inCache.getDMCache(existingInsight);
//// DataMakerComponent dmc = new
// DataMakerComponent(inCache.getDMFilePath(existingInsight));
////
//// Vector<DataMakerComponent> dmcList = new Vector<DataMakerComponent>();
//// dmcList.add(dmc);
//// existingInsight.setDataMakerComponents(dmcList);
//// } else {
// // otherwise, grab the serialization if it is there
// IDataMaker dm =
// CacheFactory.getInsightCache(CacheFactory.CACHE_TYPE.DB_INSIGHT_CACHE).getDMCache(existingInsight);
//// }
//
// if(dm != null) {
// // this means the serialization was good and pushing it into the insight
// object
// existingInsight.setDataMaker(dm);
// } else {
//// this means the serialization has never occurred
//// could be because hasn't happened, or could be because it is not a tinker
// frame
// InsightCreateRunner run = new InsightCreateRunner(existingInsight);
// Map<String, Object> webData = run.runWeb();
// // try to serialize
// // this will do nothing if not a tinker frame
// CacheFactory.getInsightCache(CacheFactory.CACHE_TYPE.DB_INSIGHT_CACHE).cacheInsight(existingInsight,
// webData);
// }
// }
// }
// }
} else if (insightID == null || insightID.equals("new")) {
// get the data frame type and set it from the FE
if (dataFrameType == null) {
dataFrameType = "H2Frame";
}
// existingInsight = new Insight(null, dataFrameType, "Grid");
existingInsight = new Insight();
// set the user id into the insight
existingInsight.setUser(((User) request.getSession().getAttribute(Constants.SESSION_USER)));
InsightStore.getInstance().put(existingInsight);
}
// else if(insightID.equals("newDashboard")) {
// // get the data frame type and set it from the FE
//// existingInsight = new Insight(null, "Dashboard", "Dashboard");
// existingInsight = new Insight();
// // set the user id into the insight
// existingInsight.setUserId( ((User)
// request.getSession().getAttribute(Constants.SESSION_USER)).getId() );
// Dashboard dashboard = new Dashboard();
// existingInsight.setDataMaker(dashboard);
// String insightid = InsightStore.getInstance().put(existingInsight);
// dashboard.setInsightID(insightid);
// }
DataframeResource dfr = new DataframeResource();
dfr.insight = existingInsight;
return dfr;
}
@GET
@Path("/downloadFile")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFile(@QueryParam("insightId") String insightId, @QueryParam("fileKey") String fileKey) {
// for "security"
// require the person to have both the insight id
// and the file id
// in order to download the file
insightId = WebUtility.inputSanitizer(insightId);
fileKey = WebUtility.inputSQLSanitizer(fileKey);
Insight insight = InsightStore.getInstance().get(insightId);
if (insight == null) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Could not find the insight id");
return WebUtility.getResponse(errorMap, 400);
}
try {
String filePath = insight.getExportFileLocation(fileKey);
File exportFile = new File(WebUtility.normalizePath(filePath));
if (!exportFile.exists()) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Could not find the file for given file id");
return WebUtility.getResponse(errorMap, 400);
}
String exportName = FilenameUtils.getName(filePath);
return Response.status(200).entity(exportFile)
.header("Content-Disposition", "attachment; filename=\"" + exportName + "\"").build();
} catch (Exception e) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 400);
}
}
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////
@POST
@Path("/runPixel")
@Consumes({ "application/x-www-form-urlencoded", "application/json" })
@Produces("application/json;charset=utf-8")
public Response runPixelSync(@Context HttpServletRequest request) {
// I need to do a couple of things here
// I need to get the basic blocking queue as a singleton
// create a thread
// set the insight and pixels into the thread
// and then let it lose
// I need a couple of different statistics for this user and panel
// is user (initially I had he, but then diversity) listening for
// stdout, stderr or both
// what is the level of log the user wants and the panel wants
// other than that -
// there is a jobID status Hash - this can eventually be zookeeper
// Then there is a jobID to message if the user has turned on the stdout, then
// it has a stack of messages
// once the job is done, the stack is also cleared
HttpSession session = request.getSession(false);
String sessionId = null;
String routeId = null;
User user = null;
Insight insight = null;
boolean dropLogging = true;
if (session != null) {
sessionId = session.getId();
user = ((User) session.getAttribute(Constants.SESSION_USER));
}
// how did you even get past the no user in session filter?
if (user == null) {
if (session != null && (session.isNew() || request.isRequestedSessionIdValid())) {
session.invalidate();
}
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "User session is invalid");
return WebUtility.getResponse(errorMap, 401);
}
// add the route if this is server deployment
String routeCookieName = Utility.getDIHelperProperty(Constants.LOAD_BALANCER_COOKIE_NAME);
if (routeCookieName != null && !routeCookieName.isEmpty()) {
Cookie[] curCookies = request.getCookies();
if (curCookies != null) {
for (Cookie c : curCookies) {
classLogger.debug(">>>>> Request cookie {} with value {}", Utility.cleanLogString(c.getName()),
Utility.cleanLogString(c.getValue()));
if (c.getName().equals(routeCookieName)) {
routeId = WebUtility.inputSQLSanitizer(c.getValue());
ChromeDriverUtility.setRouteCookieValue(c.getValue());
}
}
}
}
// Extract parameters based on content type
String insightId = null;
String expression = null;
String strTz = null;
String logStr = null;
String contentType = request.getContentType();
if (contentType != null && contentType.toLowerCase().contains("application/json")) {
// Handle JSON content
try {
StringBuilder jsonBuffer = new StringBuilder();
String line;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
jsonBuffer.append(line);
}
String jsonString = jsonBuffer.toString();
Gson gson = new GsonBuilder().disableHtmlEscaping()
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE).create();
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
// Extract values from JSON object
insightId = jsonObject.has("insightId") && !jsonObject.get("insightId").isJsonNull()
? jsonObject.get("insightId").getAsString()
: null;
expression = jsonObject.has("expression") && !jsonObject.get("expression").isJsonNull()
? jsonObject.get("expression").getAsString()
: null;
strTz = jsonObject.has("tz") && !jsonObject.get("tz").isJsonNull() ? jsonObject.get("tz").getAsString()
: null;
logStr = jsonObject.has("dropLogging") && !jsonObject.get("dropLogging").isJsonNull()
? jsonObject.get("dropLogging").getAsString()
: null;
// Sanitize the extracted values
if (insightId != null) {
insightId = WebUtility.inputSanitizer(insightId);
}
if (strTz != null) {
strTz = WebUtility.inputSQLSanitizer(strTz);
}
if (logStr != null) {
logStr = WebUtility.inputSQLSanitizer(logStr);
}
} catch (IOException e) {
classLogger.error("Error reading JSON request body", e);
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Invalid JSON request body");
return WebUtility.getResponse(errorMap, 400);
} catch (JsonSyntaxException e) {
classLogger.error("Error parsing JSON request body", e);
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Invalid JSON syntax in request body");
return WebUtility.getResponse(errorMap, 400);
}
} else {
// Handle form-urlencoded content (original approach)
insightId = WebUtility.inputSanitizer(request.getParameter("insightId"));
expression = request.getParameter("expression");
strTz = WebUtility.inputSQLSanitizer(request.getParameter("tz"));
logStr = WebUtility.inputSQLSanitizer(request.getParameter("dropLogging"));
}
if (expression == null || (expression = expression.trim()).isEmpty()) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Must pass in 'expression' key containing the pixel to execute");
errorMap.put(ERROR_TYPE, EXPRESSION_NOT_FOUND);
return WebUtility.getResponse(errorMap, 400);
}
if (!expression.endsWith(";")) {
expression = expression + ";";
}
// figure out the type of insight
if (insightId == null || insightId.toString().isEmpty() || insightId.equals("undefined")
|| insightId.equals("new")) {
// need to make a new insight here
insight = new Insight();
insight.setBaseURL(WebUtility.getRefererURL(request));
InsightStore.getInstance().put(insight);
insightId = insight.getInsightId();
} else {
// or just get it from the store
// the session id needs to be checked
// you better have a valid id... or else... O_O
insight = InsightStore.getInstance().get(insightId);
if (insight == null) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Could not find the insight id");
errorMap.put(ERROR_TYPE, INSIGHT_NOT_FOUND);
classLogger.error("Insight not found for insightId: {}", insightId);
return WebUtility.getResponse(errorMap, 400);
}
}
InsightStore.getInstance().addToSessionHash(sessionId, insightId);
// set the user
insight.setUser(user);
// set the user timezone
ZoneId zoneId = null;
if (strTz == null || (strTz = strTz.trim()).isEmpty()) {
zoneId = ZoneId.of(Utility.getApplicationTimeZoneId());
} else {
try {
zoneId = ZoneId.of(strTz);
} catch (Exception e) {
classLogger.warn("Invalid timezone value '{}', falling back to application default", strTz, e);
zoneId = ZoneId.of(Utility.getApplicationTimeZoneId());
}
}
// need null check if security is off
if (user != null) {
user.setZoneId(zoneId);
}
// set if we are scheduler mode
Boolean schedulerMode = ThreadStore.isSchedulerMode();
if (schedulerMode != null) {
insight.setSchedulerMode(schedulerMode);
}
// are we running runPixel in runPixel on the same insight?
if (logStr != null) {
dropLogging = Boolean.parseBoolean(logStr);
}
return runPixelJob(user, insight, expression, insightId, sessionId, routeId, dropLogging);
}
/**
* Convenience wrapper around {@link #runPixelSync(HttpServletRequest)} that
* accepts raw Python source in a {@code code} field and dispatches it as the
* pixel expression {@code Py(code="...")}. Saves callers from having to
* handcraft pixel syntax (and from escaping quotes/backslashes/newlines) just
* to run a snippet of Python.
* <p>
* Body fields (JSON or form-urlencoded):
* <ul>
* <li>{@code code} (required) - the Python source to execute</li>
* <li>{@code insightId} (optional) - existing insight to run within; a new
* transient insight is created if missing/{@code "new"}</li>
* <li>{@code tz} (optional) - IANA timezone for the user</li>
* <li>{@code dropLogging} (optional) - same as
* {@link #runPixelSync(HttpServletRequest)}</li>
* </ul>
* The Python code is passed through {@link Gson#toJson(Object)} so any embedded
* quotes, backslashes, and newlines are safely escaped into the pixel
* expression.
*/
@POST
@Path("/runPython")
@Consumes({ "application/x-www-form-urlencoded", "application/json" })
@Produces("application/json;charset=utf-8")
public Response runPython(@Context HttpServletRequest request) {
HttpSession session = request.getSession(false);
String sessionId = null;
String routeId = null;
User user = null;
Insight insight = null;
boolean dropLogging = true;
if (session != null) {
sessionId = session.getId();
user = ((User) session.getAttribute(Constants.SESSION_USER));
}
// how did you even get past the no user in session filter?
if (user == null) {
if (session != null && (session.isNew() || request.isRequestedSessionIdValid())) {
session.invalidate();
}
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "User session is invalid");
return WebUtility.getResponse(errorMap, 401);
}
// add the route if this is server deployment
String routeCookieName = Utility.getDIHelperProperty(Constants.LOAD_BALANCER_COOKIE_NAME);
if (routeCookieName != null && !routeCookieName.isEmpty()) {
Cookie[] curCookies = request.getCookies();
if (curCookies != null) {
for (Cookie c : curCookies) {
classLogger.debug(">>>>> Request cookie {} with value {}", Utility.cleanLogString(c.getName()),
Utility.cleanLogString(c.getValue()));
if (c.getName().equals(routeCookieName)) {
routeId = WebUtility.inputSQLSanitizer(c.getValue());
ChromeDriverUtility.setRouteCookieValue(c.getValue());
}
}
}
}
// Extract parameters based on content type
String insightId = null;
String code = null;
String strTz = null;
String logStr = null;
String contentType = request.getContentType();
if (contentType != null && contentType.toLowerCase().contains("application/json")) {
try {
StringBuilder jsonBuffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
jsonBuffer.append(line);
}
Gson gson = new GsonBuilder().disableHtmlEscaping()
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE).create();
JsonObject jsonObject = gson.fromJson(jsonBuffer.toString(), JsonObject.class);
insightId = jsonObject.has("insightId") && !jsonObject.get("insightId").isJsonNull()
? jsonObject.get("insightId").getAsString()
: null;
code = jsonObject.has("code") && !jsonObject.get("code").isJsonNull()
? jsonObject.get("code").getAsString()
: null;
strTz = jsonObject.has("tz") && !jsonObject.get("tz").isJsonNull() ? jsonObject.get("tz").getAsString()
: null;
logStr = jsonObject.has("dropLogging") && !jsonObject.get("dropLogging").isJsonNull()
? jsonObject.get("dropLogging").getAsString()
: null;
if (insightId != null) {
insightId = WebUtility.inputSanitizer(insightId);
}
if (strTz != null) {
strTz = WebUtility.inputSQLSanitizer(strTz);
}
if (logStr != null) {
logStr = WebUtility.inputSQLSanitizer(logStr);
}
} catch (IOException e) {
classLogger.error("Error reading JSON request body for /runPython", e);
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Invalid JSON request body");
return WebUtility.getResponse(errorMap, 400);
} catch (JsonSyntaxException e) {
classLogger.error("Error parsing JSON request body for /runPython", e);
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Invalid JSON syntax in request body");
return WebUtility.getResponse(errorMap, 400);
}
} else {
insightId = WebUtility.inputSanitizer(request.getParameter("insightId"));
code = request.getParameter("code");
strTz = WebUtility.inputSQLSanitizer(request.getParameter("tz"));
logStr = WebUtility.inputSQLSanitizer(request.getParameter("dropLogging"));
}
if (code == null || code.trim().isEmpty()) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Must pass in 'code' containing the python code to execute");
errorMap.put(ERROR_TYPE, EXPRESSION_NOT_FOUND);
return WebUtility.getResponse(errorMap, 400);
}
// Wrap the python source as the pixel expression Py(code="...");
// Gson handles escaping for embedded quotes, backslashes, and newlines.
Gson pixelGson = new GsonBuilder().disableHtmlEscaping().create();
String expression = "Py(code=" + pixelGson.toJson(code) + ");";
// figure out the type of insight - reuse if existing, otherwise transient
if (insightId == null || insightId.isEmpty() || insightId.equals("undefined") || insightId.equals("new")) {
insight = new Insight();
insight.setBaseURL(WebUtility.getRefererURL(request));
InsightStore.getInstance().put(insight);
insightId = insight.getInsightId();
} else {
insight = InsightStore.getInstance().get(insightId);
if (insight == null) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Could not find the insight id");
errorMap.put(ERROR_TYPE, INSIGHT_NOT_FOUND);
classLogger.error("Insight not found for insightId: {}", insightId);
return WebUtility.getResponse(errorMap, 400);
}
}
InsightStore.getInstance().addToSessionHash(sessionId, insightId);
insight.setUser(user);
// set the user timezone
ZoneId zoneId = null;
if (strTz == null || (strTz = strTz.trim()).isEmpty()) {
zoneId = ZoneId.of(Utility.getApplicationTimeZoneId());
} else {
try {
zoneId = ZoneId.of(strTz);
} catch (Exception e) {
classLogger.warn("Invalid timezone value '{}', falling back to application default", strTz, e);
zoneId = ZoneId.of(Utility.getApplicationTimeZoneId());
}
}
if (user != null) {
user.setZoneId(zoneId);
}
// set if we are scheduler mode
Boolean schedulerMode = ThreadStore.isSchedulerMode();
if (schedulerMode != null) {
insight.setSchedulerMode(schedulerMode);
}
if (logStr != null) {
dropLogging = Boolean.parseBoolean(logStr);
}
return runPixelJob(user, insight, expression, insightId, sessionId, routeId, dropLogging);
}
@POST
@Path("/runReactorMCP")
@Consumes({ "application/json" })
@Produces("application/json;charset=utf-8")
public Response runReactorMCP(@Context HttpServletRequest request) {
/*
* Simpler way of running pixel reactor { "jsonrpc": "2.0", "id":
* "unique-request-id", "method": "tools/call", "params": { "name":
* "reactorName", "arguments": { "param1": "value1", "param2": "value2" } },
* "_meta":{ "insightId":"insightId", "tz":"timezone",
* "dropLogging":"dropLogging", "contextProjectId":"projectId" } }
*/
JSONObject response = new JSONObject();
JSONObject root = null;
HttpSession session = request.getSession(false);
String sessionId = null;
String routeId = null;
User user = null;
Insight insight = null;
if (session != null) {
sessionId = session.getId();
user = ((User) session.getAttribute(Constants.SESSION_USER));
}
// how did you even get past the no user in session filter?
if (user == null) {
if (session != null && (session.isNew() || request.isRequestedSessionIdValid())) {
session.invalidate();
}
response.put("id", "null");
response.put("jsonrpc", "2.0");
JSONObject error = new JSONObject();
error.put("code", MCPErrorCode.RESOURCE_ACCESS_DENIED.getCode());
error.put("message", "User session is invalid or expired");
response.put("error", error);
return Response.status(401).entity(response.toString())
.header("Cache-Control",
"no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0")
.header("Pragma", "no-cache").build();
}
// add the route if this is server deployment
String routeCookieName = Utility.getDIHelperProperty(Constants.LOAD_BALANCER_COOKIE_NAME);
if (routeCookieName != null && !routeCookieName.isEmpty()) {
Cookie[] curCookies = request.getCookies();
if (curCookies != null) {
for (Cookie c : curCookies) {
classLogger.debug(">>>>> Request cookie {} with value {}", Utility.cleanLogString(c.getName()),
Utility.cleanLogString(c.getValue()));
if (c.getName().equals(routeCookieName)) {
routeId = WebUtility.inputSQLSanitizer(c.getValue());
ChromeDriverUtility.setRouteCookieValue(c.getValue());
}
}
}
}
// Extract parameters from meta
String insightId = null;
String strTz = null;
try {
// Handle JSON content
StringBuilder jsonBuffer = new StringBuilder();
String line;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
jsonBuffer.append(line);
}
root = new JSONObject(jsonBuffer.toString());
} catch (IOException | org.json.JSONException e) {
classLogger.error("Failed to parse MCP request JSON", e);
/*
* { "jsonrpc": "2.0", "id": null, "error": { "code": -32700, "message":
* "Parse error - Invalid JSON was received by the server" } }
*/
response.put("id", "null");
response.put("jsonrpc", "2.0");
JSONObject error = new JSONObject();
error.put("code", MCPErrorCode.PARSE_ERROR.getCode());
error.put("message", MCPErrorCode.PARSE_ERROR.getDescription());
response.put("error", error);
return Response.status(400).entity(response.toString())
.header("Cache-Control",
"no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0")
.header("Pragma", "no-cache").build();
}
JSONObject meta = null;
if (root.has("_meta")) {
meta = root.getJSONObject("_meta");
}
// Sanitize the extracted values
if (meta != null && meta.has("insightId")) {
insightId = WebUtility.inputSanitizer(meta.getString("insightId"));
}
if (meta != null && meta.has("tz")) {
strTz = WebUtility.inputSQLSanitizer(meta.getString("tz"));
}
String uuid = GUID.v7().toUUID().toString();
// figure out the type of insight
if (insightId == null || insightId.toString().isEmpty() || insightId.equals("undefined")
|| insightId.equals("new")) {
// need to make a new insight here
insight = new Insight();
insight.setBaseURL(WebUtility.getRefererURL(request));
InsightStore.getInstance().put(insight);
insightId = insight.getInsightId();
} else {
// or just get it from the store
// the session id needs to be checked
// you better have a valid id... or else... O_O
insight = InsightStore.getInstance().get(insightId);
if (insight == null) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Could not find the insight id");
errorMap.put(ERROR_TYPE, INSIGHT_NOT_FOUND);
classLogger.error("Insight not found for insightId: {}", insightId);
return WebUtility.getResponse(errorMap, 400);
}
}
InsightStore.getInstance().addToSessionHash(sessionId, insightId);
// set the user
insight.setUser(user);
// set the user timezone
ZoneId zoneId = null;
if (strTz == null || (strTz = strTz.trim()).isEmpty()) {
zoneId = ZoneId.of(Utility.getApplicationTimeZoneId());
} else {
try {
zoneId = ZoneId.of(strTz);
} catch (Exception e) {
classLogger.warn("Invalid timezone value '{}', falling back to application default", strTz, e);
zoneId = ZoneId.of(Utility.getApplicationTimeZoneId());
}
}
// need null check if security is off
if (user != null) {
user.setZoneId(zoneId);
}
// set if we are scheduler mode
Boolean schedulerMode = ThreadStore.isSchedulerMode();
if (schedulerMode != null) {
insight.setSchedulerMode(schedulerMode);
}
// set in thread
ThreadStore.setInsightId(insight.getInsightId());
ThreadStore.setSessionId(sessionId);
ThreadStore.setRouteId(routeId);
ThreadStore.setJobId(uuid);
ThreadStore.setUser(insight.getUser());
String reactorName = root.getJSONObject("params").getString("name");
JSONObject arguments = root.getJSONObject("params").getJSONObject("arguments");
int statusCode = 200;
IReactor thisReactor = ReactorFactory.getReactor(insight, reactorName, null, insight.getCurFrame());
JSONObject reactorToolMCP = thisReactor.asMcpTool();
// get everything else
JSONObject reactorProperties = ((JSONObject) reactorToolMCP.get("inputSchema")).getJSONObject("properties");
try {
String retObject = MCPUtility.runPixelTool(null, insight, reactorName, reactorProperties,
arguments.toMap());
Map<String, Object> resultMap = new HashMap<>();
List<Map<String, Object>> contentList = new ArrayList<>();
Map<String, Object> contentMap = new HashMap<>();
contentMap.put("type", "text");
contentMap.put("text", retObject);
contentList.add(contentMap);
resultMap.put("content", contentList);
resultMap.put("isError", false);
response.put("result", resultMap);
} catch (SemossMCPException e) {
classLogger.error("MCP tool execution failed: {}", e.getMessage(), e);
statusCode = 400;
/*
* { "jsonrpc": "2.0", "id": 3, "error": { "code": <example code>, "message":
* <example message> } }
*/
JSONObject error = new JSONObject();
error.put("code", e.getError().getCode());
if (e.getMessage() != null) {
error.put("message", e.getMessage());
} else {
error.put("message", e.getError().getDescription());
}
response.put("error", error);
} catch (Exception e) {
classLogger.error("Unexpected error during MCP tool execution", e);
statusCode = 400;
JSONObject error = new JSONObject();
error.put("code", MCPErrorCode.TOOL_EXECUTION_FAILED.getCode());
if (e.getMessage() != null) {
error.put("message", e.getMessage());
} else {
error.put("message", MCPErrorCode.TOOL_EXECUTION_FAILED.getDescription());
}
response.put("error", error);
}
return Response.status(statusCode).entity(response.toString())
.header("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0")
.header("Pragma", "no-cache").build();
}
@POST
@Path("/getPipeline")
@Produces("application/json;charset=utf-8")
public Response getPixelPipelinePlan(@Context HttpServletRequest request) {
HttpSession session = request.getSession(false);
String sessionId = null;
User user = null;
if (session != null) {
sessionId = session.getId();
user = ((User) session.getAttribute(Constants.SESSION_USER));
}
if (user == null) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "User session is invalid");
classLogger.debug("User session is invalid");
return WebUtility.getResponse(errorMap, 401);
}
String insightId = WebUtility.inputSanitizer(request.getParameter("insightId"));
Insight insight = InsightStore.getInstance().get(insightId);
if (insight == null) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Could not find the insight id");
errorMap.put(ERROR_TYPE, INSIGHT_NOT_FOUND);
classLogger.error("Insight not found for insightId: {}", insightId);
return WebUtility.getResponse(errorMap, 400);
}
// set the user
insight.setUser(user);
// set in thread
ThreadStore.setInsightId(insightId);
ThreadStore.setSessionId(sessionId);
ThreadStore.setUser(user);
return getInsightPipeline(insight);
}
/**
*
* @param user
* @param insight
* @param expression
* @param insightId
* @param sessionId
* @param routeId
* @param dropLogging
* @return
*/
public static Response runPixelJob(User user, Insight insight, String expression, String insightId,
String sessionId, String routeId, boolean dropLogging) {
PixelJobManager manager = PixelJobManager.getManager();
PixelJobRunner jobRunner = manager.makeJob(WebUtility.inputSanitizer(insightId), insight, sessionId, routeId);
String jobId = jobRunner.getJobId();
jobRunner.addPixel(expression);
jobRunner.run();
PixelRunner pixelRunner = jobRunner.getRunner();
try {
return Response.status(200).entity(PixelStreamUtility.collectPixelData(pixelRunner, jobRunner))
.header("Cache-Control",
"no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0")
.header("Pragma", "no-cache").build();
} catch (Exception e) {
Map<String, Object> error = new HashMap<>();
error.put(ERROR_TYPE, "unknown");
error.put("message", e.getMessage());
return Response.status(500).entity(error)
.header("Cache-Control",
"no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0")
.header("Pragma", "no-cache").build();
} finally {
// there are times when we spin up
// other runPixel requests on the same
// insight but don't want to drop the master insight
// console logging
// example is ExportToExcel grids
jobRunner.setStatus(PixelJobStatus.COMPLETE);
if (dropLogging) {
manager.clearJob(jobId);
manager.removeJob(jobId);
// dont do this
// let the clearing happen from the UserSessionLoader
// so that we also close any user processes that exist
// if(insight.isTemporaryInsight()) {
// InsightStore.getInstance().removeFromSessionHash(WebUtility.inputSQLSanitizer(sessionId), WebUtility.inputSQLSanitizer(insightId));
// }
}
}
}
/**
*
* @param insight
* @param expression
* @return
*/
public static Response getInsightPipeline(final Insight insight) {
synchronized (insight) {
try {
return Response.status(200)
.entity(GsonUtility.getDefaultGson().toJson(PixelUtility.generatePipeline(insight))).build();
} catch (Exception e) {
classLogger.error("Failed to generate pipeline for insight", e);
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 400);
}
}
}
@POST
@Path("runPixelAsync")
@Consumes({ "application/x-www-form-urlencoded", "application/json" })
@Produces("application/json;charset=utf-8")
public Response runPixelAsync(@Context HttpServletRequest request) {
HttpSession session = request.getSession(false);
String sessionId = null;
String routeId = null;
User user = null;
Insight insight = null;
if (session != null) {
sessionId = WebUtility.inputSQLSanitizer(session.getId());
user = ((User) session.getAttribute(Constants.SESSION_USER));
}
if (user == null) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "User session is invalid");
classLogger.debug("User session is invalid");
return WebUtility.getResponse(errorMap, 401);
}
// add the route if this is server deployment
String routeCookieName = Utility.getDIHelperProperty(Constants.LOAD_BALANCER_COOKIE_NAME);
if (routeCookieName != null && !routeCookieName.isEmpty()) {
Cookie[] curCookies = request.getCookies();
if (curCookies != null) {
for (Cookie c : curCookies) {
classLogger.debug(">>>>> Request cookie {} with value {}", Utility.cleanLogString(c.getName()),
Utility.cleanLogString(c.getValue()));
if (c.getName().equals(routeCookieName)) {
routeId = WebUtility.inputSQLSanitizer(c.getValue());
ChromeDriverUtility.setRouteCookieValue(c.getValue());
}
}
}