Repository navigation
Expand file tree
/
Copy pathUser.java
More file actions
1245 lines (1107 loc) · 39.2 KB
/
Copy pathUser.java
File metadata and controls
1245 lines (1107 loc) · 39.2 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.auth;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
import org.javatuples.Pair;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import prerna.auth.utils.UserAssetUtils;
import prerna.cluster.util.ClusterUtil;
import prerna.engine.impl.model.Room;
import prerna.engine.impl.r.IRUserConnection;
import prerna.engine.impl.r.RRemoteRserve;
import prerna.engine.impl.r.RUserConnectionDedicated;
import prerna.om.ClientProcessWrapper;
import prerna.om.LocalUserStore;
import prerna.project.api.IProject;
import prerna.reactor.frame.r.util.RJavaTranslatorFactory;
import prerna.reactor.mgmt.MgmtUtil;
import prerna.reactor.playwright.PlaywrightSession;
import prerna.tcp.client.SocketClient;
import prerna.util.Constants;
import prerna.util.Settings;
import prerna.util.SymlinkHelper;
import prerna.util.openshell.OpenShellUserSandboxes;
import prerna.util.InternalUtility;
import prerna.util.Utility;
import prerna.util.sandbox.ISandbox;
import prerna.util.sandbox.SandboxFactory;
public class User implements Serializable {
private static Logger classLogger = LogManager.getLogger(User.class);
private static final String DIR_SEPARATOR = "/";
// main object storing the users access tokens
private Map<AuthProvider, AccessToken> accessTokens = new ConcurrentHashMap<>();
private List<AuthProvider> loggedInProfiles = Collections.synchronizedList(new ArrayList<>());
// storing the timezone the user is in
private ZoneId zoneId;
// store model conversation rooms
private Map<String, Room> roomHash = new ConcurrentHashMap<>();
// store the users insights
private transient Map<String, List<String>> openInsights = null;
// need to have an access token store
private transient IRUserConnection rcon;
private transient RRemoteRserve rconRemote;
// python related stuff
private transient ClientProcessWrapper pythonCPW = new ClientProcessWrapper();
// node.js agent execution environment - lazily spawned, agent-tool only
private transient ClientProcessWrapper nodeCPW = new ClientProcessWrapper();
private transient ClientProcessWrapper javaCPW = new ClientProcessWrapper();
private String chrootPath = null;
private transient volatile SymlinkHelper symlinkHelper = null;
// playwright
private transient volatile Map<String, PlaywrightSession> playwrightSessionStore = null;
private transient volatile BrowserContext sharedPlaywrightContext;
private Map<AuthProvider, String> assetProjectMap = new ConcurrentHashMap<>();
private AuthProvider primaryLogin;
// in-memory mutex for user-scoped lazy init/mutations (asset project creation,
// symlink setup, temporal key generation,
// playwright context/session store setup)
private transient ReentrantLock userLock = new ReentrantLock();
// need to move everything here
// since on reconnect we need to redo serialization.
private Map<String, Boolean> insightSerializedMap = new ConcurrentHashMap<>();
// this is a unique identifier for this user instance
private String userEpoch = null;
private transient volatile String[] cachedTemporalAccessSecretKey = null;
public User() {
// transient objects should be defined in the constructor
// since if this is serialized we dont want these values to be null
this.openInsights = new HashMap<>();
// set it in the mgmt utils
addUserMemory();
this.userEpoch = UUID.randomUUID().toString();
this.playwrightSessionStore = new ConcurrentHashMap<>();
}
/**
* Set the access token for a given provider
*
* @param value
*/
public void setAccessToken(AccessToken value) {
value = ReadOnlyAccessToken.unmodifiableToken(value);
AuthProvider name = value.getProvider();
if (!loggedInProfiles.contains(name)) {
loggedInProfiles.add(name);
}
accessTokens.put(name, value);
}
/**
* Set the access token for a given provider We do not register in the logged in
* profiles but can still grab from reactors that utilize them
*
* @param value
*/
public void setGlobalAccessToken(AccessToken value) {
AuthProvider name = value.getProvider();
accessTokens.put(name, value);
}
/**
* Get the requested access token
*
* @param name
* @return
*/
public AccessToken getAccessToken(AuthProvider name) {
return accessTokens.get(name);
}
/**
* Drop the access token for a given provider
*
* @param name The name of the provider
* @return boolean if the provider was dropped
*/
public boolean dropAccessToken(String name) {
// remove from token map
AuthProvider tokenKey = AuthProvider.valueOf(name);
AccessToken token = accessTokens.remove(tokenKey);
// remove from profiles list
loggedInProfiles.remove(tokenKey);
// return false if the token actually wasn't found
return token != null;
}
/**
* Drop the access token for a given provider
*
* @param tokenKey The name of the provider
* @return boolean if the provider was dropped
*/
public boolean dropAccessToken(AuthProvider tokenKey) {
// remove from token map
AccessToken token = accessTokens.remove(tokenKey);
// remove from profiles list
loggedInProfiles.remove(tokenKey);
// return false if the token actually wasn't found
if (token == null) {
return false;
}
// recalculate the primary login
if (this.primaryLogin == tokenKey && !this.loggedInProfiles.isEmpty()) {
this.primaryLogin = this.loggedInProfiles.get(0);
}
return true;
}
/**
* Get the list of logged in profiles
*
* @return
*/
public List<AuthProvider> getLogins() {
return loggedInProfiles;
}
public boolean isLoggedIn() {
return !this.loggedInProfiles.isEmpty();
}
/**
* Returns whether another user is the same person as this one: the same object,
* or a user who shares a login with the same id and login type.
*
* @param other the user to compare with, or null
* @return true when both are the same person
*/
public boolean isSamePerson(User other) {
if (other == this) {
return true;
}
if (other == null) {
return false;
}
for (AuthProvider login : getLogins()) {
AccessToken mine = getAccessToken(login);
AccessToken theirs = other.getAccessToken(login);
if (mine != null && theirs != null && mine.getId() != null && mine.getId().equals(theirs.getId())) {
return true;
}
}
return false;
}
////////////////////////////////////////////////////////////////////////
public AuthProvider getPrimaryLogin() {
if (this.primaryLogin == null && isLoggedIn()) {
this.primaryLogin = this.loggedInProfiles.get(0);
}
return this.primaryLogin;
}
public AccessToken getPrimaryLoginToken() {
if (this.primaryLogin == null && isLoggedIn()) {
this.primaryLogin = this.loggedInProfiles.get(0);
}
return accessTokens.get(primaryLogin);
}
public void setPrimaryLogin(AuthProvider primaryLogin) {
this.primaryLogin = primaryLogin;
}
public String getAssetProjectId(AuthProvider token) {
if (token == null) {
return null;
}
String cachedProjectId = this.assetProjectMap.get(token);
if (cachedProjectId != null) {
return cachedProjectId;
}
String projectId = UserAssetUtils.getUserAssetProject(this, token);
if (projectId != null) {
this.assetProjectMap.put(token, projectId);
} else {
ReentrantLock lock = getUserLock();
lock.lock();
try {
projectId = UserAssetUtils.getUserAssetProject(this, token);
if (projectId == null) {
projectId = UserAssetUtils.createUserAssetProject(this, token);
}
} catch (Exception e) {
classLogger.error("Failed to load or create user asset project for token {}", token, e);
} finally {
lock.unlock();
}
if (projectId != null) {
this.assetProjectMap.put(token, projectId);
}
}
if (projectId == null) {
return null;
}
// TODO actually sync the pull, not sure pull it
if (ClusterUtil.IS_CLUSTER) {
ClusterUtil.pullUserAsset(projectId, false);
}
return projectId;
}
/**
* Convenience wrapper that returns the user's asset project as an IProject,
* resolved via the primary login token.
*/
public IProject getAssetProject() {
return getAssetProject(getPrimaryLogin());
}
/**
* Convenience wrapper that returns the user's asset project as an IProject for
* the given auth provider token.
*/
public IProject getAssetProject(AuthProvider token) {
String projectId = getAssetProjectId(token);
if (projectId == null) {
return null;
}
return InternalUtility.getUserAssetProject(projectId);
}
public Map<AuthProvider, String> getAssetEngineMap() {
return this.assetProjectMap;
}
public String getUserEpoch() {
return userEpoch;
}
////////////////////////////////////////////////////////////////////////
public IRUserConnection getRcon() {
return rcon;
}
public void setRcon(IRUserConnection rcon) {
this.rcon = rcon;
}
public RRemoteRserve getRconRemote() {
return rconRemote;
}
public void setRconRemote(RRemoteRserve rconRemote) {
this.rconRemote = rconRemote;
}
/**
* Store the open insight
*
* @param engineId
* @param rdbmsId
* @param insightId
*/
public void addOpenInsight(String engineId, String rdbmsId, String insightId) {
if (this.openInsights == null) {
this.openInsights = new ConcurrentHashMap<>();
}
String id = getUid(engineId, rdbmsId);
this.openInsights.computeIfAbsent(id, k -> Collections.synchronizedList(new ArrayList<>())).add(insightId);
}
/**
* Remove open insight
*
* @param engineId
* @param rdbmsId
* @param insightId
*/
public void removeOpenInsight(String engineId, String rdbmsId, String insightId) {
if (this.openInsights == null) {
return;
}
String id = getUid(engineId, rdbmsId);
this.openInsights.computeIfPresent(id, (k, openInstances) -> {
openInstances.remove(insightId);
// Returning null automatically removes the key from the map
// if the list is now empty
return openInstances.isEmpty() ? null : openInstances;
});
}
/**
* Grab the open insight ids for a specific saved insight
*
* @param engineId
* @param rdbmsId
* @return
*/
public List<String> getOpenInsightInstances(String engineId, String rdbmsId) {
String id = getUid(engineId, rdbmsId);
return this.openInsights.get(id);
}
private String getUid(String engineId, String rdbmsId) {
return engineId + "__" + rdbmsId;
}
/**
* Get the user open insights
*
* @return
*/
public Map<String, List<String>> getOpenInsights() {
return openInsights;
}
/**
*
* @param zoneId
*/
public void setZoneId(ZoneId zoneId) {
this.zoneId = zoneId;
}
/**
*
* @return
*/
public ZoneId getZoneId() {
return zoneId;
}
/**
*
* @return
*/
public Map<String, Room> getRoomHash() {
return roomHash;
}
/**
* Returns the user-level lock, lazily reinitializing after deserialization when
* transient fields are null.
*/
private ReentrantLock getUserLock() {
ReentrantLock lock = this.userLock;
if (lock != null) {
return lock;
}
synchronized (this) {
lock = this.userLock;
if (lock == null) {
lock = new ReentrantLock();
this.userLock = lock;
}
}
return lock;
}
/**
*
* @return
*/
public ClientProcessWrapper getPythonClientProcessWrapper() {
return this.pythonCPW;
}
/**
*
* @param create
* @return
*/
public SocketClient getPythonSocketClient(boolean create) {
return getPythonSocketClient(create, -1, null);
}
/**
*
* @param create
* @param venvEngineId
* @return
*/
public SocketClient getPythonSocketClient(boolean create, String venvEngineId) {
return getPythonSocketClient(create, -1, venvEngineId);
}
/**
*
* @param create
* @param port
* @return
*/
public SocketClient getPythonSocketClient(boolean create, int port, String venvEngineId) {
if (!create) {
if (this.pythonCPW == null) {
return null;
}
return this.pythonCPW.getSocketClient();
}
if (OpenShellUserSandboxes.appliesTo(this)) {
return getOpenShellPythonSocketClient(venvEngineId);
}
if (this.pythonCPW == null) {
this.pythonCPW = new ClientProcessWrapper();
}
SocketClient client = this.pythonCPW
.getOrStartSocketClient(() -> startPythonSocketServerAndClient(-1, venvEngineId));
client.setUser(this);
return client;
}
/**
* OPENSHELL: the user's python is one persistent worker in their own sandbox,
* shared by every session of theirs. On this instance all of those sessions use
* one wrapper (one connection, one record of what was transported); the wrapper
* attaches to the sandbox if it is running anywhere and creates it otherwise.
*/
private SocketClient getOpenShellPythonSocketClient(String venvEngineId) {
while (true) {
OpenShellUserSandboxes.Local local = OpenShellUserSandboxes.local(this);
synchronized (local) {
if (local.isReleased()) {
// the user's last other session here ended between the lookup and the lock
continue;
}
this.pythonCPW = local.getWrapper();
// write-back permission checks run as the session that asked most recently
this.pythonCPW.setUser(this);
SocketClient client = this.pythonCPW.getSocketClient();
if (client == null) {
startPythonSocketServerAndClient(-1, venvEngineId);
} else if (!client.isConnected()) {
this.pythonCPW.shutdown(false);
try {
this.pythonCPW.reconnect();
} catch (Exception e) {
classLogger.error("Failed to reconnect to user python process", e);
throw new IllegalArgumentException("Failed to connect to your isolated analytics engine");
}
}
this.pythonCPW.getSocketClient().setUser(this);
break;
}
}
this.insightSerializedMap.clear();
return this.pythonCPW.getSocketClient();
}
/**
* The user's sandbox: where their workers and commands run, and what they may
* see. The one way to grant a folder or project, start a worker or run a
* command, whichever backend is configured.
*
* @return the sandbox
* @throws IllegalArgumentException when chroot is not enabled on this instance
*/
public ISandbox getSandbox() {
return SandboxFactory.of(getUserSymlinkHelper(), this);
}
/**
*
* @return
*/
public SymlinkHelper getUserSymlinkHelper() {
if (Boolean.parseBoolean(Utility.getDIHelperProperty(Constants.CHROOT_ENABLE))) {
if (OpenShellUserSandboxes.appliesTo(this)) {
// shared by the user's sessions on this instance;
// see getOpenShellPythonSocketClient
symlinkHelper = OpenShellUserSandboxes.local(this).getHelper();
// permission checks run as the session that asked most recently
symlinkHelper.setUser(this);
chrootPath = symlinkHelper.getUserChrootFolder();
return symlinkHelper;
}
if (symlinkHelper != null) {
return symlinkHelper;
}
ReentrantLock lock = getUserLock();
lock.lock();
try {
if (symlinkHelper == null) {
String uniqueUserName = getSingleLogginName(this) + "-" + UUID.randomUUID().toString();
String chrootDir = Utility.getDIHelperProperty(Constants.CHROOT_DIR);
chrootPath = chrootDir + DIR_SEPARATOR + uniqueUserName;
symlinkHelper = new SymlinkHelper(chrootPath, this);
// symlink the user asset folder into the chroot on boot
try {
symlinkHelper.symlinkUserAsset(this);
} catch (Exception e) {
classLogger.warn("Unable to symlink user asset folder into chroot", e);
}
}
} finally {
lock.unlock();
}
return symlinkHelper;
}
throw new IllegalArgumentException("Chroot is not enabled on this instance");
}
/**
* Starts this user's native Python server process and connects its socket
* client. The process runs inside the user's chroot when chroot is enabled.
*
* @param port the port to connect on; negative to auto-allocate, or to
* use FORCE_PORT when it is set
* @param venvEngineId the virtual environment engine whose Python executable to
* use, or null for the base Python
*/
public void startPythonSocketServerAndClient(int port, String venvEngineId) {
if (this.pythonCPW == null) {
this.pythonCPW = new ClientProcessWrapper();
}
if (this.pythonCPW.getSocketClient() == null || !this.pythonCPW.getSocketClient().isConnected()) {
boolean debug = false;
if (port < 0) {
String forcePort = Utility.getDIHelperProperty(Settings.FORCE_PORT);
// port has not been forced
if (forcePort != null && !(forcePort = forcePort.trim()).isEmpty()) {
try {
port = Integer.parseInt(forcePort);
debug = true;
} catch (NumberFormatException e) {
// ignore
classLogger.warn("User {} has an invalid FORCE_PORT value", User.getSingleLogginName(this));
}
}
}
String loggerLevel = Utility.getDIHelperProperty(Settings.LOGGER_LEVEL);
if (loggerLevel == null || (loggerLevel = loggerLevel.trim()).isEmpty()) {
loggerLevel = "WARNING";
}
String serverDirectory = Utility.getDIHelperProperty(Constants.INSIGHT_CACHE_DIR);
Path serverDirectoryPath = null;
if (Boolean.parseBoolean(Utility.getDIHelperProperty(Constants.CHROOT_ENABLE))) {
// unique user is just for testing so when i ls on R,
// I can see it is me and not someone else
this.symlinkHelper = getUserSymlinkHelper();
// we do not define the Server Directory here - because it will dynamically
// generate in the chroot location
try {
this.pythonCPW.setUser(this);
this.pythonCPW.createProcessAndClient(true, this.symlinkHelper, port, null, null, debug, "-1",
loggerLevel, ThreadContext.getImmutableContext());
} catch (Exception e) {
classLogger.error("Failed to start chrooted python process for user {}",
User.getSingleLogginName(this), e);
throw new IllegalArgumentException("Unable to connect to user server");
}
} else {
try {
serverDirectoryPath = getWorkerDirectory(this.pythonCPW, serverDirectory, "a");
} catch (IOException e) {
classLogger.error("Failed to create temp directory for non-chroot python process under {}",
serverDirectory, e);
throw new IllegalArgumentException("Could not create directory to launch project process");
}
classLogger.info("Starting Non-chroot TCP Server for User = {}", User.getSingleLogginName(this));
try {
String venvPath = venvEngineId != null ? Utility.getVenvEngine(venvEngineId).pathToExecutable()
: this.pythonCPW.getVenvPath();
this.pythonCPW.setUser(this);
this.pythonCPW.createProcessAndClient(true, null, port, venvPath, serverDirectoryPath.toString(),
debug, "-1", loggerLevel, ThreadContext.getImmutableContext());
} catch (Exception e) {
classLogger.error("Failed to start non-chroot python process for user {}",
User.getSingleLogginName(this), e);
throw new IllegalArgumentException("Unable to connect to user server");
}
}
}
}
/**
*
* @return
*/
public ClientProcessWrapper getNodeClientProcessWrapper() {
return this.nodeCPW;
}
/**
* Get the socket client for this user's node.js agent worker, optionally
* starting the worker if it is not running. Unlike the python process, the node
* worker is only ever reached through agent harness tools - there is no
* user-facing reactor or endpoint for it.
*
* @param create true to lazily start/revive the worker
* @return the socket client, or null when create is false and none exists
*/
public SocketClient getNodeSocketClient(boolean create) {
if (!create) {
if (this.nodeCPW == null) {
return null;
}
return this.nodeCPW.getSocketClient();
}
if (this.nodeCPW == null) {
this.nodeCPW = new ClientProcessWrapper();
}
SocketClient client = this.nodeCPW.getOrStartSocketClient(() -> startNodeSocketServerAndClient(-1));
client.setUser(this);
return client;
}
/**
* Start the per-user node.js agent worker and its socket client. The worker
* self-exits after an idle period (NODE_IDLE_TIMEOUT minutes, default 30) since
* no user session depends on it directly.
*
* @param port the port to connect on; negative to auto-allocate
*/
public void startNodeSocketServerAndClient(int port) {
if (this.nodeCPW == null) {
this.nodeCPW = new ClientProcessWrapper();
}
if (this.nodeCPW.getSocketClient() == null || !this.nodeCPW.getSocketClient().isConnected()) {
String loggerLevel = Utility.getDIHelperProperty(Settings.LOGGER_LEVEL);
if (loggerLevel == null || (loggerLevel = loggerLevel.trim()).isEmpty()) {
loggerLevel = "WARNING";
}
String idleTimeout = Utility.getDIHelperProperty(Settings.NODE_IDLE_TIMEOUT);
if (idleTimeout == null || (idleTimeout = idleTimeout.trim()).isEmpty()) {
idleTimeout = "30";
}
String serverDirectory = Utility.getDIHelperProperty(Constants.INSIGHT_CACHE_DIR);
Path serverDirectoryPath = null;
try {
serverDirectoryPath = getWorkerDirectory(this.nodeCPW, serverDirectory, "n");
} catch (IOException e) {
classLogger.error("Failed to create temp directory for the node process under {}", serverDirectory, e);
throw new IllegalArgumentException("Could not create directory to launch the node process");
}
classLogger.info("Starting node agent worker for User = {}", User.getSingleLogginName(this));
try {
this.nodeCPW.createNodeProcessAndClient(port, serverDirectoryPath.toString(), false, idleTimeout,
loggerLevel, ThreadContext.getImmutableContext());
} catch (Exception e) {
classLogger.error("Failed to start node process for user {}", User.getSingleLogginName(this), e);
throw new IllegalArgumentException("Unable to connect to the node execution engine");
}
}
}
/**
* Returns the wrapper for this user's Java worker process, which runs R over
* TCP and the custom reactors set to execute on the socket.
*
* @return the Java worker process wrapper
*/
public ClientProcessWrapper getJavaClientProcessWrapper() {
return this.javaCPW;
}
/**
* Returns the socket client for this user's Java worker process, which runs R
* over TCP and the custom reactors set to execute on the socket.
*
* @param create true to start the worker, or reconnect to it, when it is not
* connected
* @return the socket client, or null when create is false and no worker exists
*/
public SocketClient getJavaSocketClient(boolean create) {
if (!create) {
if (this.javaCPW == null) {
return null;
}
return this.javaCPW.getSocketClient();
}
if (this.javaCPW == null) {
this.javaCPW = new ClientProcessWrapper();
}
SocketClient client = this.javaCPW.getOrStartSocketClient(() -> startJavaSocketServerAndClient(-1));
client.setUser(this);
this.insightSerializedMap.clear();
return client;
}
/**
* Starts this user's Java worker process and connects its socket client. The
* worker runs inside the user's chroot when chroot is enabled.
*
* @param port the port to connect on; negative to auto-allocate, or to attach
* to JAVA_FORCE_PORT when it is set
*/
public void startJavaSocketServerAndClient(int port) {
if (this.javaCPW == null) {
this.javaCPW = new ClientProcessWrapper();
}
if (this.javaCPW.getSocketClient() == null || !this.javaCPW.getSocketClient().isConnected()) {
boolean debug = false;
if (port < 0) {
String forcePort = Utility.getDIHelperProperty(Settings.JAVA_FORCE_PORT);
if (forcePort != null && !(forcePort = forcePort.trim()).isEmpty()) {
try {
port = Integer.parseInt(forcePort);
debug = true;
} catch (NumberFormatException e) {
classLogger.warn("User {} has an invalid JAVA_FORCE_PORT value",
User.getSingleLogginName(this));
}
}
}
String loggerLevel = Utility.getDIHelperProperty(Settings.LOGGER_LEVEL);
if (loggerLevel == null || (loggerLevel = loggerLevel.trim()).isEmpty()) {
loggerLevel = "WARNING";
}
if (Boolean.parseBoolean(Utility.getDIHelperProperty(Constants.CHROOT_ENABLE))) {
this.symlinkHelper = getUserSymlinkHelper();
try {
this.javaCPW.createProcessAndClient(false, this.symlinkHelper, port, null, null, debug, "-1",
loggerLevel, ThreadContext.getImmutableContext());
} catch (Exception e) {
classLogger.error("Failed to start chrooted Java worker for user {}",
User.getSingleLogginName(this), e);
throw new IllegalArgumentException("Unable to connect to the Java worker");
}
} else {
String serverDirectory = Utility.getDIHelperProperty(Constants.INSIGHT_CACHE_DIR);
Path serverDirectoryPath = null;
try {
serverDirectoryPath = getWorkerDirectory(this.javaCPW, serverDirectory, "j");
} catch (IOException e) {
classLogger.error("Failed to create temp directory for the Java worker under {}", serverDirectory,
e);
throw new IllegalArgumentException("Could not create directory to launch the Java worker");
}
classLogger.info("Starting Java worker for User = {}", User.getSingleLogginName(this));
try {
this.javaCPW.createProcessAndClient(false, null, port, null, serverDirectoryPath.toString(), debug,
"-1", loggerLevel, ThreadContext.getImmutableContext());
} catch (Exception e) {
classLogger.error("Failed to start Java worker for user {}", User.getSingleLogginName(this), e);
throw new IllegalArgumentException("Unable to connect to the Java worker");
}
}
}
}
/**
* Returns the folder a worker runs in: the folder its wrapper already uses when
* that still exists, so a restarted worker keeps its folder, or a new folder
* under the insight cache.
*
* @param cpw the worker's process wrapper
* @param cacheDir the insight cache folder
* @param folderPrefix the prefix for a new folder's name
* @return the folder
* @throws IOException if a new folder cannot be created
*/
private static Path getWorkerDirectory(ClientProcessWrapper cpw, String cacheDir, String folderPrefix)
throws IOException {
String existing = cpw.getServerDirectory();
if (existing != null && Files.isDirectory(Paths.get(existing))) {
return Paths.get(existing);
}
return Files.createTempDirectory(Paths.get(cacheDir), folderPrefix);
}
/**
* Returns the process that runs this user's R: the Java worker when R runs over
* TCP, or the user's dedicated Rserve.
*
* @return the process, or null when R does not run in a process of its own for
* this user
*/
public Process getrProcess() {
if (RJavaTranslatorFactory.runsInJavaWorker()) {
return this.javaCPW == null ? null : this.javaCPW.getProcess();
}
return this.rcon instanceof RUserConnectionDedicated dedicated ? dedicated.getProcess() : null;
}
/**
* Returns the port of the process that runs this user's R: the Java worker when
* R runs over TCP, or the user's dedicated Rserve.
*
* @return the port, or -1 when R does not run in a process of its own for this
* user
*/
public int getrPort() {
if (RJavaTranslatorFactory.runsInJavaWorker()) {
return this.javaCPW == null || this.javaCPW.getSocketClient() == null ? -1 : this.javaCPW.getPort();
}
return this.rcon instanceof RUserConnectionDedicated dedicated ? dedicated.getPort() : -1;
}
/**
* Returns the port of this user's python process.
*
* @return the port, or -1 when the python process has not started
*/
public int getPyPort() {
return this.pythonCPW == null || this.pythonCPW.getSocketClient() == null ? -1 : this.pythonCPW.getPort();
}
private void addUserMemory() {
long memoryInGigs = 0;
// check if the user has memory
boolean checkMem = Boolean.parseBoolean(Utility.getDIHelperProperty(Settings.CHECK_MEM) + "");
if (checkMem) {
long freeMem = MgmtUtil.getFreeMemory();
String memProfileSettings = Utility.getDIHelperProperty(Settings.MEM_PROFILE_SETTINGS);
if (memProfileSettings.equalsIgnoreCase(Settings.CONSTANT_MEM)) {
String memLimitSettings = Utility.getDIHelperProperty(Settings.USER_MEM_LIMIT);
memoryInGigs = Integer.parseInt(memLimitSettings);
}
MgmtUtil.addMemory4User(memoryInGigs);
}
}
public void removeUserMemory() {
long memoryInGigs = 0;
// check if the user has memory
boolean checkMem = Boolean.parseBoolean(Utility.getDIHelperProperty(Settings.CHECK_MEM) + "");
if (checkMem) {
String memProfileSettings = Utility.getDIHelperProperty(Settings.MEM_PROFILE_SETTINGS);
if (memProfileSettings.equalsIgnoreCase(Settings.CONSTANT_MEM)) {
String memLimitSettings = Utility.getDIHelperProperty(Settings.USER_MEM_LIMIT);
memoryInGigs = Integer.parseInt(memLimitSettings);
}
MgmtUtil.removeMemory4User(memoryInGigs);
}
}
public String[] getUserCredential(AuthProvider prov) {
// just need some specific one the user is using
if (prov != null && accessTokens.containsKey(prov)) {
String[] creds = getUserEmail(accessTokens.get(prov));
if (creds[1] != null) {
return creds;
}
}
Iterator<AuthProvider> accessKeysItr = accessTokens.keySet().iterator();
while (accessKeysItr.hasNext()) {
AuthProvider provider = accessKeysItr.next();
AccessToken tok = accessTokens.get(provider);
String[] creds = getUserEmail(tok);
if (creds[1] != null) {
return creds;
}
}
return new String[] { "anonymous", "anonymous@not_logged_in.com" };
}
public String getCachedTemporalAccessKey() {
if (this.cachedTemporalAccessSecretKey != null) {
return this.cachedTemporalAccessSecretKey[0];
}
return null;
}
public String[] createCachedTemporalAccessSecretKey() {
AccessToken loginToken = this.getPrimaryLoginToken();
if (loginToken == null) {
throw new NullPointerException("User does not have a primary login token");
}
if (this.cachedTemporalAccessSecretKey != null) {
return this.cachedTemporalAccessSecretKey;
}
if (this.cachedTemporalAccessSecretKey == null) {
ReentrantLock lock = getUserLock();
lock.lock();
try {
if (this.cachedTemporalAccessSecretKey == null) {
String accessKey = UUID.randomUUID().toString();
String secretKey = UUID.randomUUID().toString();
this.cachedTemporalAccessSecretKey = new String[] { accessKey, secretKey };
LocalUserStore.getInstance().store(accessKey,
new Object[] { secretKey, loginToken.getId(), loginToken.getProvider() });