slicerNetwork.py 18 KB

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