checks.py 21 KB

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