wms_base.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. """!
  2. @brief Preparation of parameters for drivers, which download it, and managing downloaded data.
  3. List of classes:
  4. - wms_base::WMSBase
  5. - wms_base::GRASSImporter
  6. - wms_base::WMSDriversInfo
  7. (C) 2012-2013 by the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. @author Stepan Turek <stepan.turek seznam.cz> (Mentor: Martin Landa)
  11. """
  12. import os
  13. from math import ceil
  14. import base64
  15. import urllib2
  16. from httplib import HTTPException
  17. import grass.script as grass
  18. from grass.exceptions import CalledModuleError
  19. class WMSBase:
  20. def __init__(self):
  21. # these variables are information for destructor
  22. self.temp_files_to_cleanup = []
  23. self.params = {}
  24. self.tile_size = {'bbox' : None}
  25. self.temp_map = None
  26. self.temp_warpmap = None
  27. def __del__(self):
  28. # tries to remove temporary files, all files should be
  29. # removed before, implemented just in case of unexpected
  30. # stop of module
  31. for temp_file in self.temp_files_to_cleanup:
  32. grass.try_remove(temp_file)
  33. def _debug(self, fn, msg):
  34. grass.debug("%s.%s: %s" %
  35. (self.__class__.__name__, fn, msg))
  36. def _initializeParameters(self, options, flags):
  37. self._debug("_initialize_parameters", "started")
  38. # initialization of module parameters (options, flags)
  39. self.params['driver'] = options['driver']
  40. drv_info = WMSDriversInfo()
  41. driver_props = drv_info.GetDrvProperties(options['driver'])
  42. self._checkIgnoeredParams(options, flags, driver_props)
  43. self.params['capfile'] = options['capfile'].strip()
  44. for key in ['url', 'layers', 'styles', 'method']:
  45. self.params[key] = options[key].strip()
  46. self.flags = flags
  47. if self.flags['o']:
  48. self.params['transparent'] = 'FALSE'
  49. else:
  50. self.params['transparent'] = 'TRUE'
  51. for key in ['password', 'username', 'urlparams']:
  52. self.params[key] = options[key]
  53. if (self.params ['password'] and self.params ['username'] == '') or \
  54. (self.params ['password'] == '' and self.params ['username']):
  55. grass.fatal(_("Please insert both %s and %s parameters or none of them." % ('password', 'username')))
  56. self.params['bgcolor'] = options['bgcolor'].strip()
  57. if options['format'] == "jpeg" and \
  58. not 'format' in driver_props['ignored_params']:
  59. if not flags['o'] and \
  60. 'WMS' in self.params['driver']:
  61. grass.warning(_("JPEG format does not support transparency"))
  62. self.params['format'] = drv_info.GetFormat(options['format'])
  63. if not self.params['format']:
  64. self.params['format'] = self.params['format']
  65. #TODO: get srs from Tile Service file in OnEarth_GRASS driver
  66. self.params['srs'] = int(options['srs'])
  67. if self.params['srs'] <= 0 and not 'srs' in driver_props['ignored_params']:
  68. grass.fatal(_("Invalid EPSG code %d") % self.params['srs'])
  69. self.params['wms_version'] = options['wms_version']
  70. if "CRS" in GetSRSParamVal(self.params['srs']) and self.params['wms_version'] == "1.1.1":
  71. self.params['wms_version'] = "1.3.0"
  72. grass.warning(_("WMS version <1.3.0> will be used, because version <1.1.1> does not support <%s>projection")
  73. % GetSRSParamVal(self.params['srs']))
  74. if self.params['wms_version'] == "1.3.0":
  75. self.params['proj_name'] = "CRS"
  76. else:
  77. self.params['proj_name'] = "SRS"
  78. # read projection info
  79. self.proj_location = grass.read_command('g.proj',
  80. flags ='jf').rstrip('\n')
  81. self.proj_location = self._modifyProj(self.proj_location)
  82. if self.params['srs'] in [3857, 900913]:
  83. # HACK: epsg 3857 def: http://spatialreference.org/ref/sr-org/7483/
  84. # g.proj can return: ...+a=6378137 +rf=298.257223563... (WGS84 elipsoid def instead of sphere), it can make 20km shift in Y, when raster is transformed
  85. # needed to be tested on more servers
  86. self.proj_srs = '+proj=merc +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +no_defs +a=6378137 +b=6378137 +nadgrids=@null +to_meter=1'
  87. else:
  88. self.proj_srs = grass.read_command('g.proj',
  89. flags = 'jf',
  90. epsg = str(GetEpsg(self.params['srs']))).rstrip('\n')
  91. self.proj_srs = self._modifyProj(self.proj_srs)
  92. if not self.proj_srs or not self.proj_location:
  93. grass.fatal(_("Unable to get projection info"))
  94. self.region = options['region']
  95. min_tile_size = 100
  96. maxcols = int(options['maxcols'])
  97. if maxcols <= min_tile_size:
  98. grass.fatal(_("Maxcols must be greater than 100"))
  99. maxrows = int(options['maxrows'])
  100. if maxrows <= min_tile_size:
  101. grass.fatal(_("Maxrows must be greater than 100"))
  102. # setting optimal tile size according to maxcols and maxrows constraint and region cols and rows
  103. self.tile_size['cols'] = int(self.region['cols'] / ceil(self.region['cols'] / float(maxcols)))
  104. self.tile_size['rows'] = int(self.region['rows'] / ceil(self.region['rows'] / float(maxrows)))
  105. # default format for GDAL library
  106. self.gdal_drv_format = "GTiff"
  107. self._debug("_initialize_parameters", "finished")
  108. def _modifyProj(self, proj):
  109. """!Modify proj.4 string for usage in this module"""
  110. # add +wktext parameter to avoid droping of +nadgrids parameter (if presented) in gdalwarp
  111. if '+nadgrids=' in proj and ' +wktext' not in proj:
  112. proj += ' +wktext'
  113. return proj
  114. def _checkIgnoeredParams(self, options, flags, driver_props):
  115. """!Write warnings for set parameters and flags, which chosen driver does not use."""
  116. not_relevant_params = []
  117. for i_param in driver_props['ignored_params']:
  118. if options.has_key(i_param) and \
  119. options[i_param] and \
  120. i_param not in ['srs', 'wms_version', 'format']: # params with default value
  121. not_relevant_params.append('<' + i_param + '>')
  122. if len(not_relevant_params) > 0:
  123. grass.warning(_("These parameter are ignored: %s\n\
  124. %s driver does not support the parameters." %\
  125. (','.join(not_relevant_params), options['driver'])))
  126. not_relevant_flags = []
  127. for i_flag in driver_props['ignored_flags']:
  128. if flags[i_flag]:
  129. not_relevant_flags.append('<' + i_flag + '>')
  130. if len(not_relevant_flags) > 0:
  131. grass.warning(_("These flags are ignored: %s\n\
  132. %s driver does not support the flags." %\
  133. (','.join(not_relevant_flags), options['driver'])))
  134. def GetMap(self, options, flags):
  135. """!Download data from WMS server."""
  136. self._initializeParameters(options, flags)
  137. self.bbox = self._computeBbox()
  138. self.temp_map = self._download()
  139. if not self.temp_map:
  140. return
  141. self._reprojectMap()
  142. return self.temp_warpmap
  143. def _fetchCapabilities(self, options):
  144. """!Download capabilities from WMS server
  145. """
  146. cap_url = options['url'].strip()
  147. if "?" in cap_url:
  148. cap_url += "&"
  149. else:
  150. cap_url += "?"
  151. if 'WMTS' in options['driver']:
  152. cap_url += "SERVICE=WMTS&REQUEST=GetCapabilities&VERSION=1.0.0"
  153. elif 'OnEarth' in options['driver']:
  154. cap_url += "REQUEST=GetTileService"
  155. else:
  156. cap_url += "SERVICE=WMS&REQUEST=GetCapabilities&VERSION=" + options['wms_version']
  157. if options['urlparams']:
  158. cap_url += "&" + options['urlparams']
  159. grass.debug('Fetching capabilities file.\n%s' % cap_url)
  160. try:
  161. cap = self._fetchDataFromServer(cap_url, options['username'], options['password'])
  162. except (IOError, HTTPException) as e:
  163. if urllib2.HTTPError == type(e) and e.code == 401:
  164. grass.fatal(_("Authorization failed to <%s> when fetching capabilities") % options['url'])
  165. else:
  166. msg = _("Unable to fetch capabilities from <%s>: %s") % (options['url'], e)
  167. if hasattr(e, 'reason'):
  168. msg += _("\nReason: ") + e.reason
  169. grass.fatal(msg)
  170. grass.debug('Fetching capabilities OK')
  171. return cap
  172. def _fetchDataFromServer(self, url, username = None, password = None):
  173. """!Fetch data from server
  174. """
  175. request = urllib2.Request(url)
  176. if username and password:
  177. base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
  178. request.add_header("Authorization", "Basic %s" % base64string)
  179. try:
  180. return urllib2.urlopen(request)
  181. except ValueError as error:
  182. grass.fatal("%s" % error)
  183. def GetCapabilities(self, options):
  184. """!Get capabilities from WMS server
  185. """
  186. cap = self._fetchCapabilities(options)
  187. capfile_output = options['capfile_output'].strip()
  188. # save to file
  189. if capfile_output:
  190. try:
  191. temp = open(capfile_output, "w")
  192. temp.write(cap.read())
  193. temp.close()
  194. return
  195. except IOError as error:
  196. grass.fatal(_("Unabble to open file '%s'.\n%s\n" % (cap_file, error)))
  197. # print to output
  198. cap_lines = cap.readlines()
  199. for line in cap_lines:
  200. print line.rstrip()
  201. def _computeBbox(self):
  202. """!Get region extent for WMS query (bbox)
  203. """
  204. self._debug("_computeBbox", "started")
  205. bbox_region_items = {'maxy' : 'n', 'miny' : 's', 'maxx' : 'e', 'minx' : 'w'}
  206. bbox = {}
  207. if self.proj_srs == self.proj_location: # TODO: do it better
  208. for bbox_item, region_item in bbox_region_items.iteritems():
  209. bbox[bbox_item] = self.region[region_item]
  210. # if location projection and wms query projection are
  211. # different, corner points of region are transformed into wms
  212. # projection and then bbox is created from extreme coordinates
  213. # of the transformed points
  214. else:
  215. for bbox_item, region_item in bbox_region_items.iteritems():
  216. bbox[bbox_item] = None
  217. temp_region = self._tempfile()
  218. try:
  219. temp_region_opened = open(temp_region, 'w')
  220. temp_region_opened.write("%f %f\n%f %f\n%f %f\n%f %f\n" %\
  221. (self.region['e'], self.region['n'],\
  222. self.region['w'], self.region['n'],\
  223. self.region['w'], self.region['s'],\
  224. self.region['e'], self.region['s'] ))
  225. except IOError:
  226. grass.fatal(_("Unable to write data into tempfile"))
  227. finally:
  228. temp_region_opened.close()
  229. points = grass.read_command('m.proj', flags = 'd',
  230. proj_out = self.proj_srs,
  231. proj_in = self.proj_location,
  232. input = temp_region,
  233. quiet = True) # TODO: stdin
  234. grass.try_remove(temp_region)
  235. if not points:
  236. grass.fatal(_("Unable to determine region, %s failed") % 'm.proj')
  237. points = points.splitlines()
  238. if len(points) != 4:
  239. grass.fatal(_("Region definition: 4 points required"))
  240. for point in points:
  241. try:
  242. point = map(float, point.split("|"))
  243. except ValueError:
  244. grass.fatal(_('Reprojection of region using m.proj failed.'))
  245. if not bbox['maxy']:
  246. bbox['maxy'] = point[1]
  247. bbox['miny'] = point[1]
  248. bbox['maxx'] = point[0]
  249. bbox['minx'] = point[0]
  250. continue
  251. if bbox['maxy'] < point[1]:
  252. bbox['maxy'] = point[1]
  253. elif bbox['miny'] > point[1]:
  254. bbox['miny'] = point[1]
  255. if bbox['maxx'] < point[0]:
  256. bbox['maxx'] = point[0]
  257. elif bbox['minx'] > point[0]:
  258. bbox['minx'] = point[0]
  259. self._debug("_computeBbox", "finished -> %s" % bbox)
  260. # Ordering of coordinates axis of geographic coordinate
  261. # systems in WMS 1.3.0 is flipped. If self.tile_size['flip_coords'] is
  262. # True, coords in bbox need to be flipped in WMS query.
  263. return bbox
  264. def _reprojectMap(self):
  265. """!Reproject data using gdalwarp if needed
  266. """
  267. # reprojection of raster
  268. if self.proj_srs != self.proj_location: # TODO: do it better
  269. grass.message(_("Reprojecting raster..."))
  270. self.temp_warpmap = grass.tempfile()
  271. if int(os.getenv('GRASS_VERBOSE', '2')) <= 2:
  272. nuldev = file(os.devnull, 'w+')
  273. else:
  274. nuldev = None
  275. if self.params['method'] == "nearest":
  276. gdal_method = "near"
  277. elif self.params['method'] == "linear":
  278. gdal_method = "bilinear"
  279. else:
  280. gdal_method = self.params['method']
  281. #"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"
  282. # RGB rasters - alpha layer is added for cropping edges of projected raster
  283. try:
  284. if self.temp_map_bands_num == 3:
  285. ps = grass.Popen(['gdalwarp',
  286. '-s_srs', '%s' % self.proj_srs,
  287. '-t_srs', '%s' % self.proj_location,
  288. '-r', gdal_method, '-dstalpha',
  289. self.temp_map, self.temp_warpmap], stdout = nuldev)
  290. # RGBA rasters
  291. else:
  292. ps = grass.Popen(['gdalwarp',
  293. '-s_srs', '%s' % self.proj_srs,
  294. '-t_srs', '%s' % self.proj_location,
  295. '-r', gdal_method,
  296. self.temp_map, self.temp_warpmap], stdout = nuldev)
  297. ps.wait()
  298. except OSError as e:
  299. grass.fatal('%s \nThis can be caused by missing %s utility. ' % (e, 'gdalwarp'))
  300. if nuldev:
  301. nuldev.close()
  302. if ps.returncode != 0:
  303. grass.fatal(_('%s failed') % 'gdalwarp')
  304. grass.try_remove(self.temp_map)
  305. # raster projection is same as projection of location
  306. else:
  307. self.temp_warpmap = self.temp_map
  308. self.temp_files_to_cleanup.remove(self.temp_map)
  309. return self.temp_warpmap
  310. def _tempfile(self):
  311. """!Create temp_file and append list self.temp_files_to_cleanup
  312. with path of file
  313. @return string path to temp_file
  314. """
  315. temp_file = grass.tempfile()
  316. if temp_file is None:
  317. grass.fatal(_("Unable to create temporary files"))
  318. # list of created tempfiles for destructor
  319. self.temp_files_to_cleanup.append(temp_file)
  320. return temp_file
  321. class GRASSImporter:
  322. def __init__(self, opt_output):
  323. self.cleanup_mask = False
  324. self.cleanup_layers = False
  325. # output map name
  326. self.opt_output = opt_output
  327. # suffix for existing mask (during overriding will be saved
  328. # into raster named:self.opt_output + this suffix)
  329. self.original_mask_suffix = "_temp_MASK"
  330. # check names of temporary rasters, which module may create
  331. maps = []
  332. for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix ):
  333. rast = self.opt_output + suffix
  334. if grass.find_file(rast, element = 'cell', mapset = '.')['file']:
  335. maps.append(rast)
  336. if len(maps) != 0:
  337. grass.fatal(_("Please change output name, or change names of these rasters: %s, "
  338. "module needs to create this temporary maps during execution.") % ",".join(maps))
  339. def __del__(self):
  340. # removes temporary mask, used for import transparent or warped temp_map
  341. if self.cleanup_mask:
  342. # clear temporary mask, which was set by module
  343. try:
  344. grass.run_command('r.mask', quiet=True, flags='r')
  345. except CalledModuleError:
  346. grass.fatal(_('%s failed') % 'r.mask')
  347. # restore original mask, if exists
  348. if grass.find_file(self.opt_output + self.original_mask_suffix, element = 'cell', mapset = '.' )['name']:
  349. try:
  350. mask_copy = self.opt_output + self.original_mask_suffix
  351. grass.run_command('g.copy', quiet=True,
  352. rast=mask_copy + ',MASK')
  353. except CalledModuleError:
  354. grass.fatal(_('%s failed') % 'g.copy')
  355. # remove temporary created rasters
  356. if self.cleanup_layers:
  357. maps = []
  358. for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix):
  359. rast = self.opt_output + suffix
  360. if grass.find_file(rast, element = 'cell', mapset = '.')['file']:
  361. maps.append(rast)
  362. if maps:
  363. grass.run_command('g.remove',
  364. quiet = True,
  365. flags = 'fb',
  366. type = 'rast',
  367. name = ','.join(maps))
  368. # delete environmental variable which overrides region
  369. if 'GRASS_REGION' in os.environ.keys():
  370. os.environ.pop('GRASS_REGION')
  371. def ImportMapIntoGRASS(self, raster):
  372. """!Import raster into GRASS.
  373. """
  374. # importing temp_map into GRASS
  375. try:
  376. grass.run_command('r.in.gdal',
  377. quiet=True, overwrite=True,
  378. input=raster, output=self.opt_output)
  379. except CalledModuleError:
  380. grass.fatal(_('%s failed') % 'r.in.gdal')
  381. # information for destructor to cleanup temp_layers, created
  382. # with r.in.gdal
  383. self.cleanup_layers = True
  384. # setting region for full extend of imported raster
  385. if grass.find_file(self.opt_output + '.red', element = 'cell', mapset = '.')['file']:
  386. region_map = self.opt_output + '.red'
  387. else:
  388. region_map = self.opt_output
  389. os.environ['GRASS_REGION'] = grass.region_env(rast = region_map)
  390. # mask created from alpha layer, which describes real extend
  391. # of warped layer (may not be a rectangle), also mask contains
  392. # transparent parts of raster
  393. if grass.find_file( self.opt_output + '.alpha', element = 'cell', mapset = '.' )['name']:
  394. # saving current mask (if exists) into temp raster
  395. if grass.find_file('MASK', element = 'cell', mapset = '.' )['name']:
  396. try:
  397. mask_copy = self.opt_output + self.original_mask_suffix
  398. grass.run_command('g.copy', quiet=True,
  399. rast='MASK,' + mask_copy)
  400. except CalledModuleError:
  401. grass.fatal(_('%s failed') % 'g.copy')
  402. # info for destructor
  403. self.cleanup_mask = True
  404. try:
  405. grass.run_command('r.mask',
  406. quiet=True, overwrite=True,
  407. maskcats="0",
  408. flags='i',
  409. raster=self.opt_output + '.alpha')
  410. except CalledModuleError:
  411. grass.fatal(_('%s failed') % 'r.mask')
  412. #TODO one band + alpha band?
  413. if grass.find_file(self.opt_output + '.red', element = 'cell', mapset = '.')['file']:
  414. try:
  415. grass.run_command('r.composite',
  416. quiet=True, overwrite=True,
  417. red=self.opt_output + '.red',
  418. green=self.opt_output + '.green',
  419. blue=self.opt_output + '.blue',
  420. output=self.opt_output)
  421. except CalledModuleError:
  422. grass.fatal(_('%s failed') % 'r.composite')
  423. grass.message(_('<%s> created.') % self.opt_output)
  424. class WMSDriversInfo:
  425. def __init__(self):
  426. """!Provides information about driver parameters.
  427. """
  428. # format labels
  429. self.f_labels = ["geotiff", "tiff", "png", "jpeg", "gif", "png8"]
  430. # form for request
  431. self.formats = ["image/geotiff", "image/tiff", "image/png", "image/jpeg", "image/gif", "image/png8"]
  432. self.srs = ("epsg", "crs")
  433. def GetDrvProperties(self, driver):
  434. """!Get information about driver parameters.
  435. """
  436. if driver == 'WMS_GDAL':
  437. return self._GDALDrvProperties()
  438. if 'WMS' in driver:
  439. return self._WMSProperties()
  440. if 'WMTS' in driver:
  441. return self._WMTSProperties()
  442. if 'OnEarth' in driver:
  443. return self._OnEarthProperties()
  444. def _OnEarthProperties(self):
  445. props = {}
  446. props['ignored_flags'] = ['o']
  447. props['ignored_params'] = ['bgcolor', 'styles', 'capfile_output',
  448. 'format', 'srs', 'wms_version']
  449. props['req_multiple_layers'] = False
  450. return props
  451. def _WMSProperties(self):
  452. props = {}
  453. props['ignored_params'] = ['capfile']
  454. props['ignored_flags'] = []
  455. props['req_multiple_layers'] = True
  456. return props
  457. def _WMTSProperties(self):
  458. props = {}
  459. props['ignored_flags'] = ['o']
  460. props['ignored_params'] = ['urlparams', 'bgcolor', 'wms_version']
  461. props['req_multiple_layers'] = False
  462. return props
  463. def _GDALDrvProperties(self):
  464. props = {}
  465. props['ignored_flags'] = []
  466. props['ignored_params'] = ['urlparams', 'bgcolor', 'capfile', 'capfile_output',
  467. 'username', 'password']
  468. props['req_multiple_layers'] = True
  469. return props
  470. def GetFormatLabel(self, format):
  471. """!Convert format request form to value in parameter 'format'.
  472. """
  473. if format in self.formats:
  474. return self.f_labels[self.formats.index(format)]
  475. return None
  476. def GetFormat(self, label):
  477. """!Convert value in parameter 'format' to format request form.
  478. """
  479. if label in self.f_labels:
  480. return self.formats[self.f_labels.index(label)]
  481. return None
  482. def GetSrs(self):
  483. """!Get supported srs prefixes (e.g. epsg/crs)
  484. @todo filter according to version and driver params
  485. """
  486. return self.srs
  487. #TODO move to utils?
  488. def GetSRSParamVal(srs):
  489. """!Decides whether to use CRS or EPSG prefix according to srs number.
  490. """
  491. if srs in [84, 83, 27]:
  492. return "CRS:%d" % srs
  493. else:
  494. return "EPSG:%d" % srs
  495. def GetEpsg(srs):
  496. """
  497. @return EPSG number
  498. If srs is CRS number, return EPSG number which corresponds to CRS number.
  499. """
  500. if srs == 84:
  501. return 4326
  502. if srs == 83:
  503. return 4269
  504. if srs == 27:
  505. return 4267
  506. return srs