slicerNetwork.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. import qt
  2. import urllib2
  3. import ssl
  4. import cookielib
  5. import xml.etree.ElementTree as ET
  6. import re
  7. import StringIO
  8. import slicer
  9. import shutil
  10. import distutils
  11. import os
  12. import base64
  13. import json
  14. #see https://gist.github.com/logic/2715756, allow requests to do Put
  15. class MethodRequest(urllib2.Request):
  16. def __init__(self, *args, **kwargs):
  17. if 'method' in kwargs:
  18. self._method = kwargs['method']
  19. del kwargs['method']
  20. else:
  21. self._method = None
  22. return urllib2.Request.__init__(self, *args, **kwargs)
  23. def get_method(self, *args, **kwargs):
  24. if self._method is not None:
  25. return self._method
  26. return urllib2.Request.get_method(self, *args, **kwargs)
  27. class slicerNetwork(slicer.ScriptedLoadableModule.ScriptedLoadableModule):
  28. def __init__(self, parent):
  29. slicer.ScriptedLoadableModule.ScriptedLoadableModule.__init__(self,parent)
  30. self.parent.title="slicerNetwork"
  31. pass
  32. class labkeyURIHandler(slicer.vtkURIHandler):
  33. def __init__(self):
  34. slicer.vtkURIHandler.__init__(self)
  35. self.className="labkeyURIHandler"
  36. slicer.mrmlScene.AddURIHandler(self)
  37. try:
  38. fhome=os.environ["HOME"]
  39. except:
  40. #in windows, the variable is called HOMEPATH
  41. fhome=os.environ['HOMEDRIVE']+os.environ['HOMEPATH']
  42. self.localCacheDirectory=os.path.join(fhome,"labkeyCache")
  43. self.configDir=os.path.join(fhome,".labkey")
  44. self.mode="http"
  45. #try initializing network from default config file, if found
  46. self.initFromConfig()
  47. def CanHandleURI(self,uri):
  48. print("labkeyURIHandler::CanHandleURI({0})").format(uri)
  49. if uri.find('labkey://')==0:
  50. return 1
  51. return 0
  52. def GetClassName(self):
  53. return self.className
  54. def GetHostName(self):
  55. return self.hostname
  56. def SetHostName(self,host):
  57. self.hostname=host
  58. def SetLocalCahceDirectory(self,dir):
  59. self.localCacheDirectory=dir
  60. def GetLocalCacheDirectory(self):
  61. return self.localCacheDirectory
  62. def GetLabkeyUrl(self):
  63. return self.hostname+"/labkey"
  64. def GetLabkeyWebdavUrl(self):
  65. return self.GetLabkeyUrl()+"/_webdav"
  66. def GetLocalPath(self,source):
  67. debug=False
  68. relativePath=re.sub('labkey://','',source)
  69. sp=os.sep.encode('string-escape')
  70. if debug:
  71. print("Substituting / with {0} in {1}").format(sp,relativePath)
  72. relativePath=re.sub('/',sp,relativePath)
  73. return os.path.join(self.localCacheDirectory,relativePath)
  74. def GetRemotePath(self,source):
  75. return self.GetLabkeyWebdavUrl()+"/"+GetLabkeyPathFromLocalPath(source)
  76. def GetLabkeyPathFromLocalPath(self,f):
  77. #report it with URL separator, forward-slash
  78. if f.find(self.localCacheDirectory)<-1:
  79. print("Localpath misformation. Exiting")
  80. return "NULL"
  81. dest=re.sub(self.localCacheDirectory,'',f)
  82. #leaves /ContextPath/%40files/subdirectory_list/files
  83. #remove first separator
  84. sp=os.sep.encode('string-escape')
  85. if dest[0]==sp:
  86. dest=dest[1:len(dest)]
  87. return re.sub(sp,'/',dest)
  88. def GetLabkeyPathFromRemotePath(self,f):
  89. #used to query labkey stuff, so URL separator is used
  90. f=re.sub('labkey://','',f)
  91. f=re.sub(self.GetLabkeyWebdavUrl(),'',f)
  92. if f[0]=='/':
  93. f=f[1:len(f)]
  94. return f;
  95. def GetFile(self,source):
  96. # check for file in cache. If available, use, if not, download
  97. localPath=self.GetLocalPath(source)
  98. if os.path.isfile(localPath):
  99. return localPath
  100. self.StageFileRead(source,localPath)
  101. return localPath
  102. def StageFileRead(self,source,dest):
  103. debug=False
  104. if debug:
  105. print("labkeyURIHandler::StageFileRead({0},{1})").format(source,dest)
  106. labkeyPath=re.sub('labkey://','',source)
  107. remote=self.readFile(self.hostname,labkeyPath)
  108. #make all necessary directories
  109. path=os.path.dirname(dest)
  110. if not os.path.isdir(path):
  111. os.makedirs(path)
  112. local=open(dest,'wb')
  113. #make sure we are at the begining of the file
  114. #check file size
  115. if debug:
  116. remote.seek(0,2)
  117. sz=remote.tell()
  118. print("Remote size: {0}").format(sz)
  119. remote.seek(0)
  120. shutil.copyfileobj(remote,local)
  121. if debug:
  122. print("Local size: {0}").format(local.tell())
  123. local.close()
  124. def StageFileWrite(self,source,dest):
  125. print("labkeyURIHandler::StageFileWrite({0},{1}) not implemented yet").format(
  126. source,dest)
  127. def fileTypesAvailable(self):
  128. return ('VolumeFile','SegmentationFile','TransformFile')
  129. #mimic slicer.util.loadNodeFromFile
  130. # def loadNodeFromFile(self, filename, filetype, properties={}, returnNode=False):
  131. # #this is the only relevant part - file must be downloaded to cache
  132. # localPath=self.GetFile(filename)
  133. # slicer.util.loadNodeFromFile(localPath,filetype,properties,returnNode)
  134. # #remove retrieved file
  135. # try:
  136. # if not(properties['keepCachedFile']) :
  137. # os.remove(localPath)
  138. # except:
  139. # pass
  140. # def loadVolume(self,filename, properties={}, returnNode=False):
  141. # filetype = 'VolumeFile'
  142. # #redirect to self.loadNodeFromFile first to get the cached file
  143. # return self.loadNodeFromFile(filename,filetype, properties,returnNode)
  144. #
  145. # def loadSegmentation(self,filename,properties={},returnNode=False):
  146. # filetype='SegmentationFile'
  147. # #redirect to self.loadNodeFromFile first to get the cached file
  148. # return self.loadNodeFromFile(filename,filetype, properties,returnNode)
  149. # #add others if needed
  150. ## setup & initialization routines
  151. def configureSSL(self,cert,key,pwd,cacert):
  152. #do this first
  153. try:
  154. self.ctx=ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  155. self.ctx.load_cert_chain(cert,key,pwd)
  156. self.ctx.verify_mode=ssl.CERT_REQUIRED
  157. self.ctx.load_verify_locations(cacert)
  158. except ssl.SSLError as err:
  159. print(" Failed to configure SSL: {0}").format(str(err))
  160. self.mode="https"
  161. def initRemote(self):
  162. if self.mode=="https":
  163. http_handler=urllib2.HTTPSHandler(context=self.ctx)
  164. if self.mode=="http":
  165. http_handler=urllib2.HTTPHandler()
  166. #cookie part
  167. cj=cookielib.CookieJar()
  168. cookie_handler=urllib2.HTTPCookieProcessor(cj)
  169. self.opener=urllib2.build_opener(http_handler,cookie_handler)
  170. def initFromConfig(self):
  171. path=os.path.join(self.configDir,"Remote.json")
  172. try:
  173. self.parseConfig(path)
  174. except OSError:
  175. return
  176. self.initRemote()
  177. def parseConfig(self,fname):
  178. try:
  179. f=open(fname)
  180. except OSError as e:
  181. print("Confgiuration error: OS error({0}): {1}").format(e.errno, e.strerror)
  182. raise
  183. dt=json.load(f)
  184. if dt.has_key('SSL'):
  185. self.configureSSL(
  186. dt['SSL']['user'],
  187. dt['SSL']['key'],
  188. dt['SSL']['keyPwd'],
  189. dt['SSL']['ca']
  190. )
  191. self.hostname=dt['host']
  192. self.auth_name=dt['labkey']['user']
  193. self.auth_pass=dt['labkey']['password']
  194. #cj in opener contains the cookies
  195. def get(self,url):
  196. debug=False
  197. if debug:
  198. print("GET: {0}").format(url)
  199. print("as {0}").format(self.auth_name)
  200. r=urllib2.Request(url)
  201. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  202. r.add_header("Authorization", "Basic %s" % base64string)
  203. try:
  204. return self.opener.open(r)
  205. #f contains json as a return value
  206. except urllib2.HTTPError as e:
  207. print e.code
  208. print e.read()
  209. return e
  210. def post(self,url,data):
  211. r=urllib2.Request(url)
  212. #makes it a post
  213. r.add_data(data)
  214. r.add_header("Content-Type","application/json")
  215. #add csrf
  216. csrf=self.getCSRF()
  217. r.add_header("X-LABKEY-CSRF",csrf)
  218. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  219. r.add_header("Authorization", "Basic %s" % base64string)
  220. print("{}: {}").format(r.get_method(),r.get_full_url())
  221. print("data: {}").format(r.get_data())
  222. print("Content-Type: {}").format(r.get_header('Content-Type'))
  223. try:
  224. return self.opener.open(r)
  225. except urllib2.HTTPError as e:
  226. print e.code
  227. print e.read()
  228. return e
  229. #f contains json as a return value
  230. def put(self,url,data):
  231. print("PUT: {0}").format(url)
  232. r=MethodRequest(url.encode('utf-8'),method="PUT")
  233. #makes it a post
  234. r.add_data(data)
  235. r.add_header("content-type","application/octet-stream")
  236. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  237. r.add_header("Authorization", "Basic %s" % base64string)
  238. return self.opener.open(r)
  239. #f contains json as a return value
  240. def getCSRF(self):
  241. url=self.GetLabkeyUrl()+'/login/whoAmI.view'
  242. jsonData=json.load(self.get(url))
  243. return jsonData["CSRF"]
  244. def remoteDirExists(self,url):
  245. status,dirs=self.listRemoteDir(url);
  246. return status
  247. def mkdir(self,remoteDir):
  248. if self.remoteDirExists(remoteDir):
  249. return False
  250. r=MethodRequest(remoteDir,method="MKCOL")
  251. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  252. r.add_header("Authorization", "Basic %s" % base64string)
  253. try:
  254. f=self.opener.open(r)
  255. except:
  256. print("Error: Failed MKCOL {}").format(remoteDir)
  257. return False
  258. return True
  259. def mkdirs(self,remoteDir):
  260. labkeyPath=self.GetLabkeyPathFromRemotePath(remoteDir)
  261. s=0
  262. while True:
  263. s1=labkeyPath.find('/',s)
  264. if s1<0:
  265. break
  266. path=labkeyPath[0:s1]
  267. remotePath=self.GetLabkeyWebdavUrl()+'/'+path
  268. dirExists=self.remoteDirExists(remotePath)
  269. if not dirExists:
  270. if not self.mkdir(remotePath):
  271. return False
  272. s=s1+1
  273. return self.mkdir(remoteDir)
  274. def rmdir(self,remoteDir):
  275. if not self.remoteDirExists(remoteDir):
  276. return True
  277. r=MethodRequest(remoteDir,method="DELETE")
  278. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  279. r.add_header("Authorization", "Basic %s" % base64string)
  280. try:
  281. f=self.opener.open(r)
  282. except:
  283. print("Error: Failed DELETE {}").format(remoteDir)
  284. return False
  285. return True
  286. def listDir(self,dir):
  287. print("Listing for {0}").format(dir)
  288. dirUrl=self.GetLabkeyWebdavUrl()+"/"+dir
  289. status,dirs=self.listRemoteDir(dirUrl)
  290. return dirs
  291. def isDir(self, remotePath):
  292. #print "isDir: {}".format(remotePath)
  293. r=MethodRequest(remotePath,method="PROPFIND")
  294. PROPFIND=u"""<?xml version="1.0" encoding="utf-8"?>\n
  295. <a:propfind xmlns:a="DAV:">\n
  296. <a:prop>\n
  297. <a:resourcetype/>\n
  298. </a:prop>\n
  299. </a:propfind>"""
  300. r.add_header('content-type','text/xml; charset="utf-8"')
  301. r.add_header('content-length',str(len(PROPFIND)))
  302. r.add_header('Depth','0')
  303. r.add_data(PROPFIND)
  304. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  305. r.add_header("Authorization", "Basic %s" % base64string)
  306. print("PROPFIND: {0}").format(remotePath)
  307. try:
  308. f=self.opener.open(r)
  309. except:
  310. return False
  311. tree=ET.XML(f.read())
  312. try:
  313. rps=tree.find('{DAV:}response').find('{DAV:}propstat')
  314. rps=rps.find('{DAV:}prop')
  315. rps=rps.find('{DAV:}resourcetype').find('{DAV:}collection')
  316. if rps != None:
  317. return True
  318. else:
  319. return False
  320. except:
  321. return False
  322. def listRemoteDir(self,dirUrl):
  323. r=MethodRequest(dirUrl,method="PROPFIND")
  324. PROPFIND=u"""<?xml version="1.0" encoding="utf-8"?>\n
  325. <propfind xmlns="DAV:">\n
  326. <prop>\n
  327. <getetag/>\n
  328. </prop>\n
  329. </propfind>"""
  330. r.add_header('content-type','text/xml; charset="utf-8"')
  331. r.add_header('content-length',str(len(PROPFIND)))
  332. r.add_header('Depth','1')
  333. r.add_data(PROPFIND)
  334. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  335. r.add_header("Authorization", "Basic %s" % base64string)
  336. print("PROPFIND: {0}").format(dirUrl)
  337. dirs=[]
  338. try:
  339. f=self.opener.open(r)
  340. except:
  341. return False,dirs
  342. tree=ET.XML(f.read())
  343. rps=tree.findall('{DAV:}response')
  344. for r in rps:
  345. hr=r.find('{DAV:}href')
  346. dirent=hr.text
  347. dirent=re.sub('/labkey/_webdav/','',dirent)
  348. dirs.append(dirent)
  349. del dirs[0]
  350. return True,dirs
  351. def toRelativePath(self,dirs):
  352. flist1=[]
  353. for d in dirs:
  354. if d[-1]=='/':
  355. d=d[:-1]
  356. if d.rfind('/')>-1:
  357. d=d[d.rfind('/')+1:]
  358. flist1.append(d)
  359. return flist1
  360. def readFile(self, serverUrl, path):
  361. dirUrl=serverUrl+"/labkey/_webdav"+"/"+path
  362. f=self.get(dirUrl)
  363. return StringIO.StringIO(f.read())
  364. def uploadFile(self,localPath):
  365. #get upstream directories sorted out
  366. labkeyPath=self.GetLabkeyPathFromLocalPath(localPath)
  367. if labkeyPath=="NULL":
  368. errorCode="Failed to upload {}. Potential incorrect location"
  369. errorCode+=". Should be in labkeyCache!"
  370. print(errorCode.format(localPath))
  371. return False
  372. labkeyDir=labkeyPath[0:labkeyPath.rfind('/')]
  373. remoteDir=self.GetLabkeyWebdavUrl()+'/'+labkeyDir
  374. if not self.remoteDirExists(remoteDir):
  375. if not self.mkdirs(remoteDir):
  376. errorCode="UploadFile: Could not create directory {}"
  377. print(errorCode.format(remoteDir))
  378. return False
  379. #make an URL request
  380. with open(localPath, 'r') as f:
  381. data=f.read()
  382. remotePath=self.GetLabkeyWebdavUrl()+'/'+labkeyPath
  383. self.put(remotePath,data)
  384. def copyFileToRemote(self,localPath, remotePath):
  385. #get upstream directories sorted out
  386. labkeyDir=os.path.dirname(remotePath)
  387. if not self.remoteDirExists(labkeyDir):
  388. if not self.mkdirs(labkeyDir):
  389. errorCode="UploadFile: Could not create directory {}"
  390. print(errorCode.format(labkeyDir))
  391. return False
  392. #make an URL request
  393. if (self.isDir(remotePath)):
  394. remotePath=remotePath+'/'+os.path.basename(localPath)
  395. with open(localPath, 'r') as f:
  396. data=f.read()
  397. self.put(remotePath,data)
  398. def loadDir(self, path):
  399. #dirURL=serverUrl+"/labkey/_webdav/"+path
  400. files=self.listDir(path)
  401. fdir="NONE"
  402. for f in files:
  403. #returns local path
  404. try:
  405. fdir=os.path.dirname(self.GetFile(f))
  406. except:
  407. #fails if there is a subdirectory; go recursively
  408. print("self.readDir(f) not implemented")
  409. return fdir
  410. def loadDataset(self,project,dataset):
  411. url=self.GetLabkeyUrl()+'/'+project
  412. url+='/query-selectRows.api?schemaName=study&query.queryName='+dataset
  413. return json.load(self.get(url))
  414. def filterDataset(self,project,dataset,variable,value,oper="eq"):
  415. debug=True
  416. url=self.GetLabkeyUrl()+'/'+project
  417. url+='/query-selectRows.api?schemaName=study&query.queryName='+dataset
  418. url+="&query."+variable+"~"+oper+"="+value
  419. if debug:
  420. print("Sending {}").format(url)
  421. return json.load(self.get(url))
  422. def modifyDataset(self,method,project,dataset,rows):
  423. #method can be insert or update
  424. data={}
  425. data['schemaName']='study'
  426. data['queryName']=dataset
  427. data['rows']=rows
  428. url=self.GetLabkeyUrl()+'/'+project
  429. url+='/query-'+method+'Rows.api?'
  430. return self.post(url,json.dumps(data))