checks.py 18 KB

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