slicerNetwork.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. self.mode="http"
  185. if dt.has_key('SSL'):
  186. self.configureSSL(
  187. dt['SSL']['user'],
  188. dt['SSL']['key'],
  189. dt['SSL']['keyPwd'],
  190. dt['SSL']['ca']
  191. )
  192. self.hostname=dt['host']
  193. self.auth_name=dt['labkey']['user']
  194. self.auth_pass=dt['labkey']['password']
  195. #cj in opener contains the cookies
  196. def get(self,url):
  197. debug=False
  198. if debug:
  199. print("GET: {0}").format(url)
  200. print("as {0}").format(self.auth_name)
  201. r=urllib2.Request(url)
  202. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  203. r.add_header("Authorization", "Basic %s" % base64string)
  204. return self.opener.open(r)
  205. #f contains json as a return value
  206. def post(self,url,data):
  207. r=urllib2.Request(url)
  208. #makes it a post
  209. r.add_data(data)
  210. r.add_header("Content-Type","application/json")
  211. #add csrf
  212. csrf=self.getCSRF()
  213. r.add_header("X-LABKEY-CSRF",csrf)
  214. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  215. r.add_header("Authorization", "Basic %s" % base64string)
  216. print("{}: {}").format(r.get_method(),r.get_full_url())
  217. print("data: {}").format(r.get_data())
  218. print("Content-Type: {}").format(r.get_header('Content-Type'))
  219. try:
  220. return self.opener.open(r)
  221. except urllib2.HTTPError as e:
  222. print e.code
  223. print e.read()
  224. return e
  225. #f contains json as a return value
  226. def put(self,url,data):
  227. print("PUT: {0}").format(url)
  228. r=MethodRequest(url.encode('utf-8'),method="PUT")
  229. #makes it a post
  230. r.add_data(data)
  231. r.add_header("content-type","application/octet-stream")
  232. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  233. r.add_header("Authorization", "Basic %s" % base64string)
  234. return self.opener.open(r)
  235. #f contains json as a return value
  236. def getCSRF(self):
  237. url=self.GetLabkeyUrl()+'/login/whoAmI.view'
  238. jsonData=json.load(self.get(url))
  239. return jsonData["CSRF"]
  240. def remoteDirExists(self,url):
  241. status,dirs=self.listRemoteDir(url);
  242. return status
  243. def mkdir(self,remoteDir):
  244. if self.remoteDirExists(remoteDir):
  245. return False
  246. r=MethodRequest(remoteDir,method="MKCOL")
  247. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  248. r.add_header("Authorization", "Basic %s" % base64string)
  249. try:
  250. f=self.opener.open(r)
  251. except:
  252. print("Error: Failed MKCOL {}").format(remoteDir)
  253. return False
  254. return True
  255. def mkdirs(self,remoteDir):
  256. labkeyPath=self.GetLabkeyPathFromRemotePath(remoteDir)
  257. s=0
  258. while True:
  259. s1=labkeyPath.find('/',s)
  260. if s1<0:
  261. break
  262. path=labkeyPath[0:s1]
  263. remotePath=self.GetLabkeyWebdavUrl()+'/'+path
  264. dirExists=self.remoteDirExists(remotePath)
  265. if not dirExists:
  266. if not self.mkdir(remotePath):
  267. return False
  268. s=s1+1
  269. return self.mkdir(remoteDir)
  270. def rmdir(self,remoteDir):
  271. if not self.remoteDirExists(remoteDir):
  272. return True
  273. r=MethodRequest(remoteDir,method="DELETE")
  274. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  275. r.add_header("Authorization", "Basic %s" % base64string)
  276. try:
  277. f=self.opener.open(r)
  278. except:
  279. print("Error: Failed DELETE {}").format(remoteDir)
  280. return False
  281. return True
  282. def listDir(self,dir):
  283. print("Listing for {0}").format(dir)
  284. dirUrl=self.GetLabkeyWebdavUrl()+"/"+dir
  285. status,dirs=self.listRemoteDir(dirUrl)
  286. return dirs
  287. def isDir(self, remotePath):
  288. #print "isDir: {}".format(remotePath)
  289. r=MethodRequest(remotePath,method="PROPFIND")
  290. PROPFIND=u"""<?xml version="1.0" encoding="utf-8"?>\n
  291. <a:propfind xmlns:a="DAV:">\n
  292. <a:prop>\n
  293. <a:resourcetype/>\n
  294. </a:prop>\n
  295. </a:propfind>"""
  296. r.add_header('content-type','text/xml; charset="utf-8"')
  297. r.add_header('content-length',str(len(PROPFIND)))
  298. r.add_header('Depth','0')
  299. r.add_data(PROPFIND)
  300. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  301. r.add_header("Authorization", "Basic %s" % base64string)
  302. print("PROPFIND: {0}").format(remotePath)
  303. try:
  304. f=self.opener.open(r)
  305. except:
  306. return False
  307. tree=ET.XML(f.read())
  308. try:
  309. rps=tree.find('{DAV:}response').find('{DAV:}propstat')
  310. rps=rps.find('{DAV:}prop')
  311. rps=rps.find('{DAV:}resourcetype').find('{DAV:}collection')
  312. if rps != None:
  313. return True
  314. else:
  315. return False
  316. except:
  317. return False
  318. def listRemoteDir(self,dirUrl):
  319. r=MethodRequest(dirUrl,method="PROPFIND")
  320. PROPFIND=u"""<?xml version="1.0" encoding="utf-8"?>\n
  321. <propfind xmlns="DAV:">\n
  322. <prop>\n
  323. <getetag/>\n
  324. </prop>\n
  325. </propfind>"""
  326. r.add_header('content-type','text/xml; charset="utf-8"')
  327. r.add_header('content-length',str(len(PROPFIND)))
  328. r.add_header('Depth','1')
  329. r.add_data(PROPFIND)
  330. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  331. r.add_header("Authorization", "Basic %s" % base64string)
  332. print("PROPFIND: {0}").format(dirUrl)
  333. dirs=[]
  334. try:
  335. f=self.opener.open(r)
  336. except:
  337. return False,dirs
  338. tree=ET.XML(f.read())
  339. rps=tree.findall('{DAV:}response')
  340. for r in rps:
  341. hr=r.find('{DAV:}href')
  342. dirent=hr.text
  343. dirent=re.sub('/labkey/_webdav/','',dirent)
  344. dirs.append(dirent)
  345. del dirs[0]
  346. return True,dirs
  347. def toRelativePath(self,dirs):
  348. flist1=[]
  349. for d in dirs:
  350. if d[-1]=='/':
  351. d=d[:-1]
  352. if d.rfind('/')>-1:
  353. d=d[d.rfind('/')+1:]
  354. flist1.append(d)
  355. return flist1
  356. def readFile(self, serverUrl, path):
  357. dirUrl=serverUrl+"/labkey/_webdav"+"/"+path
  358. f=self.get(dirUrl)
  359. return StringIO.StringIO(f.read())
  360. def uploadFile(self,localPath):
  361. #get upstream directories sorted out
  362. labkeyPath=self.GetLabkeyPathFromLocalPath(localPath)
  363. if labkeyPath=="NULL":
  364. errorCode="Failed to upload {}. Potential incorrect location"
  365. errorCode+=". Should be in labkeyCache!"
  366. print(errorCode.format(localPath))
  367. return False
  368. labkeyDir=labkeyPath[0:labkeyPath.rfind('/')]
  369. remoteDir=self.GetLabkeyWebdavUrl()+'/'+labkeyDir
  370. if not self.remoteDirExists(remoteDir):
  371. if not self.mkdirs(remoteDir):
  372. errorCode="UploadFile: Could not create directory {}"
  373. print(errorCode.format(remoteDir))
  374. return False
  375. #make an URL request
  376. with open(localPath, 'r') as f:
  377. data=f.read()
  378. remotePath=self.GetLabkeyWebdavUrl()+'/'+labkeyPath
  379. self.put(remotePath,data)
  380. def copyFileToRemote(self,localPath, remotePath):
  381. #get upstream directories sorted out
  382. labkeyDir=os.path.dirname(remotePath)
  383. if not self.remoteDirExists(labkeyDir):
  384. if not self.mkdirs(labkeyDir):
  385. errorCode="UploadFile: Could not create directory {}"
  386. print(errorCode.format(labkeyDir))
  387. return False
  388. #make an URL request
  389. if (self.isDir(remotePath)):
  390. remotePath=remotePath+'/'+os.path.basename(localPath)
  391. with open(localPath, 'r') as f:
  392. data=f.read()
  393. self.put(remotePath,data)
  394. def loadDir(self, path):
  395. #dirURL=serverUrl+"/labkey/_webdav/"+path
  396. files=self.listDir(path)
  397. fdir="NONE"
  398. for f in files:
  399. #returns local path
  400. try:
  401. fdir=os.path.dirname(self.GetFile(f))
  402. except:
  403. #fails if there is a subdirectory; go recursively
  404. print("self.readDir(f) not implemented")
  405. return fdir
  406. def loadDataset(self,project,dataset):
  407. url=self.GetLabkeyUrl()+'/'+project
  408. url+='/query-selectRows.api?schemaName=study&query.queryName='+dataset
  409. return json.load(self.get(url))
  410. def filterDataset(self,project,dataset,variable,value,oper="eq"):
  411. debug=True
  412. url=self.GetLabkeyUrl()+'/'+project
  413. url+='/query-selectRows.api?schemaName=study&query.queryName='+dataset
  414. url+="&query."+variable+"~"+oper+"="+value
  415. if debug:
  416. print("Sending {}").format(url)
  417. return json.load(self.get(url))
  418. def modifyDataset(self,method,project,dataset,rows):
  419. #method can be insert or update
  420. data={}
  421. data['schemaName']='study'
  422. data['queryName']=dataset
  423. data['rows']=rows
  424. url=self.GetLabkeyUrl()+'/'+project
  425. url+='/query-'+method+'Rows.api?'
  426. return self.post(url,json.dumps(data))