slicerNetwork.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. return localPath
  224. if debug:
  225. print("labkeyURIHandler::DownloadFileToCache({0}->{1})").format(relativePath,localPath)
  226. #make all necessary directories LOCALLY
  227. path=os.path.dirname(localPath)
  228. if not os.path.isdir(path):
  229. os.makedirs(path)
  230. localBuffer=open(localPath,'wb')
  231. #make sure we are at the begining of the file
  232. #labkeyPath=self.GetLabkeyPathFromRelativePath(relativePath)
  233. remoteBuffer=self.readFileToBuffer(relativePath)
  234. #check file size
  235. if debug:
  236. remoteBuffer.seek(0,2)
  237. sz=remoteBuffer.tell()
  238. print("Remote size: {0}").format(sz)
  239. remoteBuffer.seek(0)
  240. shutil.copyfileobj(remoteBuffer,localBuffer)
  241. if debug:
  242. print("Local size: {0}").format(localBuffer.tell())
  243. localBuffer.close()
  244. return localPath
  245. def fileTypesAvailable(self):
  246. return ('VolumeFile','SegmentationFile','TransformFile')
  247. #mimic slicer.util.loadNodeFromFile
  248. def loadNode(self, relativeName, filetype, properties={}, returnNode=False):
  249. #this is the only relevant part - file must be downloaded to cache
  250. #labkeyName is just the relative part (from labkey onwards)
  251. localPath=self.DownloadFileToCache(relativeName)
  252. print localPath
  253. slicer.util.loadNodeFromFile(localPath,filetype,properties,returnNode)
  254. # #remove retrieved file
  255. def remoteDirExists(self,url):
  256. status,dirs=self.listRemoteDir(url);
  257. return status
  258. def mkdir(self,remoteDir):
  259. if self.remoteDirExists(remoteDir):
  260. return False
  261. r=MethodRequest(remoteDir,method="MKCOL")
  262. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  263. r.add_header("Authorization", "Basic %s" % base64string)
  264. try:
  265. f=self.opener.open(r)
  266. except:
  267. print("Error: Failed MKCOL {}").format(remoteDir)
  268. return False
  269. return True
  270. def mkdirs(self,remoteDir):
  271. relativePath=self.GetRelativePathFromLabkeyPath(remoteDir)
  272. s=0
  273. while True:
  274. s1=relativePath.find('/',s)
  275. if s1<0:
  276. break
  277. path=relativePath[0:s1]
  278. remotePath=self.GetLabkeyPathFromRelativePath(relativePath)
  279. dirExists=self.remoteDirExists(remotePath)
  280. if not dirExists:
  281. if not self.mkdir(remotePath):
  282. return False
  283. s=s1+1
  284. return self.mkdir(remoteDir)
  285. def rmdir(self,remoteDir):
  286. if not self.remoteDirExists(remoteDir):
  287. return True
  288. r=MethodRequest(remoteDir,method="DELETE")
  289. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  290. r.add_header("Authorization", "Basic %s" % base64string)
  291. try:
  292. f=self.opener.open(r)
  293. except:
  294. print("Error: Failed DELETE {}").format(remoteDir)
  295. return False
  296. return True
  297. #was listDir
  298. def listRelativeDir(self,relativeDir):
  299. print("Listing for {0}").format(relativeDir)
  300. dirUrl=self.GetLabkeyPathFromRelativePath(relativeDir)
  301. status,dirs=self.listRemoteDir(dirUrl)
  302. dirs=[self.GetRelativePathFromLabkeyPath(d) for d in dirs];
  303. return dirs
  304. #was isDir
  305. def isRemoteDir(self, remotePath):
  306. #print "isDir: {}".format(remotePath)
  307. r=MethodRequest(remotePath,method="PROPFIND")
  308. PROPFIND=u"""<?xml version="1.0" encoding="utf-8"?>\n
  309. <a:propfind xmlns:a="DAV:">\n
  310. <a:prop>\n
  311. <a:resourcetype/>\n
  312. </a:prop>\n
  313. </a:propfind>"""
  314. r.add_header('content-type','text/xml; charset="utf-8"')
  315. r.add_header('content-length',str(len(PROPFIND)))
  316. r.add_header('Depth','0')
  317. r.add_data(PROPFIND)
  318. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  319. r.add_header("Authorization", "Basic %s" % base64string)
  320. print("PROPFIND: {0}").format(remotePath)
  321. try:
  322. f=self.opener.open(r)
  323. except:
  324. return False
  325. tree=ET.XML(f.read())
  326. try:
  327. rps=tree.find('{DAV:}response').find('{DAV:}propstat')
  328. rps=rps.find('{DAV:}prop')
  329. rps=rps.find('{DAV:}resourcetype').find('{DAV:}collection')
  330. if rps != None:
  331. return True
  332. else:
  333. return False
  334. except:
  335. return False
  336. def listRemoteDir(self,dirUrl):
  337. #input is remoteDir, result are remoteDirs
  338. r=MethodRequest(dirUrl,method="PROPFIND")
  339. PROPFIND=u"""<?xml version="1.0" encoding="utf-8"?>\n
  340. <propfind xmlns="DAV:">\n
  341. <prop>\n
  342. <getetag/>\n
  343. </prop>\n
  344. </propfind>"""
  345. r.add_header('content-type','text/xml; charset="utf-8"')
  346. r.add_header('content-length',str(len(PROPFIND)))
  347. r.add_header('Depth','1')
  348. r.add_data(PROPFIND)
  349. base64string = base64.b64encode('%s:%s' % (self.auth_name, self.auth_pass))
  350. r.add_header("Authorization", "Basic %s" % base64string)
  351. print("PROPFIND: {0}").format(dirUrl)
  352. dirs=[]
  353. try:
  354. f=self.opener.open(r)
  355. except:
  356. return False,dirs
  357. tree=ET.XML(f.read())
  358. rps=tree.findall('{DAV:}response')
  359. for r in rps:
  360. hr=r.find('{DAV:}href')
  361. dirent=hr.text
  362. #dirent=re.sub('/labkey/_webdav/','',dirent)
  363. dirent=self.GetHostName()+dirent
  364. dirs.append(dirent)
  365. del dirs[0]
  366. return True,dirs
  367. def toRelativePath(self,dirs):
  368. flist1=[]
  369. for d in dirs:
  370. if d[-1]=='/':
  371. d=d[:-1]
  372. if d.rfind('/')>-1:
  373. d=d[d.rfind('/')+1:]
  374. flist1.append(d)
  375. return flist1
  376. def readFileToBuffer(self, relativePath):
  377. dirUrl=self.GetLabkeyPathFromRelativePath(relativePath)
  378. f=self.get(dirUrl)
  379. return StringIO.StringIO(f.read())
  380. def uploadFile(self,localPath):
  381. #get upstream directories sorted out
  382. relativePath=self.GetRelativePathFromLocalPath(localPath)
  383. if relativePath=="NULL":
  384. errorCode="Failed to upload {}. Potential incorrect location"
  385. errorCode+=". Should be in labkeyCache!"
  386. print(errorCode.format(relativePath))
  387. return False
  388. relativeDir=relativePath[0:labkeyPath.rfind('/')]
  389. remoteDir=self.GetLabkeyPathFromRemotePath(relativeDir)
  390. if not self.remoteDirExists(remoteDir):
  391. if not self.mkdirs(remoteDir):
  392. errorCode="UploadFile: Could not create directory {}"
  393. print(errorCode.format(remoteDir))
  394. return False
  395. #make an URL request
  396. with open(localPath, 'rb') as f:
  397. data=f.read()
  398. remotePath=self.GetLabkeyPathFromRelativePath(relativePath)
  399. self.put(remotePath,data)
  400. #was copyFileToRemote
  401. def copyLocalFileToRemote(self,localPath, remotePath):
  402. #get upstream directories sorted out
  403. remoteDir=os.path.dirname(remotePath)
  404. if not self.remoteDirExists(remoteDir):
  405. if not self.mkdirs(remoteDir):
  406. errorCode="UploadFile: Could not create directory {}"
  407. print(errorCode.format(remoteDir))
  408. return False
  409. #make an URL request
  410. if (self.isRemoteDir(remotePath)):
  411. remotePath=remotePath+'/'+os.path.basename(localPath)
  412. with open(localPath, 'rb') as f:
  413. data=f.read()
  414. self.put(remotePath,data)
  415. #was loadDir
  416. def DownloadDirToCache(self, relativePath):
  417. files=self.listRelativeDir(relativePath)
  418. fdir="NONE"
  419. for f in files:
  420. #f is local path
  421. try:
  422. localDir=os.path.dirname(self.DownloadFileToCache(f))
  423. except:
  424. #fails if there is a subdirectory; go recursively
  425. print("self.readDir(f) not implemented")
  426. return localDir
  427. #database routines
  428. def loadDataset(self,project,dataset):
  429. url=self.GetLabkeyUrl()+'/'+project
  430. url+='/query-selectRows.api?schemaName=study&query.queryName='+dataset
  431. return json.load(self.get(url))
  432. def filterDataset(self,project,dataset,filter):
  433. debug=False
  434. url=self.GetLabkeyUrl()+'/'+project
  435. url+='/query-selectRows.api?schemaName=study&query.queryName='+dataset
  436. for f in filter:
  437. url+="&query."+f['variable']+"~"+f['oper']+"="+f['value']
  438. if debug:
  439. print("Sending {}").format(url)
  440. return json.load(self.get(url))
  441. def modifyDataset(self,method,project,dataset,rows):
  442. #method can be insert or update
  443. data={}
  444. data['schemaName']='study'
  445. data['queryName']=dataset
  446. data['rows']=rows
  447. url=self.GetLabkeyUrl()+'/'+project
  448. url+='/query-'+method+'Rows.api?'
  449. return self.post(url,json.dumps(data))
  450. def filterList(self,project,dataset,filter):
  451. schemaName='lists'
  452. debug=False
  453. url=self.GetLabkeyUrl()+'/'+project
  454. url+='/query-selectRows.api?schemaName='+schemaName+'&query.queryName='+dataset
  455. for f in filter:
  456. url+="&query."+f['variable']+"~"+f['oper']+"="+f['value']
  457. if debug:
  458. print("Sending {}").format(url)
  459. return json.load(self.get(url))
  460. def modifyList(self,method,project,dataset,rows):
  461. #method can be insert or update
  462. data={}
  463. schemaName='lists'
  464. data['schemaName']=schemaName
  465. data['queryName']=dataset
  466. data['rows']=rows
  467. url=self.GetLabkeyUrl()+'/'+project
  468. url+='/query-'+method+'Rows.api?'
  469. return self.post(url,json.dumps(data))