/
SessionMain.cpp
2761 lines (2328 loc) · 84.4 KB
/
SessionMain.cpp
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
/*
* SessionMain.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <session/SessionMain.hpp>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
#include <cstdlib>
#include <csignal>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/signals.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/join.hpp>
#include <core/Error.hpp>
#include <core/BoostThread.hpp>
#include <core/FilePath.hpp>
#include <core/Exec.hpp>
#include <core/Scope.hpp>
#include <core/Settings.hpp>
#include <core/Thread.hpp>
#include <core/Log.hpp>
#include <core/system/System.hpp>
#include <core/ProgramStatus.hpp>
#include <core/system/System.hpp>
#include <core/FileSerializer.hpp>
#include <core/http/Request.hpp>
#include <core/http/Response.hpp>
#include <core/http/UriHandler.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/gwt/GwtLogHandler.hpp>
#include <core/gwt/GwtFileHandler.hpp>
#include <core/system/Crypto.hpp>
#include <core/system/Process.hpp>
#include <core/system/Environment.hpp>
#include <core/system/ParentProcessMonitor.hpp>
#include <core/system/FileMonitor.hpp>
#include <core/text/TemplateFilter.hpp>
#include <r/RJsonRpc.hpp>
#include <r/RExec.hpp>
#include <r/ROptions.hpp>
#include <r/RFunctionHook.hpp>
#include <r/RInterface.hpp>
#include <r/session/RSession.hpp>
#include <r/session/RClientState.hpp>
#include <r/session/RConsoleActions.hpp>
#include <r/session/RConsoleHistory.hpp>
#include <r/session/RGraphics.hpp>
#include <r/session/REventLoop.hpp>
extern "C" const char *locale2charset(const char *);
#include <session/SessionConstants.hpp>
#include <session/SessionOptions.hpp>
#include <session/SessionUserSettings.hpp>
#include <session/SessionSourceDatabase.hpp>
#include <session/SessionPersistentState.hpp>
#include "SessionAddins.hpp"
#include "SessionModuleContextInternal.hpp"
#include "SessionClientEventQueue.hpp"
#include "SessionClientEventService.hpp"
#include "modules/SessionAgreement.hpp"
#include "modules/SessionAskPass.hpp"
#include "modules/SessionAuthoring.hpp"
#include "modules/SessionHTMLPreview.hpp"
#include "modules/SessionCodeSearch.hpp"
#include "modules/SessionConsole.hpp"
#include "modules/SessionConsoleProcess.hpp"
#include "modules/SessionCrypto.hpp"
#include "modules/SessionFiles.hpp"
#include "modules/SessionFind.hpp"
#include "modules/SessionWorkspace.hpp"
#include "modules/SessionWorkbench.hpp"
#include "modules/SessionData.hpp"
#include "modules/SessionHelp.hpp"
#include "modules/SessionPlots.hpp"
#include "modules/SessionPath.hpp"
#include "modules/SessionPackages.hpp"
#include "modules/SessionRPubs.hpp"
#include "modules/SessionSpelling.hpp"
#include "modules/SessionSource.hpp"
#include "modules/SessionVCS.hpp"
#include "modules/SessionHistory.hpp"
#include "modules/SessionLimits.hpp"
#include "modules/SessionLists.hpp"
#include "modules/SessionContentUrls.hpp"
#include "modules/build/SessionBuild.hpp"
#include "modules/presentation/SessionPresentation.hpp"
#include "modules/SessionGit.hpp"
#include "modules/SessionSVN.hpp"
#include <session/projects/SessionProjects.hpp>
#include "projects/SessionProjectsInternal.hpp"
#include "workers/SessionWebRequestWorker.hpp"
#include <session/SessionHttpConnectionListener.hpp>
#include "config.h"
using namespace core;
using namespace session;
using namespace session::client_events;
namespace {
// uri handlers
http::UriHandlers s_uriHandlers;
http::UriHandlerFunction s_defaultUriHandler;
// json rpc methods
core::json::JsonRpcAsyncMethods s_jsonRpcMethods;
// R browseUrl handlers
std::vector<module_context::RBrowseUrlHandler> s_rBrowseUrlHandlers;
// R browseFile handlers
std::vector<module_context::RBrowseFileHandler> s_rBrowseFileHandlers;
// names of waitForMethod handlers (used to screen out of bkgnd processing)
std::vector<std::string> s_waitForMethodNames;
// last prompt we issued
std::string s_lastPrompt;
// have we fully initialized? used by rConsoleRead and clientInit to
// tweak their behavior when the process is first starting
bool s_sessionInitialized = false;
// was the underlying r session resumed
bool s_rSessionResumed = false;
// manage global state indicating whether R is processing input
volatile sig_atomic_t s_rProcessingInput = 0;
// did we fail to coerce the charset to UTF-8
bool s_printCharsetWarning = false;
std::queue<r::session::RConsoleInput> s_consoleInputBuffer;
// superivsor is a module level static so that we can terminateChildren
// upon exit of the session (otherwise we could leave a long running
// sweave operation still hogging cpu after we exit)
core::system::ProcessSupervisor s_interruptableChildSupervisor;
// json rpc methods we handle (the rest are delegated to the HttpServer)
const char * const kClientInit = "client_init" ;
const char * const kConsoleInput = "console_input" ;
const char * const kEditCompleted = "edit_completed";
const char * const kChooseFileCompleted = "choose_file_completed";
const char * const kLocatorCompleted = "locator_completed";
const char * const kHandleUnsavedChangesCompleted = "handle_unsaved_changes_completed";
const char * const kQuitSession = "quit_session" ;
const char * const kInterrupt = "interrupt";
// convenience function for disallowing suspend (note still doesn't override
// the presence of s_forceSuspend = 1)
bool disallowSuspend() { return false; }
// request suspends (cooperative and forced) using interrupts
volatile sig_atomic_t s_suspendRequested = 0;
volatile sig_atomic_t s_forceSuspend = 0;
volatile sig_atomic_t s_forceSuspendInterruptedR = 0;
// cooperative suspend -- the http server is forced to timeout and a flag
// indicating that we should suspend at ourfirst valid opportunity is set
void handleUSR1(int unused)
{
// note that a suspend has been requested. the process will suspend
// at the first instance that it is valid for it to do so
s_suspendRequested = 1;
}
// forced suspend -- R is interrupted, the http server is forced to timeout,
// and the 'force' flag is set
void handleUSR2(int unused)
{
// note whether R was interrupted
if (s_rProcessingInput)
s_forceSuspendInterruptedR = 1;
// set the r interrupt flag (always)
r::exec::setInterruptsPending(true);
// note that a suspend is being forced.
s_forceSuspend = 1;
}
// version of the executable
double s_version = 0;
// installed version (computed as the time in seconds since epoch that
// the running/served code was installed) can be distinct from the version
// of the currently running executable if a deployment occured after this
// executable started running.
double installedVersion()
{
// never return a version in desktop mode
if (session::options().programMode() == kSessionProgramModeDesktop)
return 0;
// read installation time (as string) from file (return 0 if not found)
FilePath installedPath("/etc/rstudio/installed");
if (!installedPath.exists())
return 0;
// attempt to get the value (return 0 if we have any trouble)
std::string installedStr;
Error error = readStringFromFile(installedPath, &installedStr);
if (error)
{
LOG_ERROR(error);
return 0;
}
// empty string means 0
if (installedStr.empty())
{
LOG_ERROR_MESSAGE("No value within /etc/rstudio/installed");
return 0;
}
// attempt to parse the value into a double
double installedSeconds = 0.0;
try
{
std::istringstream istr(installedStr);
istr >> installedSeconds;
if (istr.fail())
LOG_ERROR(systemError(boost::system::errc::io_error, ERROR_LOCATION));
}
CATCH_UNEXPECTED_EXCEPTION
// return installed seconds as version
return installedSeconds ;
}
void detectChanges(module_context::ChangeSource source)
{
module_context::events().onDetectChanges(source);
}
// certain things are deferred until after we have sent our first response
// take care of these things here
void ensureSessionInitialized()
{
// note that we are now fully initialized. we defer setting this
// flag so that consoleRead and handleClientInit know that we have just
// started up and can act accordingly
s_sessionInitialized = true;
// ensure the session is fully deserialized (deferred deserialization
// is supported so that the workbench UI can load without having to wait
// for the potentially very lengthy deserialization of the environment)
r::session::ensureDeserialized();
}
FilePath getDefaultWorkingDirectory()
{
// calculate using user settings
FilePath defaultWorkingDir = userSettings().initialWorkingDirectory();
// return it if it exists, otherwise use the default user home path
if (defaultWorkingDir.exists() && defaultWorkingDir.isDirectory())
return defaultWorkingDir;
else
return session::options().userHomePath();
}
FilePath getInitialWorkingDirectory()
{
// check for a project
if (projects::projectContext().hasProject())
return projects::projectContext().directory();
// see if there is an override from the environment (perhaps based
// on a folder drag and drop or other file association)
FilePath workingDirPath = session::options().initialWorkingDirOverride();
if (workingDirPath.exists() && workingDirPath.isDirectory())
{
return workingDirPath;
}
else
{
// if not then just return default working dir
return getDefaultWorkingDirectory();
}
}
void handleClientInit(const boost::function<void()>& initFunction,
boost::shared_ptr<HttpConnection> ptrConnection)
{
// alias options
Options& options = session::options();
// calculate initialization parameters
std::string clientId = session::persistentState().newActiveClientId();
bool resumed = s_rSessionResumed || s_sessionInitialized;
// if we are resuming then we don't need to worry about events queued up
// by R during startup (e.g. printing of the banner) being sent to the
// client. so, clear out the events which might be pending in the
// client event service and/or queue
bool clearEvents = resumed;
// reset the client event service for the new client (will cause
// outstanding http requests from old clients to fail with
// InvalidClientId). note that we can't simply stop() the
// ClientEventService and start() a new one because in that case the
// old client will never get disconnected because it won't get
// the InvalidClientId error.
clientEventService().setClientId(clientId, clearEvents);
// prepare session info
json::Object sessionInfo ;
sessionInfo["clientId"] = clientId;
sessionInfo["mode"] = options.programMode();
sessionInfo["userIdentity"] = options.userIdentity();
// only send log_dir and scratch_dir if we are in desktop mode
if (options.programMode() == kSessionProgramModeDesktop)
{
sessionInfo["log_dir"] = options.userLogPath().absolutePath();
sessionInfo["scratch_dir"] = options.userScratchPath().absolutePath();
}
// temp dir
FilePath tempDir = r::session::utils::tempDir();
Error error = tempDir.ensureDirectory();
if (error)
LOG_ERROR(error);
sessionInfo["temp_dir"] = tempDir.absolutePath();
// installed version
sessionInfo["version"] = installedVersion();
// default prompt
sessionInfo["prompt"] = r::options::getOption<std::string>("prompt");
// client state
json::Object clientStateObject;
r::session::clientState().currentState(&clientStateObject);
sessionInfo["client_state"] = clientStateObject;
// source documents
json::Array jsonDocs;
error = modules::source::clientInitDocuments(&jsonDocs);
if (error)
LOG_ERROR(error);
sessionInfo["source_documents"] = jsonDocs;
// agreement
sessionInfo["hasAgreement"] = modules::agreement::hasAgreement();
sessionInfo["pendingAgreement"] = modules::agreement::pendingAgreement();
// docs url
sessionInfo["docsURL"] = session::options().docsURL();
// get alias to console_actions and get limit
r::session::ConsoleActions& consoleActions = r::session::consoleActions();
sessionInfo["console_actions_limit"] = consoleActions.capacity();
// resumed
sessionInfo["resumed"] = resumed;
if (resumed)
{
// console actions
json::Object actionsObject;
consoleActions.asJson(&actionsObject);
sessionInfo["console_actions"] = actionsObject;
}
sessionInfo["rnw_weave_types"] = modules::authoring::supportedRnwWeaveTypes();
sessionInfo["latex_program_types"] = modules::authoring::supportedLatexProgramTypes();
sessionInfo["tex_capabilities"] = modules::authoring::texCapabilitiesAsJson();
sessionInfo["compile_pdf_state"] = modules::authoring::compilePdfStateAsJson();
sessionInfo["html_capabilities"] = modules::html_preview::capabilitiesAsJson();
sessionInfo["find_in_files_state"] = modules::find::findInFilesStateAsJson();
sessionInfo["rstudio_version"] = std::string(RSTUDIO_VERSION);
sessionInfo["ui_prefs"] = userSettings().uiPrefs();
// initial working directory
std::string initialWorkingDir = module_context::createAliasedPath(
getInitialWorkingDirectory());
sessionInfo["initial_working_dir"] = initialWorkingDir;
// active project file
if (projects::projectContext().hasProject())
{
sessionInfo["active_project_file"] = module_context::createAliasedPath(
projects::projectContext().file());
sessionInfo["project_ui_prefs"] = projects::projectContext().uiPrefs();
}
else
{
sessionInfo["active_project_file"] = json::Value();
sessionInfo["project_ui_prefs"] = json::Value();
}
sessionInfo["system_encoding"] = std::string(::locale2charset(NULL));
std::vector<std::string> vcsAvailable;
if (modules::source_control::isGitInstalled())
vcsAvailable.push_back(modules::git::kVcsId);
if (modules::source_control::isSvnInstalled())
vcsAvailable.push_back(modules::svn::kVcsId);
sessionInfo["vcs_available"] = boost::algorithm::join(vcsAvailable, ",");
sessionInfo["vcs"] = modules::source_control::activeVCSName();
sessionInfo["default_ssh_key_dir"] =module_context::createAliasedPath(
modules::source_control::defaultSshKeyDir());
// contents of all lists
sessionInfo["lists"] = modules::lists::allListsAsJson();
sessionInfo["console_processes"] =
session::modules::console_process::processesAsJson();
// is internal preview supported by the client browser
std::string userAgent = ptrConnection->request().userAgent();
sessionInfo["internal_pdf_preview_enabled"] =
modules::authoring::isPdfViewerSupported(userAgent);
// send sumatra pdf exe path if we are on windows
#ifdef _WIN32
sessionInfo["sumatra_pdf_exe_path"] =
options.sumatraPath().complete("SumatraPDF.exe").absolutePath();
#endif
// are build tools enabled
if (projects::projectContext().hasProject())
{
std::string type = projects::projectContext().config().buildType;
sessionInfo["build_tools_type"] = type;
FilePath buildTargetDir = projects::projectContext().buildTargetPath();
if (!buildTargetDir.empty())
{
sessionInfo["build_target_dir"] = module_context::createAliasedPath(
buildTargetDir);
sessionInfo["has_pkg_src"] = (type == r_util::kBuildTypePackage) &&
buildTargetDir.childPath("src").exists();
}
else
{
sessionInfo["build_target_dir"] = json::Value();
sessionInfo["has_pkg_src"] = false;
}
}
else
{
sessionInfo["build_tools_type"] = r_util::kBuildTypeNone;
sessionInfo["build_target_dir"] = json::Value();
sessionInfo["has_pkg_src"] = false;
}
sessionInfo["presentation_state"] = modules::presentation::presentationStateAsJson();
sessionInfo["build_state"] = modules::build::buildStateAsJson();
sessionInfo["devtools_installed"] = module_context::isPackageInstalled(
"devtools");
sessionInfo["have_rcpp_attributes"] = module_context::haveRcppAttributes();
sessionInfo["have_cairo_pdf"] = modules::plots::haveCairoPdf();
// console history -- we do this at the end because
// restoreBuildRestartContext may have reset it
json::Array historyArray;
r::session::consoleHistory().asJson(&historyArray);
sessionInfo["console_history"] = historyArray;
sessionInfo["console_history_capacity"] =
r::session::consoleHistory().capacity();
// send response (we always set kEventsPending to false so that the client
// won't poll for events until it is ready)
json::JsonRpcResponse jsonRpcResponse ;
jsonRpcResponse.setField(kEventsPending, "false");
jsonRpcResponse.setResult(sessionInfo) ;
ptrConnection->sendJsonRpcResponse(jsonRpcResponse);
// complete initialization of session
ensureSessionInitialized();
// notify modules of the client init
module_context::events().onClientInit();
// call the init function
initFunction();
}
enum ConnectionType
{
ForegroundConnection,
BackgroundConnection
};
void endHandleRpcRequestDirect(boost::shared_ptr<HttpConnection> ptrConnection,
boost::posix_time::ptime executeStartTime,
const core::Error& executeError,
json::JsonRpcResponse* pJsonRpcResponse)
{
// return error or result then continue waiting for requests
if (executeError)
{
ptrConnection->sendJsonRpcError(executeError);
}
else
{
// allow modules to detect changes after rpc calls
if (!pJsonRpcResponse->suppressDetectChanges())
detectChanges(module_context::ChangeSourceRPC);
// are there (or will there likely be) events pending?
// (if not then notify the client)
if ( !clientEventQueue().eventAddedSince(executeStartTime) &&
!pJsonRpcResponse->hasAfterResponse() )
{
pJsonRpcResponse->setField(kEventsPending, "false");
}
// send the response
ptrConnection->sendJsonRpcResponse(*pJsonRpcResponse);
// run after response if we have one (then detect changes again)
if (pJsonRpcResponse->hasAfterResponse())
{
pJsonRpcResponse->runAfterResponse();
if (!pJsonRpcResponse->suppressDetectChanges())
detectChanges(module_context::ChangeSourceRPC);
}
}
}
void endHandleRpcRequestIndirect(
const std::string& asyncHandle,
const core::Error& executeError,
json::JsonRpcResponse* pJsonRpcResponse)
{
json::JsonRpcResponse temp;
json::JsonRpcResponse& jsonRpcResponse =
pJsonRpcResponse ? *pJsonRpcResponse : temp;
BOOST_ASSERT(!jsonRpcResponse.hasAfterResponse());
if (executeError)
{
jsonRpcResponse.setError(executeError);
}
json::Object value;
value["handle"] = asyncHandle;
value["response"] = jsonRpcResponse.getRawResponse();
ClientEvent evt(client_events::kAsyncCompletion, value);
module_context::enqueClientEvent(evt);
}
void handleRpcRequest(const core::json::JsonRpcRequest& request,
boost::shared_ptr<HttpConnection> ptrConnection,
ConnectionType connectionType)
{
// record the time just prior to execution of the event
// (so we can determine if any events were added during execution)
using namespace boost::posix_time;
ptime executeStartTime = microsec_clock::universal_time();
// execute the method
json::JsonRpcAsyncMethods::const_iterator it =
s_jsonRpcMethods.find(request.method);
if (it != s_jsonRpcMethods.end())
{
std::pair<bool, json::JsonRpcAsyncFunction> reg = it->second;
json::JsonRpcAsyncFunction handlerFunction = reg.second;
if (reg.first)
{
// direct return
handlerFunction(request,
boost::bind(endHandleRpcRequestDirect,
ptrConnection,
executeStartTime,
_1,
_2));
}
else
{
// indirect return (asyncHandle style)
std::string handle = core::system::generateUuid(true);
json::JsonRpcResponse response;
response.setAsyncHandle(handle);
response.setField(kEventsPending, "false");
ptrConnection->sendJsonRpcResponse(response);
handlerFunction(request,
boost::bind(endHandleRpcRequestIndirect,
handle,
_1,
_2));
}
}
else
{
Error executeError = Error(json::errc::MethodNotFound, ERROR_LOCATION);
executeError.addProperty("method", request.method);
// we need to know about these because they represent unexpected
// application states
LOG_ERROR(executeError);
endHandleRpcRequestDirect(ptrConnection, executeStartTime, executeError, NULL);
}
}
bool isMethod(const std::string& uri, const std::string& method)
{
return boost::algorithm::ends_with(uri, method);
}
bool isMethod(boost::shared_ptr<HttpConnection> ptrConnection,
const std::string& method)
{
return isMethod(ptrConnection->request().uri(), method);
}
bool isJsonRpcRequest(boost::shared_ptr<HttpConnection> ptrConnection)
{
return boost::algorithm::starts_with(ptrConnection->request().uri(),
"/rpc/");
}
bool isWaitForMethodUri(const std::string& uri)
{
BOOST_FOREACH(const std::string& methodName, s_waitForMethodNames)
{
if (isMethod(uri, methodName))
return true;
}
return false;
}
bool parseAndValidateJsonRpcConnection(
boost::shared_ptr<HttpConnection> ptrConnection,
json::JsonRpcRequest* pJsonRpcRequest)
{
// attempt to parse the request into a json-rpc request
Error error = json::parseJsonRpcRequest(ptrConnection->request().body(),
pJsonRpcRequest);
if (error)
{
ptrConnection->sendJsonRpcError(error);
return false;
}
// check for invalid client id
if (pJsonRpcRequest->clientId != session::persistentState().activeClientId())
{
Error error(json::errc::InvalidClientId, ERROR_LOCATION);
ptrConnection->sendJsonRpcError(error);
return false;
}
// check for old client version
if ( (pJsonRpcRequest->version > 0) &&
(s_version > pJsonRpcRequest->version) )
{
Error error(json::errc::InvalidClientVersion, ERROR_LOCATION);
ptrConnection->sendJsonRpcError(error);
return false;
}
// got through all of the validation, return true
return true;
}
void endHandleConnection(boost::shared_ptr<HttpConnection> ptrConnection,
ConnectionType connectionType,
http::Response* pResponse)
{
ptrConnection->sendResponse(*pResponse);
if (!s_rProcessingInput)
detectChanges(module_context::ChangeSourceURI);
}
void handleConnection(boost::shared_ptr<HttpConnection> ptrConnection,
ConnectionType connectionType)
{
// check for a uri handler registered by a module
const http::Request& request = ptrConnection->request();
std::string uri = request.uri();
http::UriAsyncHandlerFunction uriHandler = s_uriHandlers.handlerFor(uri);
if (uriHandler) // uri handler
{
// r code may execute - ensure session is initialized
ensureSessionInitialized();
uriHandler(request, boost::bind(endHandleConnection,
ptrConnection,
connectionType,
_1));
}
else if (isJsonRpcRequest(ptrConnection)) // check for json-rpc
{
// r code may execute - ensure session is initialized
ensureSessionInitialized();
// attempt to parse & validate
json::JsonRpcRequest jsonRpcRequest;
if (parseAndValidateJsonRpcConnection(ptrConnection, &jsonRpcRequest))
{
// quit_session: exit process
if (jsonRpcRequest.method == kQuitSession)
{
// see whether we should save the workspace
bool saveWorkspace = true;
std::string switchToProject;
Error error = json::readParams(jsonRpcRequest.params,
&saveWorkspace,
&switchToProject) ;
if (error)
LOG_ERROR(error);
// note switch to project
if (!switchToProject.empty())
{
session::projects::projectContext().setNextSessionProject(
switchToProject);
}
// acknowledge request & quit session
ptrConnection->sendJsonRpcResponse();
r::session::quit(saveWorkspace); // does not return
}
// interrupt
else if ( jsonRpcRequest.method == kInterrupt )
{
// Discard any buffered input
while (!s_consoleInputBuffer.empty())
s_consoleInputBuffer.pop();
// aknowledge request
ptrConnection->sendJsonRpcResponse();
// only accept interrupts while R is processing input
if ( s_rProcessingInput )
r::exec::setInterruptsPending(true);
}
// other rpc method, handle it
else
{
jsonRpcRequest.isBackgroundConnection =
(connectionType == BackgroundConnection);
handleRpcRequest(jsonRpcRequest, ptrConnection, connectionType);
}
}
}
else if (s_defaultUriHandler)
{
http::Response response;
s_defaultUriHandler(request, &response);
ptrConnection->sendResponse(response);
}
else
{
http::Response response;
response.setError(http::status::NotFound, request.uri() + " not found");
ptrConnection->sendResponse(response);
}
}
// fork state
boost::thread::id s_mainThreadId;
bool s_wasForked = false;
// fork handlers (only applicatable to Unix platforms)
#ifndef _WIN32
void prepareFork()
{
// only detect forks from the main thread (since we are going to be
// calling into non-threadsafe code). this is ok because fork
// detection is meant to handle forks that don't exec (and thus
// continue running R code). only the main thread will ever do this
if (boost::this_thread::get_id() != s_mainThreadId)
return;
}
void atForkParent()
{
if (boost::this_thread::get_id() != s_mainThreadId)
return;
}
void atForkChild()
{
s_wasForked = true;
}
void setupForkHandlers()
{
int rc = ::pthread_atfork(prepareFork, atForkParent, atForkChild);
if (rc != 0)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
}
#else
void setupForkHandlers()
{
}
#endif
void polledEventHandler()
{
// if R is getting called after a fork this is likely multicore or
// some other parallel computing package that uses fork. in this
// case be defensive by shutting down as many things as we can
// which might cause mischief in the child process
if (s_wasForked)
{
// no more polled events
r::session::event_loop::permanentlyDisablePolledEventHandler();
// done
return;
}
// static lastPerformed value used for throttling
using namespace boost::posix_time;
static ptime s_lastPerformed;
if (s_lastPerformed.is_not_a_date_time())
s_lastPerformed = microsec_clock::universal_time();
// throttle to no more than once every 50ms
static time_duration s_intervalMs = milliseconds(50);
if (microsec_clock::universal_time() <= (s_lastPerformed + s_intervalMs))
return;
// notify modules
module_context::onBackgroundProcessing(false);
// set last performed (should be set after calling onBackgroundProcessing so
// that long running background processing handlers can't overflow the 50ms
// interval between background processing invocations)
s_lastPerformed = microsec_clock::universal_time();
// check for a pending connections only while R is processing
// (otherwise we'll handle them directly in waitForMethod)
if (s_rProcessingInput)
{
// check the uri of the next connection
std::string nextConnectionUri =
httpConnectionListener().mainConnectionQueue().peekNextConnectionUri();
// if the uri is empty or if it one of our special waitForMethod calls
// then bails so that the waitForMethod logic can handle it
if (nextConnectionUri.empty() || isWaitForMethodUri(nextConnectionUri))
return;
// attempt to deque a connection and handle it. for now we just handle
// a single connection at a time (we'll be called back again if processing
// continues)
boost::shared_ptr<HttpConnection> ptrConnection =
httpConnectionListener().mainConnectionQueue().dequeConnection();
if (ptrConnection)
{
if ( isMethod(ptrConnection, kClientInit) )
{
// client_init means the user is attempting to reload the browser
// in the middle of a computation. process client_init and post
// a busy event as our initFunction
using namespace session::module_context;
ClientEvent busyEvent(client_events::kBusy, true);
handleClientInit(boost::bind(enqueClientEvent, busyEvent),
ptrConnection);
}
else
{
handleConnection(ptrConnection, BackgroundConnection);
}
}
}
}
bool suspendSession(bool force)
{
// need to make sure the global environment is loaded before we
// attemmpt to save it!
r::session::ensureDeserialized();
// perform the suspend (does not return if successful)
return r::session::suspend(force);
}
void suspendIfRequested(const boost::function<bool()>& allowSuspend)
{
// never suspend in desktop mode
if (session::options().programMode() == kSessionProgramModeDesktop)
return;
// check for forced suspend request
if (s_forceSuspend)
{
// reset flag (if for any reason we fail we don't want to keep
// hammering away on the failure case)
s_forceSuspend = false;
// did this force suspend interrupt R?
if (s_forceSuspendInterruptedR)
{
// reset flag
s_forceSuspendInterruptedR = false;
// notify user
r::session::reportAndLogWarning(
"Session forced to suspend due to system upgrade, restart, maintenance, "
"or other issue. Your session data was saved however running "
"computations may have been interrupted.");
}
// execute the forced suspend (does not return)
suspendSession(true);
}
// cooperative suspend request
else if (s_suspendRequested && allowSuspend())
{
// reset flag (if for any reason we fail we don't want to keep
// hammering away on the failure case)
s_suspendRequested = false;
// attempt suspend -- if this succeeds it doesn't return; if it fails
// errors will be logged/reported internally and we will move on
suspendSession(false);
}
}
bool haveRunningChildren()
{
return module_context::processSupervisor().hasRunningChildren() ||
modules::authoring::hasRunningChildren();
}
bool canSuspend(const std::string& prompt)
{
return !haveRunningChildren() && r::session::isSuspendable(prompt);
}
bool isTimedOut(const boost::posix_time::ptime& timeoutTime)
{
// never time out in desktop mode
if (session::options().programMode() == kSessionProgramModeDesktop)
return false;
if (timeoutTime.is_not_a_date_time())
return false;
else
return boost::posix_time::second_clock::universal_time() > timeoutTime;
}