wms_base.py 22 KB

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