slicerNetwork.py 16 KB

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