checks.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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_mapset_locked(mapset_path):
  93. """Check if the mapset is locked"""
  94. lock_name = ".gislock"
  95. lockfile = os.path.join(mapset_path, lock_name)
  96. return os.path.exists(lockfile)
  97. def get_lockfile_if_present(database, location, mapset):
  98. """Return path to lock if present, None otherwise
  99. Returns the path as a string or None if nothing was found, so the
  100. return value can be used to test if the lock is present.
  101. """
  102. lock_name = ".gislock"
  103. lockfile = os.path.join(database, location, mapset, lock_name)
  104. if os.path.isfile(lockfile):
  105. return lockfile
  106. return None
  107. def get_mapset_lock_info(mapset_path):
  108. """Get information about .gislock file.
  109. Assumes lock file exists, use is_mapset_locked to find out.
  110. Returns information as a dictionary with keys
  111. 'owner' (None if unknown), 'lockpath', and 'timestamp'.
  112. """
  113. info = {}
  114. lock_name = ".gislock"
  115. info['lockpath'] = os.path.join(mapset_path, lock_name)
  116. try:
  117. info['owner'] = Path(info['lockpath']).owner()
  118. except KeyError:
  119. info['owner'] = None
  120. info['timestamp'] = (datetime.datetime.fromtimestamp(
  121. os.path.getmtime(info['lockpath']))).replace(microsecond=0)
  122. return info
  123. def can_start_in_mapset(mapset_path, ignore_lock=False):
  124. """Check if a mapset from a gisrc file is usable for new session"""
  125. if not is_mapset_valid(mapset_path):
  126. return False
  127. if not is_current_user_mapset_owner(mapset_path):
  128. return False
  129. if not ignore_lock and is_mapset_locked(mapset_path):
  130. return False
  131. return True
  132. def dir_contains_location(path):
  133. """Return True if directory *path* contains a valid location"""
  134. if not os.path.isdir(path):
  135. return False
  136. for name in os.listdir(path):
  137. if os.path.isdir(os.path.join(path, name)):
  138. if is_location_valid(path, name):
  139. return True
  140. return False
  141. # basically checking location, possibly split into two functions
  142. # (mapset one can call location one)
  143. def get_mapset_invalid_reason(database, location, mapset, none_for_no_reason=False):
  144. """Returns a message describing what is wrong with the Mapset
  145. The goal is to provide the most suitable error message
  146. (rather than to do a quick check).
  147. :param database: Path to GRASS GIS database directory
  148. :param location: name of a Location
  149. :param mapset: name of a Mapset
  150. :returns: translated message
  151. """
  152. # Since we are trying to get the one most likely message, we need all
  153. # those return statements here.
  154. # pylint: disable=too-many-return-statements
  155. location_path = os.path.join(database, location)
  156. mapset_path = os.path.join(location_path, mapset)
  157. # first checking the location validity
  158. # perhaps a special set of checks with different messages mentioning mapset
  159. # will be needed instead of the same set of messages used for location
  160. location_msg = get_location_invalid_reason(
  161. database, location, none_for_no_reason=True
  162. )
  163. if location_msg:
  164. return location_msg
  165. # if location is valid, check mapset
  166. if mapset not in os.listdir(location_path):
  167. # TODO: remove the grass.py specific wording
  168. return _(
  169. "Mapset <{mapset}> doesn't exist in GRASS Location <{location}>"
  170. ).format(mapset=mapset, location=location)
  171. if not os.path.isdir(mapset_path):
  172. return _("<%s> is not a GRASS Mapset because it is not a directory") % mapset
  173. if not os.path.isfile(os.path.join(mapset_path, "WIND")):
  174. return (
  175. _(
  176. "<%s> is not a valid GRASS Mapset"
  177. " because it does not have a WIND file"
  178. )
  179. % mapset
  180. )
  181. # based on the is_mapset_valid() function
  182. if not os.access(os.path.join(mapset_path, "WIND"), os.R_OK):
  183. return (
  184. _(
  185. "<%s> is not a valid GRASS Mapset"
  186. " because its WIND file is not readable"
  187. )
  188. % mapset
  189. )
  190. # no reason for invalidity found (might be valid)
  191. if none_for_no_reason:
  192. return None
  193. return _(
  194. "Mapset <{mapset}> or Location <{location}> is invalid for an unknown reason"
  195. ).format(mapset=mapset, location=location)
  196. def get_location_invalid_reason(database, location, none_for_no_reason=False):
  197. """Returns a message describing what is wrong with the Location
  198. The goal is to provide the most suitable error message
  199. (rather than to do a quick check).
  200. By default, when no reason is found, a message about unknown reason is
  201. returned. This applies also to the case when this function is called on
  202. a valid location (e.g. as a part of larger investigation).
  203. ``none_for_no_reason=True`` allows the function to be used as part of other
  204. diagnostic. When this function fails to find reason for invalidity, other
  205. the caller can continue the investigation in their context.
  206. :param database: Path to GRASS GIS database directory
  207. :param location: name of a Location
  208. :param none_for_no_reason: When True, return None when reason is unknown
  209. :returns: translated message or None
  210. """
  211. location_path = os.path.join(database, location)
  212. permanent_path = os.path.join(location_path, "PERMANENT")
  213. # directory
  214. if not os.path.exists(location_path):
  215. return _("Location <%s> doesn't exist") % location_path
  216. # permament mapset
  217. if "PERMANENT" not in os.listdir(location_path):
  218. return (
  219. _(
  220. "<%s> is not a valid GRASS Location"
  221. " because PERMANENT Mapset is missing"
  222. )
  223. % location_path
  224. )
  225. if not os.path.isdir(permanent_path):
  226. return (
  227. _(
  228. "<%s> is not a valid GRASS Location"
  229. " because PERMANENT is not a directory"
  230. )
  231. % location_path
  232. )
  233. # partially based on the is_location_valid() function
  234. if not os.path.isfile(os.path.join(permanent_path, "DEFAULT_WIND")):
  235. return (
  236. _(
  237. "<%s> is not a valid GRASS Location"
  238. " because PERMANENT Mapset does not have a DEFAULT_WIND file"
  239. " (default computational region)"
  240. )
  241. % location_path
  242. )
  243. # no reason for invalidity found (might be valid)
  244. if none_for_no_reason:
  245. return None
  246. return _("Location <{location_path}> is invalid for an unknown reason").format(
  247. location_path=location_path
  248. )
  249. def get_location_invalid_suggestion(database, location):
  250. """Return suggestion what to do when specified location is not valid
  251. It gives suggestion when:
  252. * A mapset was specified instead of a location.
  253. * A GRASS database was specified instead of a location.
  254. """
  255. location_path = os.path.join(database, location)
  256. # a common error is to use mapset instead of location,
  257. # if that's the case, include that info into the message
  258. if is_mapset_valid(location_path):
  259. return _(
  260. "<{location}> looks like a mapset, not a location."
  261. " Did you mean just <{one_dir_up}>?"
  262. ).format(location=location, one_dir_up=database)
  263. # confusion about what is database and what is location
  264. if dir_contains_location(location_path):
  265. return _(
  266. "It looks like <{location}> contains locations."
  267. " Did you mean to specify one of them?"
  268. ).format(location=location)
  269. return None
  270. def get_mapset_name_invalid_reason(database, location, mapset_name):
  271. """Get reasons why mapset name is not valid.
  272. It gets reasons when:
  273. * Name is not valid.
  274. * Name is reserved for OGR layers.
  275. * Mapset in the same path already exists.
  276. Returns message as string if there was a reason, otherwise None.
  277. """
  278. message = None
  279. mapset_path = os.path.join(database, location, mapset_name)
  280. # Check if mapset name is valid
  281. if not gs.legal_name(mapset_name):
  282. message = _(
  283. "Name '{}' is not a valid name for location or mapset. "
  284. "Please use only ASCII characters excluding characters {} "
  285. "and space.").format(mapset_name, '/"\'@,=*~')
  286. # Check reserved mapset name
  287. elif mapset_name.lower() == 'ogr':
  288. message = _(
  289. "Name '{}' is reserved for direct "
  290. "read access to OGR layers. Please use "
  291. "another name for your mapset.").format(mapset_name)
  292. # Check whether mapset exists
  293. elif mapset_exists(database, location, mapset_name):
  294. message = _(
  295. "Mapset <{mapset}> already exists. Please consider using "
  296. "another name for your mapset.").format(mapset=mapset_path)
  297. return message
  298. def get_location_name_invalid_reason(grassdb, location_name):
  299. """Get reasons why location name is not valid.
  300. It gets reasons when:
  301. * Name is not valid.
  302. * Location in the same path already exists.
  303. Returns message as string if there was a reason, otherwise None.
  304. """
  305. message = None
  306. location_path = os.path.join(grassdb, location_name)
  307. # Check if mapset name is valid
  308. if not gs.legal_name(location_name):
  309. message = _(
  310. "Name '{}' is not a valid name for location or mapset. "
  311. "Please use only ASCII characters excluding characters {} "
  312. "and space.").format(location_name, '/"\'@,=*~')
  313. # Check whether location exists
  314. elif location_exists(grassdb, location_name):
  315. message = _(
  316. "Location <{location}> already exists. Please consider using "
  317. "another name for your location.").format(location=location_path)
  318. return message
  319. def is_mapset_name_valid(database, location, mapset_name):
  320. """Check if mapset name is valid.
  321. Returns True if mapset name is valid, otherwise False.
  322. """
  323. return gs.legal_name(mapset_name) and mapset_name.lower() != "ogr" and not \
  324. mapset_exists(database, location, mapset_name)
  325. def is_location_name_valid(database, location_name):
  326. """Check if location name is valid.
  327. Returns True if location name is valid, otherwise False.
  328. """
  329. return gs.legal_name(location_name) and not \
  330. location_exists(database, location_name)
  331. def get_reasons_mapsets_not_removable(mapsets, check_permanent):
  332. """Get reasons why mapsets cannot be removed.
  333. Parameter *mapsets* is a list of tuples (database, location, mapset).
  334. Parameter *check_permanent* is True of False. It depends on whether
  335. we want to check for permanent mapset or not.
  336. Returns messages as list if there were any failed checks, otherwise empty list.
  337. """
  338. messages = []
  339. for grassdb, location, mapset in mapsets:
  340. message = get_reason_mapset_not_removable(grassdb, location,
  341. mapset, check_permanent)
  342. if message:
  343. messages.append(message)
  344. return messages
  345. def get_reason_mapset_not_removable(grassdb, location, mapset, check_permanent):
  346. """Get reason why one mapset cannot be removed.
  347. Parameter *check_permanent* is True of False. It depends on whether
  348. we want to check for permanent mapset or not.
  349. Returns message as string if there was failed check, otherwise None.
  350. """
  351. message = None
  352. mapset_path = os.path.join(grassdb, location, mapset)
  353. # Check if mapset is permanent
  354. if check_permanent and mapset == "PERMANENT":
  355. message = _("Mapset <{mapset}> is required for a valid location.").format(
  356. mapset=mapset_path)
  357. # Check if mapset is current
  358. elif is_mapset_current(grassdb, location, mapset):
  359. message = _("Mapset <{mapset}> is the current mapset.").format(
  360. mapset=mapset_path)
  361. # Check whether mapset is in use
  362. elif is_mapset_locked(mapset_path):
  363. message = _("Mapset <{mapset}> is in use.").format(
  364. mapset=mapset_path)
  365. # Check whether mapset is owned by different user
  366. elif is_different_mapset_owner(mapset_path):
  367. message = _("Mapset <{mapset}> is owned by a different user.").format(
  368. mapset=mapset_path)
  369. return message
  370. def get_reasons_locations_not_removable(locations):
  371. """Get reasons why locations cannot be removed.
  372. Parameter *locations* is a list of tuples (database, location).
  373. Returns messages as list if there were any failed checks, otherwise empty list.
  374. """
  375. messages = []
  376. for grassdb, location in locations:
  377. messages += get_reasons_location_not_removable(grassdb, location)
  378. return messages
  379. def get_reasons_location_not_removable(grassdb, location):
  380. """Get reasons why one location cannot be removed.
  381. Returns messages as list if there were any failed checks, otherwise empty list.
  382. """
  383. messages = []
  384. location_path = os.path.join(grassdb, location)
  385. # Check if location is current
  386. if is_location_current(grassdb, location):
  387. messages.append(_("Location <{location}> is the current location.").format(
  388. location=location_path))
  389. return messages
  390. # Find mapsets in particular location
  391. tmp_gisrc_file, env = gs.create_environment(grassdb, location, 'PERMANENT')
  392. env['GRASS_SKIP_MAPSET_OWNER_CHECK'] = '1'
  393. g_mapsets = gs.read_command(
  394. 'g.mapsets',
  395. flags='l',
  396. separator='comma',
  397. quiet=True,
  398. env=env).strip().split(',')
  399. # Append to the list of tuples
  400. mapsets = []
  401. for g_mapset in g_mapsets:
  402. mapsets.append((grassdb, location, g_mapset))
  403. # Concentenate both checks
  404. messages += get_reasons_mapsets_not_removable(mapsets, check_permanent=False)
  405. gs.try_remove(tmp_gisrc_file)
  406. return messages
  407. def get_reasons_grassdb_not_removable(grassdb):
  408. """Get reasons why one grassdb cannot be removed.
  409. Returns messages as list if there were any failed checks, otherwise empty list.
  410. """
  411. messages = []
  412. genv = gisenv()
  413. # Check if grassdb is current
  414. if grassdb == genv['GISDBASE']:
  415. messages.append(_("GRASS database <{grassdb}> is the current database.").format(
  416. grassdb=grassdb))
  417. return messages
  418. g_locations = get_list_of_locations(grassdb)
  419. # Append to the list of tuples
  420. locations = []
  421. for g_location in g_locations:
  422. locations.append((grassdb, g_location))
  423. messages = get_reasons_locations_not_removable(locations)
  424. return messages
  425. def get_list_of_locations(dbase):
  426. """Get list of GRASS locations in given dbase
  427. :param dbase: GRASS database path
  428. :return: list of locations (sorted)
  429. """
  430. locations = list()
  431. for location in glob.glob(os.path.join(dbase, "*")):
  432. if os.path.join(
  433. location, "PERMANENT") in glob.glob(
  434. os.path.join(location, "*")):
  435. locations.append(os.path.basename(location))
  436. locations.sort(key=lambda x: x.lower())
  437. return locations