wms_base.py 24 KB

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