checks.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. """
  2. Checking objects in a GRASS GIS Spatial Database
  3. (C) 2020 by the GRASS Development Team
  4. This program is free software under the GNU General Public
  5. License (>=v2). Read the file COPYING that comes with GRASS
  6. for details.
  7. .. sectionauthor:: Vaclav Petras <wenzeslaus gmail com>
  8. """
  9. import os
  10. import sys
  11. import datetime
  12. from pathlib import Path
  13. from grass.script import gisenv
  14. import grass.script as gs
  15. import glob
  16. def mapset_exists(database, location, mapset):
  17. """Returns True whether mapset path exists."""
  18. location_path = os.path.join(database, location)
  19. mapset_path = os.path.join(location_path, mapset)
  20. if os.path.exists(mapset_path):
  21. return True
  22. return False
  23. def location_exists(database, location):
  24. """Returns True whether location path exists."""
  25. location_path = os.path.join(database, location)
  26. if os.path.exists(location_path):
  27. return True
  28. return False
  29. # TODO: distinguish between valid for getting maps and usable as current
  30. # https://lists.osgeo.org/pipermail/grass-dev/2016-September/082317.html
  31. # interface created according to the current usage
  32. def is_mapset_valid(mapset_path):
  33. """Return True if GRASS Mapset is valid"""
  34. # WIND is created from DEFAULT_WIND by `g.region -d` and functions
  35. # or modules which create a new mapset. Most modules will fail if
  36. # WIND doesn't exist (assuming that neither GRASS_REGION nor
  37. # WIND_OVERRIDE environmental variables are set).
  38. return os.access(os.path.join(mapset_path, "WIND"), os.R_OK)
  39. def is_location_valid(database, location):
  40. """Return True if GRASS Location is valid
  41. :param database: Path to GRASS GIS database directory
  42. :param location: name of a Location
  43. """
  44. # DEFAULT_WIND file should not be required until you do something
  45. # that actually uses them. The check is just a heuristic; a directory
  46. # containing a PERMANENT/DEFAULT_WIND file is probably a GRASS
  47. # location, while a directory lacking it probably isn't.
  48. return os.access(
  49. os.path.join(database, location, "PERMANENT", "DEFAULT_WIND"), os.F_OK
  50. )
  51. def is_mapset_current(database, location, mapset):
  52. genv = gisenv()
  53. if (database == genv['GISDBASE'] and
  54. location == genv['LOCATION_NAME'] and
  55. mapset == genv['MAPSET']):
  56. return True
  57. return False
  58. def is_location_current(database, location):
  59. genv = gisenv()
  60. if (database == genv['GISDBASE'] and
  61. location == genv['LOCATION_NAME']):
  62. return True
  63. return False
  64. def is_current_user_mapset_owner(mapset_path):
  65. """Returns True if mapset owner is the current user.
  66. On Windows it always returns True."""
  67. # Note that this does account for libgis built with SKIP_MAPSET_OWN_CHK
  68. # which disables the ownerships check, i.e., even if it was build with the
  69. # skip, it still needs the env variable.
  70. if os.environ.get("GRASS_SKIP_MAPSET_OWNER_CHECK", None):
  71. # Mapset just needs to be accessible for writing.
  72. return os.access(mapset_path, os.W_OK)
  73. # Mapset needs to be owned by user.
  74. if sys.platform == 'win32':
  75. return True
  76. stat_info = os.stat(mapset_path)
  77. mapset_uid = stat_info.st_uid
  78. return mapset_uid == os.getuid()
  79. def is_different_mapset_owner(mapset_path):
  80. """Returns True if mapset owner is different from the current user"""
  81. return not is_current_user_mapset_owner(mapset_path)
  82. def get_mapset_owner(mapset_path):
  83. """Returns mapset owner name or None if owner name unknown.
  84. On Windows it always returns None."""
  85. if sys.platform == 'win32':
  86. return None
  87. try:
  88. path = Path(mapset_path)
  89. return path.owner()
  90. except KeyError:
  91. return None
  92. def is_current_mapset_in_demolocation():
  93. return gisenv()['LOCATION_NAME'] == "world_latlong_wgs84"
  94. def is_mapset_locked(mapset_path):
  95. """Check if the mapset is locked"""
  96. lock_name = ".gislock"
  97. lockfile = os.path.join(mapset_path, lock_name)
  98. return os.path.exists(lockfile)
  99. def get_lockfile_if_present(database, location, mapset):
  100. """Return path to lock if present, None otherwise
  101. Returns the path as a string or None if nothing was found, so the
  102. return value can be used to test if the lock is present.
  103. """
  104. lock_name = ".gislock"
  105. lockfile = os.path.join(database, location, mapset, lock_name)
  106. if os.path.isfile(lockfile):
  107. return lockfile
  108. return None
  109. def get_mapset_lock_info(mapset_path):
  110. """Get information about .gislock file.
  111. Assumes lock file exists, use is_mapset_locked to find out.
  112. Returns information as a dictionary with keys
  113. 'owner' (None if unknown), 'lockpath', and 'timestamp'.
  114. """
  115. info = {}
  116. lock_name = ".gislock"
  117. info['lockpath'] = os.path.join(mapset_path, lock_name)
  118. try:
  119. info['owner'] = Path(info['lockpath']).owner()
  120. except KeyError:
  121. info['owner'] = None
  122. info['timestamp'] = (datetime.datetime.fromtimestamp(
  123. os.path.getmtime(info['lockpath']))).replace(microsecond=0)
  124. return info
  125. def can_start_in_mapset(mapset_path, ignore_lock=False):
  126. """Check if a mapset from a gisrc file is usable for new session"""
  127. if not is_mapset_valid(mapset_path):
  128. return False
  129. if not is_current_user_mapset_owner(mapset_path):
  130. return False
  131. if not ignore_lock and is_mapset_locked(mapset_path):
  132. return False
  133. return True
  134. def dir_contains_location(path):
  135. """Return True if directory *path* contains a valid location"""
  136. if not os.path.isdir(path):
  137. return False
  138. for name in os.listdir(path):
  139. if os.path.isdir(os.path.join(path, name)):
  140. if is_location_valid(path, name):
  141. return True
  142. return False
  143. # basically checking location, possibly split into two functions
  144. # (mapset one can call location one)
  145. def get_mapset_invalid_reason(database, location, mapset, none_for_no_reason=False):
  146. """Returns a message describing what is wrong with the Mapset
  147. The goal is to provide the most suitable error message
  148. (rather than to do a quick check).
  149. :param database: Path to GRASS GIS database directory
  150. :param location: name of a Location
  151. :param mapset: name of a Mapset
  152. :returns: translated message
  153. """
  154. # Since we are trying to get the one most likely message, we need all
  155. # those return statements here.
  156. # pylint: disable=too-many-return-statements
  157. location_path = os.path.join(database, location)
  158. mapset_path = os.path.join(location_path, mapset)
  159. # first checking the location validity
  160. # perhaps a special set of checks with different messages mentioning mapset
  161. # will be needed instead of the same set of messages used for location
  162. location_msg = get_location_invalid_reason(
  163. database, location, none_for_no_reason=True
  164. )
  165. if location_msg:
  166. return location_msg
  167. # if location is valid, check mapset
  168. if mapset not in os.listdir(location_path):
  169. # TODO: remove the grass.py specific wording
  170. return _(
  171. "Mapset <{mapset}> doesn't exist in GRASS Location <{location}>"
  172. ).format(mapset=mapset, location=location)
  173. if not os.path.isdir(mapset_path):
  174. return _("<%s> is not a GRASS Mapset because it is not a directory") % mapset
  175. if not os.path.isfile(os.path.join(mapset_path, "WIND")):
  176. return (
  177. _(
  178. "<%s> is not a valid GRASS Mapset"
  179. " because it does not have a WIND file"
  180. )
  181. % mapset
  182. )
  183. # based on the is_mapset_valid() function
  184. if not os.access(os.path.join(mapset_path, "WIND"), os.R_OK):
  185. return (
  186. _(
  187. "<%s> is not a valid GRASS Mapset"
  188. " because its WIND file is not readable"
  189. )
  190. % mapset
  191. )
  192. # no reason for invalidity found (might be valid)
  193. if none_for_no_reason:
  194. return None
  195. return _(
  196. "Mapset <{mapset}> or Location <{location}> is invalid for an unknown reason"
  197. ).format(mapset=mapset, location=location)
  198. def get_location_invalid_reason(database, location, none_for_no_reason=False):
  199. """Returns a message describing what is wrong with the Location
  200. The goal is to provide the most suitable error message
  201. (rather than to do a quick check).
  202. By default, when no reason is found, a message about unknown reason is
  203. returned. This applies also to the case when this function is called on
  204. a valid location (e.g. as a part of larger investigation).
  205. ``none_for_no_reason=True`` allows the function to be used as part of other
  206. diagnostic. When this function fails to find reason for invalidity, other
  207. the caller can continue the investigation in their context.
  208. :param database: Path to GRASS GIS database directory
  209. :param location: name of a Location
  210. :param none_for_no_reason: When True, return None when reason is unknown
  211. :returns: translated message or None
  212. """
  213. location_path = os.path.join(database, location)
  214. permanent_path = os.path.join(location_path, "PERMANENT")
  215. # directory
  216. if not os.path.exists(location_path):
  217. return _("Location <%s> doesn't exist") % location_path
  218. # permament mapset
  219. if "PERMANENT" not in os.listdir(location_path):
  220. return (
  221. _(
  222. "<%s> is not a valid GRASS Location"
  223. " because PERMANENT Mapset is missing"
  224. )
  225. % location_path
  226. )
  227. if not os.path.isdir(permanent_path):
  228. return (
  229. _(
  230. "<%s> is not a valid GRASS Location"
  231. " because PERMANENT is not a directory"
  232. )
  233. % location_path
  234. )
  235. # partially based on the is_location_valid() function
  236. if not os.path.isfile(os.path.join(permanent_path, "DEFAULT_WIND")):
  237. return (
  238. _(
  239. "<%s> is not a valid GRASS Location"
  240. " because PERMANENT Mapset does not have a DEFAULT_WIND file"
  241. " (default computational region)"
  242. )
  243. % location_path
  244. )
  245. # no reason for invalidity found (might be valid)
  246. if none_for_no_reason:
  247. return None
  248. return _("Location <{location_path}> is invalid for an unknown reason").format(
  249. location_path=location_path
  250. )
  251. def get_location_invalid_suggestion(database, location):
  252. """Return suggestion what to do when specified location is not valid
  253. It gives suggestion when:
  254. * A mapset was specified instead of a location.
  255. * A GRASS database was specified instead of a location.
  256. """
  257. location_path = os.path.join(database, location)
  258. # a common error is to use mapset instead of location,
  259. # if that's the case, include that info into the message
  260. if is_mapset_valid(location_path):
  261. return _(
  262. "<{location}> looks like a mapset, not a location."
  263. " Did you mean just <{one_dir_up}>?"
  264. ).format(location=location, one_dir_up=database)
  265. # confusion about what is database and what is location
  266. if dir_contains_location(location_path):
  267. return _(
  268. "It looks like <{location}> contains locations."
  269. " Did you mean to specify one of them?"
  270. ).format(location=location)
  271. return None
  272. def get_mapset_name_invalid_reason(database, location, mapset_name):
  273. """Get reasons why mapset name is not valid.
  274. It gets reasons when:
  275. * Name is not valid.
  276. * Name is reserved for OGR layers.
  277. * Mapset in the same path already exists.
  278. Returns message as string if there was a reason, otherwise None.
  279. """
  280. message = None
  281. mapset_path = os.path.join(database, location, mapset_name)
  282. # Check if mapset name is valid
  283. if not gs.legal_name(mapset_name):
  284. message = _(
  285. "Name '{}' is not a valid name for location or mapset. "
  286. "Please use only ASCII characters excluding characters {} "
  287. "and space.").format(mapset_name, '/"\'@,=*~')
  288. # Check reserved mapset name
  289. elif mapset_name.lower() == 'ogr':
  290. message = _(
  291. "Name '{}' is reserved for direct "
  292. "read access to OGR layers. Please use "
  293. "another name for your mapset.").format(mapset_name)
  294. # Check whether mapset exists
  295. elif mapset_exists(database, location, mapset_name):
  296. message = _(
  297. "Mapset <{mapset}> already exists. Please consider using "
  298. "another name for your mapset.").format(mapset=mapset_path)
  299. return message
  300. def get_location_name_invalid_reason(grassdb, location_name):
  301. """Get reasons why location name is not valid.
  302. It gets reasons when:
  303. * Name is not valid.
  304. * Location in the same path already exists.
  305. Returns message as string if there was a reason, otherwise None.
  306. """
  307. message = None
  308. location_path = os.path.join(grassdb, location_name)
  309. # Check if mapset name is valid
  310. if not gs.legal_name(location_name):
  311. message = _(
  312. "Name '{}' is not a valid name for location or mapset. "
  313. "Please use only ASCII characters excluding characters {} "
  314. "and space.").format(location_name, '/"\'@,=*~')
  315. # Check whether location exists
  316. elif location_exists(grassdb, location_name):
  317. message = _(
  318. "Location <{location}> already exists. Please consider using "
  319. "another name for your location.").format(location=location_path)
  320. return message
  321. def is_mapset_name_valid(database, location, mapset_name):
  322. """Check if mapset name is valid.
  323. Returns True if mapset name is valid, otherwise False.
  324. """
  325. return gs.legal_name(mapset_name) and mapset_name.lower() != "ogr" and not \
  326. mapset_exists(database, location, mapset_name)
  327. def is_location_name_valid(database, location_name):
  328. """Check if location name is valid.
  329. Returns True if location name is valid, otherwise False.
  330. """
  331. return gs.legal_name(location_name) and not \
  332. location_exists(database, location_name)
  333. def get_reasons_mapsets_not_removable(mapsets, check_permanent):
  334. """Get reasons why mapsets cannot be removed.
  335. Parameter *mapsets* is a list of tuples (database, location, mapset).
  336. Parameter *check_permanent* is True of False. It depends on whether
  337. we want to check for permanent mapset or not.
  338. Returns messages as list if there were any failed checks, otherwise empty list.
  339. """
  340. messages = []
  341. for grassdb, location, mapset in mapsets:
  342. message = get_reason_mapset_not_removable(grassdb, location,
  343. mapset, check_permanent)
  344. if message:
  345. messages.append(message)
  346. return messages
  347. def get_reason_mapset_not_removable(grassdb, location, mapset, check_permanent):
  348. """Get reason why one mapset cannot be removed.
  349. Parameter *check_permanent* is True of False. It depends on whether
  350. we want to check for permanent mapset or not.
  351. Returns message as string if there was failed check, otherwise None.
  352. """
  353. message = None
  354. mapset_path = os.path.join(grassdb, location, mapset)
  355. # Check if mapset is permanent
  356. if check_permanent and mapset == "PERMANENT":
  357. message = _("Mapset <{mapset}> is required for a valid location.").format(
  358. mapset=mapset_path)
  359. # Check if mapset is current
  360. elif is_mapset_current(grassdb, location, mapset):
  361. message = _("Mapset <{mapset}> is the current mapset.").format(
  362. mapset=mapset_path)
  363. # Check whether mapset is in use
  364. elif is_mapset_locked(mapset_path):
  365. message = _("Mapset <{mapset}> is in use.").format(
  366. mapset=mapset_path)
  367. # Check whether mapset is owned by different user
  368. elif is_different_mapset_owner(mapset_path):
  369. message = _("Mapset <{mapset}> is owned by a different user.").format(
  370. mapset=mapset_path)
  371. return message
  372. def get_reasons_locations_not_removable(locations):
  373. """Get reasons why locations cannot be removed.
  374. Parameter *locations* is a list of tuples (database, location).
  375. Returns messages as list if there were any failed checks, otherwise empty list.
  376. """
  377. messages = []
  378. for grassdb, location in locations:
  379. messages += get_reasons_location_not_removable(grassdb, location)
  380. return messages
  381. def get_reasons_location_not_removable(grassdb, location):
  382. """Get reasons why one location cannot be removed.
  383. Returns messages as list if there were any failed checks, otherwise empty list.
  384. """
  385. messages = []
  386. location_path = os.path.join(grassdb, location)
  387. # Check if location is current
  388. if is_location_current(grassdb, location):
  389. messages.append(_("Location <{location}> is the current location.").format(
  390. location=location_path))
  391. return messages
  392. # Find mapsets in particular location
  393. tmp_gisrc_file, env = gs.create_environment(grassdb, location, 'PERMANENT')
  394. env['GRASS_SKIP_MAPSET_OWNER_CHECK'] = '1'
  395. g_mapsets = gs.read_command(
  396. 'g.mapsets',
  397. flags='l',
  398. separator='comma',
  399. quiet=True,
  400. env=env).strip().split(',')
  401. # Append to the list of tuples
  402. mapsets = []
  403. for g_mapset in g_mapsets:
  404. mapsets.append((grassdb, location, g_mapset))
  405. # Concentenate both checks
  406. messages += get_reasons_mapsets_not_removable(mapsets, check_permanent=False)
  407. gs.try_remove(tmp_gisrc_file)
  408. return messages
  409. def get_reasons_grassdb_not_removable(grassdb):
  410. """Get reasons why one grassdb cannot be removed.
  411. Returns messages as list if there were any failed checks, otherwise empty list.
  412. """
  413. messages = []
  414. genv = gisenv()
  415. # Check if grassdb is current
  416. if grassdb == genv['GISDBASE']:
  417. messages.append(_("GRASS database <{grassdb}> is the current database.").format(
  418. grassdb=grassdb))
  419. return messages
  420. g_locations = get_list_of_locations(grassdb)
  421. # Append to the list of tuples
  422. locations = []
  423. for g_location in g_locations:
  424. locations.append((grassdb, g_location))
  425. messages = get_reasons_locations_not_removable(locations)
  426. return messages
  427. def get_list_of_locations(dbase):
  428. """Get list of GRASS locations in given dbase
  429. :param dbase: GRASS database path
  430. :return: list of locations (sorted)
  431. """
  432. locations = list()
  433. for location in glob.glob(os.path.join(dbase, "*")):
  434. if os.path.join(
  435. location, "PERMANENT") in glob.glob(
  436. os.path.join(location, "*")):
  437. locations.append(os.path.basename(location))
  438. locations.sort(key=lambda x: x.lower())
  439. return locations