wms_base.py 24 KB

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