RStudio Server 环境变量LD_LIBRARY_PATH的配置

问题

在服务器上安装了一个Rstudio-server进行基于R语言的web开发。前期一路顺利,直到开发数据库模块需要用到RODBC。在加载ODBC库后,调用函数odbcConnect结果报错:

In odbcDriverConnect(“DSN=myhps;UID=hps;PWD=hps”):
[RODBC] ERROR: state 01000, code 0, message [unixODBC][Driver Manager]Can’t open lib ‘/usr/lib/libmyodbc5-5.1.5.so’ : file not found

第一印象是我的odbc装的有问题,但locate了libmyodbc5-5.1.5.so这个文件,存在。同时,发现使用ssh登录到服务器直接进入R,可以正常使用该函数没有报错。看来环境变量出错的概率比较大。
为了进一步确认,我在Rstudio-server中键入:

1
system("source ~/.bashrc;Rscript ~/test.R",intern = TRUE)

其中,test.R中的内容为

1
2
library(RODBC)
odbcConnect("myhps","hps","hps")

运行成功,看来问题就是环境变量中引起的。经过排查,最终确定问题为环境变量LD_LIBRARY_PATH少了路径“/usr/local/lib”。那么下一步要做的事就是更新RStudio-server的LD_LIBRARY_PATH环境变量。 首先,我在RStudio中调用Sys.getenv(),打印出所有环境变量,其中:

1
2
"/usr/local/lib64/R/lib:/lib:/usr/local/lib64:/home/lyl/denpendence/jdk1.7.0_51/jre/lib/amd64/server" 
LD_LIBRARY_PATH

从包含的路径来看,RStudio肯定不是使用shell的方式读取.bashrc,/etc/bashrc等文件初始化环境变量(经过实验验证,的确是这样)。于是,google了下RStudio环境变量的设置方法,回答指向了如下链接:

https://support.rstudio.com/hc/communities/public/questions/203035636-global-environment-variable https://stat.ethz.ch/R-manual/R-patched/library/base/html/Startup.html

即通过在文件Renviron.site,Renviron.Rprofile中设置。起初,文档没看太仔细,直接用shell的语法设置环境变量了,但RStudio对环境变量设置有自己的一套语法,这里要注意:

Lines in a site or user environment file should be either comment lines starting with #, or lines of the form name=value. The latter sets the environmental variable name to value, overriding an existing value. If value contains an expression of the form ${foo-bar}, the value is that of the environmental variable foo if that exists and is set to a non-empty value, otherwise bar. (If it is of the form ${foo}, the default is “”.) This construction can be nested, so bar can be of the same form (as in ${foo-${bar-blah}}). Note that the braces are essential: for example $HOME will not be interpreted.

设置ok,重启RStudio,重启session(这里要注意是重启session,而不是重新登录。Rstudio-server会帮你保存session。重启session的方法: Session->Restart R),环境变量有变化,设置成功。重新运行函数odbcConnect,还是报同样的错误。

这里之后又折腾了几个小时,最后,重读了下RStudio-server的安装配置文档https://support.rstudio.com/hc/en-us/articles/200552316-Configuring-the-Server ,发现有这么一句话:

You can add elements to the default LD_LIBRARY_PATH for R sessions (as determined by the R ldpaths script) by adding an rsession-ld-library-path entry to the server config file. This might be useful for ensuring that packages can locate external library dependencies that aren’t installed in the system standard library paths. For example: rsession-ld-library-path=/opt/local/lib:/opt/local/someapp/lib

于是我在配置文件 /etc/rstudio/rserver.conf添加相应设置 rsession-ld-library-path=/usr/local/lib 重启RStudio-server,重启session,终于成功。看来,RStudio-server的LD_LIBARAR_PATH只有在这里设置才有用,真是个反人类的配置习惯。至此,在该问题上已经花费了5个小时。这同时也提醒我们,仔细看文档是多么的重要!