wms_base.py 22 KB

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