slicerNetwork.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. #configuration part
  67. def configureSSL(self,cert,key,pwd,cacert):
  68. #do this first
  69. try:
  70. self.ctx=ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  71. self.ctx.load_cert_chain(cert,key,pwd)
  72. self.ctx.verify_mode=ssl.CERT_REQUIRED
  73. self.ctx.load_verify_locations(cacert)
  74. except ssl.SSLError as err:
  75. print(" Failed to configure SSL: {0}").format(str(err))
  76. self.mode="https"
  77. def initRemote(self):
  78. if self.mode=="https":
  79. http_handler=urllib2.HTTPSHandler(context=self.ctx)
  80. if self.mode=="http":
  81. http_handler=urllib2.HTTPHandler()
  82. #cookie part
  83. cj=cookielib.CookieJar()
  84. cookie_handler=urllib2.HTTPCookieProcessor(cj)
  85. self.opener=urllib2.build_opener(http_handler,cookie_handler)
  86. def initFromConfig(self):
  87. path=os.path.join(self.configDir,"Remote.json")
  88. try:
  89. self.parseConfig(path)
  90. except OSError:
  91. return
  92. self.initRemote()
  93. def parseConfig(self,fname):
  94. try:
  95. f=open(fname)
  96. except OSError as e:
  97. print("Confgiuration error: OS error({0}): {1}").format(e.errno, e.strerror)
  98. raise
  99. dt=json.load(f)
  100. self.mode="http"
  101. if dt.has_key('SSL'):
  102. self.configureSSL(
  103. dt['SSL']['user'],
  104. dt['SSL']['key'],
  105. dt['SSL']['keyPwd'],
  106. dt['SSL']['ca']
  107. )
  108. self.hostname=dt['host']
  109. self.auth_name=dt['labkey']['user']
  110. self.auth_pass=dt['labkey']['password']
  111. #path convention
  112. #localPath is a path on local filesystem. It means it has to adhere to OS
  113. #policy, especially in separators
  114. #relativePath is just the portion of the path that is equal both locally
  115. #and remotely. In relativePath, separator is according to http convention,
  116. #which equals separator in osx and *nix
  117. #labkeyPath or remotePath is the full URL to the resource,
  118. #including http-like header and all intermediate portions
  119. #the following functions convert between different notations
  120. #was GetLocalPath
  121. def GetLocalPathFromRelativePath(self,relativePath):
  122. debug=False
  123. relativePath=re.sub('labkey://','',relativePath)
  124. sp=os.sep.encode('string-escape')
  125. if debug:
  126. print("Substituting / with {0} in {1}").format(sp,relativePath)
  127. relativePath=re.sub('/',sp,relativePath)
  128. return os.path.join(self.GetLocalCacheDirectory(),relativePath)
  129. #was GetRemotePath
  130. def GetLabkeyPathFromRelativePath(self,source):
  131. return self.GetLabkeyWebdavUrl()+"/"+source
  132. #was GetLabkeyPathFromLocalPath
  133. def GetRelativePathFromLocalPath(self,f):
  134. debug=False
  135. #report it with URL separator, forward-slash
  136. if f.find(self.localCacheDirectory)<-1:
  137. print("Localpath misformation. Exiting")
  138. return "NULL"
  139. f0=re.sub('\\\\','\\\\\\\\',self.localCacheDirectory)
  140. relativePath=re.sub(re.compile(f0),'',f)
  141. if debug:
  142. print("[SEP] Relative path {}").format(relativePath)
  143. #leaves /ContextPath/%40files/subdirectory_list/files
  144. #remove first separator
  145. sp=os.path.sep
  146. f1=re.sub('\\\\','\\\\\\\\',sp)
  147. if relativePath[0]==sp:
  148. relativePath=relativePath[1:len(relativePath)]
  149. if debug:
  150. print("[SLASH] Relative path {}").format(relativePath)
  151. return re.sub(f1,'/',relativePath)
  152. #was GetLabkeyPathFromRemotePath
  153. def GetRelativePathFromLabkeyPath(self,f):
  154. #used to query labkey stuff, so URL separator is used
  155. #in old conventions, labkey://was used to tag a labkeyPath
  156. f=re.sub('labkey://','',f)
  157. f=re.sub(self.GetLabkeyWebdavUrl(),'',f)
  158. if f[0]=='/':
  159. f=f[1:len(f)]
  160. return f;
  161. #standard HTTP
  162. def get(self,url):
  163. debug=False
  164. if debug:
  165. print("GET: {0}").format(url)
  166. print("as {0}").format(self.auth_name)
  167. r=urllib2.Request(url)
  168. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  169. r.add_header("Authorization", "Basic %s" % base64string)
  170. try:
  171. return self.opener.open(r)
  172. #f contains json as a return value
  173. except urllib2.HTTPError as e:
  174. print e.code
  175. print e.read()
  176. return e
  177. def post(self,url,data):
  178. debug=False
  179. r=urllib2.Request(url)
  180. #makes it a post
  181. r.add_data(data)
  182. r.add_header("Content-Type","application/json")
  183. #add csrf
  184. csrf=self.getCSRF()
  185. r.add_header("X-LABKEY-CSRF",csrf)
  186. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  187. r.add_header("Authorization", "Basic %s" % base64string)
  188. if debug:
  189. print("{}: {}").format(r.get_method(),r.get_full_url())
  190. print("data: {}").format(r.get_data())
  191. print("Content-Type: {}").format(r.get_header('Content-Type'))
  192. try:
  193. return self.opener.open(r)
  194. except urllib2.HTTPError as e:
  195. print e.code
  196. print e.read()
  197. return e
  198. #f contains json as a return value
  199. def put(self,url,data):
  200. debug=False
  201. if debug:
  202. print("PUT: {}").format(url)
  203. r=MethodRequest(url.encode('utf-8'),method="PUT")
  204. #makes it a post
  205. r.add_data(data)
  206. print("PUT: data size: {}").format(len(data))
  207. r.add_header("content-type","application/octet-stream")
  208. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  209. r.add_header("Authorization", "Basic %s" % base64string)
  210. return self.opener.open(r)
  211. #f contains json as a return value
  212. def getCSRF(self):
  213. url=self.GetLabkeyUrl()+'/login/whoAmI.view'
  214. jsonData=json.load(self.get(url))
  215. return jsonData["CSRF"]
  216. #file manipulation routiens
  217. #was GetFile
  218. def DownloadFileToCache(self,relativePath):
  219. debug=False
  220. # check for file in cache. If available, use, if not, download
  221. localPath=self.GetLocalPathFromRelativePath(relativePath)
  222. if os.path.isfile(localPath):
  223. if debug:
  224. print("Returning localFile {}".format(localPath))
  225. return localPath
  226. if debug:
  227. print("labkeyURIHandler::DownloadFileToCache({0}->{1})").format(relativePath,localPath)
  228. #make all necessary directories LOCALLY
  229. path=os.path.dirname(localPath)
  230. if debug:
  231. print("Target directory: '{}''".format(path))
  232. if not os.path.isdir(path):
  233. os.makedirs(path)
  234. localBuffer=open(localPath,'wb')
  235. #make sure we are at the begining of the file
  236. #labkeyPath=self.GetLabkeyPathFromRelativePath(relativePath)
  237. remoteBuffer=self.readFileToBuffer(relativePath)
  238. #check file size
  239. if debug:
  240. remoteBuffer.seek(0,2)
  241. sz=remoteBuffer.tell()
  242. print("Remote size: {0}").format(sz)
  243. remoteBuffer.seek(0)
  244. shutil.copyfileobj(remoteBuffer,localBuffer)
  245. if debug:
  246. print("Local size: {0}").format(localBuffer.tell())
  247. localBuffer.close()
  248. return localPath
  249. def fileTypesAvailable(self):
  250. return ('VolumeFile','SegmentationFile','TransformFile')
  251. #mimic slicer.util.loadNodeFromFile
  252. def loadNode(self, relativeName, filetype, properties={}, returnNode=False):
  253. #this is the only relevant part - file must be downloaded to cache
  254. #labkeyName is just the relative part (from labkey onwards)
  255. localPath=self.DownloadFileToCache(relativeName)
  256. print localPath
  257. slicer.util.loadNodeFromFile(localPath,filetype,properties,returnNode)
  258. # #remove retrieved file
  259. def remoteDirExists(self,url):
  260. status,dirs=self.listRemoteDir(url);
  261. return status
  262. def mkdir(self,remoteDir):
  263. if self.remoteDirExists(remoteDir):
  264. return False
  265. r=MethodRequest(remoteDir,method="MKCOL")
  266. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  267. r.add_header("Authorization", "Basic %s" % base64string)
  268. try:
  269. f=self.opener.open(r)
  270. except:
  271. print("Error: Failed MKCOL {}").format(remoteDir)
  272. return False
  273. return True
  274. def mkdirs(self,remoteDir):
  275. relativePath=self.GetRelativePathFromLabkeyPath(remoteDir)
  276. s=0
  277. while True:
  278. s1=relativePath.find('/',s)
  279. if s1<0:
  280. break
  281. path=relativePath[0:s1]
  282. remotePath=self.GetLabkeyPathFromRelativePath(relativePath)
  283. dirExists=self.remoteDirExists(remotePath)
  284. if not dirExists:
  285. if not self.mkdir(remotePath):
  286. return False
  287. s=s1+1
  288. return self.mkdir(remoteDir)
  289. def rmdir(self,remoteDir):
  290. if not self.remoteDirExists(remoteDir):
  291. return True
  292. r=MethodRequest(remoteDir,method="DELETE")
  293. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  294. r.add_header("Authorization", "Basic %s" % base64string)
  295. try:
  296. f=self.opener.open(r)
  297. except:
  298. print("Error: Failed DELETE {}").format(remoteDir)
  299. return False
  300. return True
  301. #was listDir
  302. def listRelativeDir(self,relativeDir):
  303. print("Listing for {0}").format(relativeDir)
  304. dirUrl=self.GetLabkeyPathFromRelativePath(relativeDir)
  305. status,dirs=self.listRemoteDir(dirUrl)
  306. dirs=[self.GetRelativePathFromLabkeyPath(d) for d in dirs];
  307. return dirs
  308. #was isDir
  309. def isRemoteDir(self, remotePath):
  310. #print "isDir: {}".format(remotePath)
  311. r=MethodRequest(remotePath,method="PROPFIND")
  312. PROPFIND=u"""<?xml version="1.0" encoding="utf-8"?>\n
  313. <a:propfind xmlns:a="DAV:">\n
  314. <a:prop>\n
  315. <a:resourcetype/>\n
  316. </a:prop>\n
  317. </a:propfind>"""
  318. r.add_header('content-type','text/xml; charset="utf-8"')
  319. r.add_header('content-length',str(len(PROPFIND)))
  320. r.add_header('Depth','0')
  321. r.add_data(PROPFIND)
  322. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  323. r.add_header("Authorization", "Basic %s" % base64string)
  324. print("PROPFIND: {0}").format(remotePath)
  325. try:
  326. f=self.opener.open(r)
  327. except:
  328. return False
  329. tree=ET.XML(f.read())
  330. try:
  331. rps=tree.find('{DAV:}response').find('{DAV:}propstat')
  332. rps=rps.find('{DAV:}prop')
  333. rps=rps.find('{DAV:}resourcetype').find('{DAV:}collection')
  334. if rps != None:
  335. return True
  336. else:
  337. return False
  338. except:
  339. return False
  340. def listRemoteDir(self,dirUrl):
  341. #input is remoteDir, result are remoteDirs
  342. r=MethodRequest(dirUrl,method="PROPFIND")
  343. PROPFIND=u"""<?xml version="1.0" encoding="utf-8"?>\n
  344. <propfind xmlns="DAV:">\n
  345. <prop>\n
  346. <getetag/>\n
  347. </prop>\n
  348. </propfind>"""
  349. r.add_header('content-type','text/xml; charset="utf-8"')
  350. r.add_header('content-length',str(len(PROPFIND)))
  351. r.add_header('Depth','1')
  352. r.add_data(PROPFIND)
  353. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  354. r.add_header("Authorization", "Basic %s" % base64string)
  355. print("PROPFIND: {0}").format(dirUrl)
  356. dirs=[]
  357. try:
  358. f=self.opener.open(r)
  359. except:
  360. return False,dirs
  361. tree=ET.XML(f.read())
  362. rps=tree.findall('{DAV:}response')
  363. for r in rps:
  364. hr=r.find('{DAV:}href')
  365. dirent=hr.text
  366. #dirent=re.sub('/labkey/_webdav/','',dirent)
  367. dirent=self.GetHostName()+dirent
  368. dirs.append(dirent)
  369. del dirs[0]
  370. return True,dirs
  371. def toRelativePath(self,dirs):
  372. flist1=[]
  373. for d in dirs:
  374. if d[-1]=='/':
  375. d=d[:-1]
  376. if d.rfind('/')>-1:
  377. d=d[d.rfind('/')+1:]
  378. flist1.append(d)
  379. return flist1
  380. def readFileToBuffer(self, relativePath):
  381. dirUrl=self.GetLabkeyPathFromRelativePath(relativePath)
  382. f=self.get(dirUrl)
  383. return StringIO.StringIO(f.read())
  384. def uploadFile(self,localPath):
  385. #get upstream directories sorted out
  386. relativePath=self.GetRelativePathFromLocalPath(localPath)
  387. if relativePath=="NULL":
  388. errorCode="Failed to upload {}. Potential incorrect location"
  389. errorCode+=". Should be in labkeyCache!"
  390. print(errorCode.format(relativePath))
  391. return False
  392. relativeDir=relativePath[0:labkeyPath.rfind('/')]
  393. remoteDir=self.GetLabkeyPathFromRemotePath(relativeDir)
  394. if not self.remoteDirExists(remoteDir):
  395. if not self.mkdirs(remoteDir):
  396. errorCode="UploadFile: Could not create directory {}"
  397. print(errorCode.format(remoteDir))
  398. return False
  399. #make an URL request
  400. with open(localPath, 'rb') as f:
  401. data=f.read()
  402. remotePath=self.GetLabkeyPathFromRelativePath(relativePath)
  403. self.put(remotePath,data)
  404. #was copyFileToRemote
  405. def copyLocalFileToRemote(self,localPath, remotePath):
  406. #get upstream directories sorted out
  407. remoteDir=os.path.dirname(remotePath)
  408. if not self.remoteDirExists(remoteDir):
  409. if not self.mkdirs(remoteDir):
  410. errorCode="UploadFile: Could not create directory {}"
  411. print(errorCode.format(remoteDir))
  412. return False
  413. #make an URL request
  414. if (self.isRemoteDir(remotePath)):
  415. remotePath=remotePath+'/'+os.path.basename(localPath)
  416. with open(localPath, 'rb') as f:
  417. data=f.read()
  418. self.put(remotePath,data)
  419. #was loadDir
  420. def DownloadDirToCache(self, relativePath):
  421. files=self.listRelativeDir(relativePath)
  422. fdir="NONE"
  423. for f in files:
  424. #f is local path
  425. try:
  426. localDir=os.path.dirname(self.DownloadFileToCache(f))
  427. except:
  428. #fails if there is a subdirectory; go recursively
  429. print("self.readDir(f) not implemented")
  430. return localDir
  431. #database routines
  432. def loadDataset(self,project,dataset):
  433. url=self.GetLabkeyUrl()+'/'+project
  434. url+='/query-selectRows.api?schemaName=study&query.queryName='+dataset
  435. return json.load(self.get(url))
  436. def filterDataset(self,project,dataset,filter):
  437. debug=False
  438. url=self.GetLabkeyUrl()+'/'+project
  439. url+='/query-selectRows.api?schemaName=study&query.queryName='+dataset
  440. for f in filter:
  441. url+="&query."+f['variable']+"~"+f['oper']+"="+f['value']
  442. if debug:
  443. print("Sending {}").format(url)
  444. return json.load(self.get(url))
  445. def modifyDataset(self,method,project,dataset,rows):
  446. #method can be insert or update
  447. data={}
  448. data['schemaName']='study'
  449. data['queryName']=dataset
  450. data['rows']=rows
  451. url=self.GetLabkeyUrl()+'/'+project
  452. url+='/query-'+method+'Rows.api?'
  453. return self.post(url,json.dumps(data))
  454. def filterList(self,project,dataset,filter):
  455. schemaName='lists'
  456. debug=False
  457. url=self.GetLabkeyUrl()+'/'+project
  458. url+='/query-selectRows.api?schemaName='+schemaName+'&query.queryName='+dataset
  459. for f in filter:
  460. url+="&query."+f['variable']+"~"+f['oper']+"="+f['value']
  461. if debug:
  462. print("Sending {}").format(url)
  463. return json.load(self.get(url))
  464. def modifyList(self,method,project,dataset,rows):
  465. #method can be insert or update
  466. data={}
  467. schemaName='lists'
  468. data['schemaName']=schemaName
  469. data['queryName']=dataset
  470. data['rows']=rows
  471. url=self.GetLabkeyUrl()+'/'+project
  472. url+='/query-'+method+'Rows.api?'
  473. return self.post(url,json.dumps(data))