migrate_from_1.4.24 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #!/usr/bin/python3
  2. import json
  3. import os
  4. import sys
  5. import subprocess
  6. from pathlib import Path
  7. from middlewared.client import Client
  8. from middlewared.service import ValidationErrors, CallError
  9. def path_in_locked_datasets(path: str) -> bool:
  10. with Client() as c:
  11. return c.call('pool.dataset.path_in_locked_datasets', path)
  12. def get_host_path_attachments(path: str) -> set:
  13. with Client() as c:
  14. return {
  15. attachment['type']
  16. for attachment in c.call('pool.dataset.attachments_with_path', path)
  17. if attachment['type'].lower() not in ['kubernetes', 'chart releases']
  18. }
  19. def get_kubernetes_config() -> dict:
  20. with Client() as c:
  21. return c.call('kubernetes.config')
  22. def validate_host_path(path: str, schema_name: str, verrors: ValidationErrors) -> None:
  23. """
  24. These validations are taken from `FilesystemService._common_perm_path_validate`.
  25. Including an additional validation that makes sure all the children under
  26. a path are on same device.
  27. """
  28. schema_name += ".migration.chown"
  29. p = Path(path)
  30. if not p.is_absolute():
  31. verrors.add(schema_name, f"Must be an absolute path: {path}")
  32. if p.is_file():
  33. verrors.add(schema_name, f"Recursive operations on a file are invalid: {path}")
  34. if not p.absolute().as_posix().startswith("/mnt/"):
  35. verrors.add(
  36. schema_name,
  37. f"Changes to permissions on paths that are not beneath the directory /mnt are not permitted: {path}"
  38. )
  39. elif len(p.resolve().parents) == 2:
  40. verrors.add(schema_name, f"The specified path is a ZFS pool mountpoint: {path}")
  41. # Make sure that dataset is not locked
  42. if path_in_locked_datasets(path):
  43. verrors.add(schema_name, f"Dataset is locked at path: {path}.")
  44. # Validate attachments
  45. if attachments := get_host_path_attachments(path):
  46. verrors.add(schema_name, f"The path '{path}' is already attached to service(s): {', '.join(attachments)}.")
  47. # Make sure all the minio's data directory children are on same device.
  48. device_id = os.stat(path).st_dev
  49. for root, dirs, files in os.walk(path):
  50. for child in dirs + files:
  51. abs_path = os.path.join(root, child)
  52. if os.stat(abs_path).st_dev != device_id:
  53. verrors.add(
  54. schema_name,
  55. (f"All the children of MinIO data directory should be on "
  56. f"same device as root: path={abs_path} device={os.stat(abs_path).st_dev}")
  57. )
  58. break
  59. def migrate(values: dict) -> dict:
  60. # minio user / group ID
  61. uid = gid = 473
  62. verrors = ValidationErrors()
  63. k8s_config = get_kubernetes_config()
  64. if values["appVolumeMounts"]["export"]["hostPathEnabled"]:
  65. host_path = values["appVolumeMounts"]["export"]["hostPath"]
  66. else:
  67. app_dataset = values["appVolumeMounts"]["export"]["datasetName"]
  68. host_path = os.path.join(
  69. "/mnt", k8s_config['dataset'], "releases", values["release_name"], app_dataset
  70. )
  71. validate_host_path(host_path, values['release_name'], verrors)
  72. verrors.check()
  73. # chown the host path
  74. acltool = subprocess.run([
  75. "/usr/bin/nfs4xdr_winacl",
  76. "-a", "chown",
  77. "-O", str(uid), "-G", str(gid),
  78. "-r",
  79. "-c", host_path,
  80. "-p", host_path], check=False, capture_output=True
  81. )
  82. if acltool.returncode != 0:
  83. raise CallError(f"acltool [chown] on path {host_path} failed with error: [{acltool.stderr.decode().strip()}]")
  84. return values
  85. if __name__ == "__main__":
  86. if len(sys.argv) != 2:
  87. exit(1)
  88. if os.path.exists(sys.argv[1]):
  89. with open(sys.argv[1], "r") as f:
  90. print(json.dumps(migrate(json.loads(f.read()))))