wms_base.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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-2016 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 <{}>. Reason: ").format(
  167. options['url'])
  168. if hasattr(e, 'reason'):
  169. msg += '{}'.format(e.reason)
  170. else:
  171. msg += '{}'.format(e)
  172. grass.fatal(msg)
  173. grass.debug('Fetching capabilities OK')
  174. return cap
  175. def _fetchDataFromServer(self, url, username = None, password = None):
  176. """!Fetch data from server
  177. """
  178. request = urllib2.Request(url)
  179. if username and password:
  180. base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
  181. request.add_header("Authorization", "Basic %s" % base64string)
  182. try:
  183. return urllib2.urlopen(request)
  184. except ValueError as error:
  185. grass.fatal("%s" % error)
  186. def GetCapabilities(self, options):
  187. """!Get capabilities from WMS server
  188. """
  189. cap = self._fetchCapabilities(options)
  190. capfile_output = options['capfile_output'].strip()
  191. # save to file
  192. if capfile_output:
  193. try:
  194. temp = open(capfile_output, "w")
  195. temp.write(cap.read())
  196. temp.close()
  197. return
  198. except IOError as error:
  199. grass.fatal(_("Unabble to open file '%s'.\n%s\n" % (cap_file, error)))
  200. # print to output
  201. cap_lines = cap.readlines()
  202. for line in cap_lines:
  203. print line.rstrip()
  204. def _computeBbox(self):
  205. """!Get region extent for WMS query (bbox)
  206. """
  207. self._debug("_computeBbox", "started")
  208. bbox_region_items = {'maxy' : 'n', 'miny' : 's', 'maxx' : 'e', 'minx' : 'w'}
  209. bbox = {}
  210. if self.proj_srs == self.proj_location: # TODO: do it better
  211. for bbox_item, region_item in bbox_region_items.iteritems():
  212. bbox[bbox_item] = self.region[region_item]
  213. # if location projection and wms query projection are
  214. # different, corner points of region are transformed into wms
  215. # projection and then bbox is created from extreme coordinates
  216. # of the transformed points
  217. else:
  218. for bbox_item, region_item in bbox_region_items.iteritems():
  219. bbox[bbox_item] = None
  220. temp_region = self._tempfile()
  221. try:
  222. temp_region_opened = open(temp_region, 'w')
  223. temp_region_opened.write("%f %f\n%f %f\n%f %f\n%f %f\n" %\
  224. (self.region['e'], self.region['n'],\
  225. self.region['w'], self.region['n'],\
  226. self.region['w'], self.region['s'],\
  227. self.region['e'], self.region['s'] ))
  228. except IOError:
  229. grass.fatal(_("Unable to write data into tempfile"))
  230. finally:
  231. temp_region_opened.close()
  232. points = grass.read_command('m.proj', flags = 'd',
  233. proj_out = self.proj_srs,
  234. proj_in = self.proj_location,
  235. input = temp_region,
  236. quiet = True) # TODO: stdin
  237. grass.try_remove(temp_region)
  238. if not points:
  239. grass.fatal(_("Unable to determine region, %s failed") % 'm.proj')
  240. points = points.splitlines()
  241. if len(points) != 4:
  242. grass.fatal(_("Region definition: 4 points required"))
  243. for point in points:
  244. try:
  245. point = map(float, point.split("|"))
  246. except ValueError:
  247. grass.fatal(_('Reprojection of region using m.proj failed.'))
  248. if not bbox['maxy']:
  249. bbox['maxy'] = point[1]
  250. bbox['miny'] = point[1]
  251. bbox['maxx'] = point[0]
  252. bbox['minx'] = point[0]
  253. continue
  254. if bbox['maxy'] < point[1]:
  255. bbox['maxy'] = point[1]
  256. elif bbox['miny'] > point[1]:
  257. bbox['miny'] = point[1]
  258. if bbox['maxx'] < point[0]:
  259. bbox['maxx'] = point[0]
  260. elif bbox['minx'] > point[0]:
  261. bbox['minx'] = point[0]
  262. self._debug("_computeBbox", "finished -> %s" % bbox)
  263. # Ordering of coordinates axis of geographic coordinate
  264. # systems in WMS 1.3.0 is flipped. If self.tile_size['flip_coords'] is
  265. # True, coords in bbox need to be flipped in WMS query.
  266. return bbox
  267. def _reprojectMap(self):
  268. """!Reproject data using gdalwarp if needed
  269. """
  270. # reprojection of raster
  271. if self.proj_srs != self.proj_location: # TODO: do it better
  272. grass.message(_("Reprojecting raster..."))
  273. self.temp_warpmap = grass.tempfile()
  274. if int(os.getenv('GRASS_VERBOSE', '2')) <= 2:
  275. nuldev = file(os.devnull, 'w+')
  276. else:
  277. nuldev = None
  278. if self.params['method'] == "nearest":
  279. gdal_method = "near"
  280. elif self.params['method'] == "linear":
  281. gdal_method = "bilinear"
  282. else:
  283. gdal_method = self.params['method']
  284. #"+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"
  285. # RGB rasters - alpha layer is added for cropping edges of projected raster
  286. try:
  287. if self.temp_map_bands_num == 3:
  288. ps = grass.Popen(['gdalwarp',
  289. '-s_srs', '%s' % self.proj_srs,
  290. '-t_srs', '%s' % self.proj_location,
  291. '-r', gdal_method, '-dstalpha',
  292. self.temp_map, self.temp_warpmap], stdout = nuldev)
  293. # RGBA rasters
  294. else:
  295. ps = grass.Popen(['gdalwarp',
  296. '-s_srs', '%s' % self.proj_srs,
  297. '-t_srs', '%s' % self.proj_location,
  298. '-r', gdal_method,
  299. self.temp_map, self.temp_warpmap], stdout = nuldev)
  300. ps.wait()
  301. except OSError as e:
  302. grass.fatal('%s \nThis can be caused by missing %s utility. ' % (e, 'gdalwarp'))
  303. if nuldev:
  304. nuldev.close()
  305. if ps.returncode != 0:
  306. grass.fatal(_('%s failed') % 'gdalwarp')
  307. grass.try_remove(self.temp_map)
  308. # raster projection is same as projection of location
  309. else:
  310. self.temp_warpmap = self.temp_map
  311. self.temp_files_to_cleanup.remove(self.temp_map)
  312. return self.temp_warpmap
  313. def _tempfile(self):
  314. """!Create temp_file and append list self.temp_files_to_cleanup
  315. with path of file
  316. @return string path to temp_file
  317. """
  318. temp_file = grass.tempfile()
  319. if temp_file is None:
  320. grass.fatal(_("Unable to create temporary files"))
  321. # list of created tempfiles for destructor
  322. self.temp_files_to_cleanup.append(temp_file)
  323. return temp_file
  324. class GRASSImporter:
  325. def __init__(self, opt_output):
  326. self.cleanup_mask = False
  327. self.cleanup_layers = False
  328. # output map name
  329. self.opt_output = opt_output
  330. # suffix for existing mask (during overriding will be saved
  331. # into raster named:self.opt_output + this suffix)
  332. self.original_mask_suffix = "_temp_MASK"
  333. # check names of temporary rasters, which module may create
  334. maps = []
  335. for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix ):
  336. rast = self.opt_output + suffix
  337. if grass.find_file(rast, element = 'cell', mapset = '.')['file']:
  338. maps.append(rast)
  339. if len(maps) != 0:
  340. grass.fatal(_("Please change output name, or change names of these rasters: %s, "
  341. "module needs to create this temporary maps during execution.") % ",".join(maps))
  342. def __del__(self):
  343. # removes temporary mask, used for import transparent or warped temp_map
  344. if self.cleanup_mask:
  345. # clear temporary mask, which was set by module
  346. try:
  347. grass.run_command('r.mask', quiet=True, flags='r')
  348. except CalledModuleError:
  349. grass.fatal(_('%s failed') % 'r.mask')
  350. # restore original mask, if exists
  351. if grass.find_file(self.opt_output + self.original_mask_suffix, element = 'cell', mapset = '.' )['name']:
  352. try:
  353. mask_copy = self.opt_output + self.original_mask_suffix
  354. grass.run_command('g.copy', quiet=True,
  355. raster=mask_copy + ',MASK')
  356. except CalledModuleError:
  357. grass.fatal(_('%s failed') % 'g.copy')
  358. # remove temporary created rasters
  359. if self.cleanup_layers:
  360. maps = []
  361. for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix):
  362. rast = self.opt_output + suffix
  363. if grass.find_file(rast, element = 'cell', mapset = '.')['file']:
  364. maps.append(rast)
  365. if maps:
  366. grass.run_command('g.remove',
  367. quiet = True,
  368. flags = 'fb',
  369. type = 'raster',
  370. name = ','.join(maps))
  371. # delete environmental variable which overrides region
  372. if 'GRASS_REGION' in os.environ.keys():
  373. os.environ.pop('GRASS_REGION')
  374. def ImportMapIntoGRASS(self, raster):
  375. """!Import raster into GRASS.
  376. """
  377. # importing temp_map into GRASS
  378. try:
  379. grass.run_command('r.in.gdal',
  380. quiet=True, overwrite=True,
  381. input=raster, output=self.opt_output)
  382. except CalledModuleError:
  383. grass.fatal(_('%s failed') % 'r.in.gdal')
  384. # information for destructor to cleanup temp_layers, created
  385. # with r.in.gdal
  386. self.cleanup_layers = True
  387. # setting region for full extend of imported raster
  388. if grass.find_file(self.opt_output + '.red', element = 'cell', mapset = '.')['file']:
  389. region_map = self.opt_output + '.red'
  390. else:
  391. region_map = self.opt_output
  392. os.environ['GRASS_REGION'] = grass.region_env(rast = region_map)
  393. # mask created from alpha layer, which describes real extend
  394. # of warped layer (may not be a rectangle), also mask contains
  395. # transparent parts of raster
  396. if grass.find_file( self.opt_output + '.alpha', element = 'cell', mapset = '.' )['name']:
  397. # saving current mask (if exists) into temp raster
  398. if grass.find_file('MASK', element = 'cell', mapset = '.' )['name']:
  399. try:
  400. mask_copy = self.opt_output + self.original_mask_suffix
  401. grass.run_command('g.copy', quiet=True,
  402. raster='MASK,' + mask_copy)
  403. except CalledModuleError:
  404. grass.fatal(_('%s failed') % 'g.copy')
  405. # info for destructor
  406. self.cleanup_mask = True
  407. try:
  408. grass.run_command('r.mask',
  409. quiet=True, overwrite=True,
  410. maskcats="0",
  411. flags='i',
  412. raster=self.opt_output + '.alpha')
  413. except CalledModuleError:
  414. grass.fatal(_('%s failed') % 'r.mask')
  415. #TODO one band + alpha band?
  416. if grass.find_file(self.opt_output + '.red', element = 'cell', mapset = '.')['file']:
  417. try:
  418. grass.run_command('r.composite',
  419. quiet=True, overwrite=True,
  420. red=self.opt_output + '.red',
  421. green=self.opt_output + '.green',
  422. blue=self.opt_output + '.blue',
  423. output=self.opt_output)
  424. except CalledModuleError:
  425. grass.fatal(_('%s failed') % 'r.composite')
  426. grass.message(_('<%s> created.') % self.opt_output)
  427. class WMSDriversInfo:
  428. def __init__(self):
  429. """!Provides information about driver parameters.
  430. """
  431. # format labels
  432. self.f_labels = ["geotiff", "tiff", "png", "jpeg", "gif", "png8"]
  433. # form for request
  434. self.formats = ["image/geotiff", "image/tiff", "image/png", "image/jpeg", "image/gif", "image/png8"]
  435. self.srs = ("epsg", "crs")
  436. def GetDrvProperties(self, driver):
  437. """!Get information about driver parameters.
  438. """
  439. if driver == 'WMS_GDAL':
  440. return self._GDALDrvProperties()
  441. if 'WMS' in driver:
  442. return self._WMSProperties()
  443. if 'WMTS' in driver:
  444. return self._WMTSProperties()
  445. if 'OnEarth' in driver:
  446. return self._OnEarthProperties()
  447. def _OnEarthProperties(self):
  448. props = {}
  449. props['ignored_flags'] = ['o']
  450. props['ignored_params'] = ['bgcolor', 'styles', 'capfile_output',
  451. 'format', 'srs', 'wms_version']
  452. props['req_multiple_layers'] = False
  453. return props
  454. def _WMSProperties(self):
  455. props = {}
  456. props['ignored_params'] = ['capfile']
  457. props['ignored_flags'] = []
  458. props['req_multiple_layers'] = True
  459. return props
  460. def _WMTSProperties(self):
  461. props = {}
  462. props['ignored_flags'] = ['o']
  463. props['ignored_params'] = ['urlparams', 'bgcolor', 'wms_version']
  464. props['req_multiple_layers'] = False
  465. return props
  466. def _GDALDrvProperties(self):
  467. props = {}
  468. props['ignored_flags'] = []
  469. props['ignored_params'] = ['urlparams', 'bgcolor', 'capfile', 'capfile_output',
  470. 'username', 'password']
  471. props['req_multiple_layers'] = True
  472. return props
  473. def GetFormatLabel(self, format):
  474. """!Convert format request form to value in parameter 'format'.
  475. """
  476. if format in self.formats:
  477. return self.f_labels[self.formats.index(format)]
  478. return None
  479. def GetFormat(self, label):
  480. """!Convert value in parameter 'format' to format request form.
  481. """
  482. if label in self.f_labels:
  483. return self.formats[self.f_labels.index(label)]
  484. return None
  485. def GetSrs(self):
  486. """!Get supported srs prefixes (e.g. epsg/crs)
  487. @todo filter according to version and driver params
  488. """
  489. return self.srs
  490. #TODO move to utils?
  491. def GetSRSParamVal(srs):
  492. """!Decides whether to use CRS or EPSG prefix according to srs number.
  493. """
  494. if srs in [84, 83, 27]:
  495. return "CRS:%d" % srs
  496. else:
  497. return "EPSG:%d" % srs
  498. def GetEpsg(srs):
  499. """
  500. @return EPSG number
  501. If srs is CRS number, return EPSG number which corresponds to CRS number.
  502. """
  503. if srs == 84:
  504. return 4326
  505. if srs == 83:
  506. return 4269
  507. if srs == 27:
  508. return 4267
  509. return srs