infrahub-server 1.5.0b0__py3-none-any.whl → 1.5.0b2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. infrahub/actions/tasks.py +8 -0
  2. infrahub/api/diff/diff.py +1 -1
  3. infrahub/api/internal.py +2 -0
  4. infrahub/api/oauth2.py +13 -19
  5. infrahub/api/oidc.py +15 -21
  6. infrahub/api/schema.py +24 -3
  7. infrahub/artifacts/models.py +2 -1
  8. infrahub/auth.py +137 -3
  9. infrahub/cli/__init__.py +2 -0
  10. infrahub/cli/db.py +103 -98
  11. infrahub/cli/db_commands/clean_duplicate_schema_fields.py +212 -0
  12. infrahub/cli/dev.py +118 -0
  13. infrahub/cli/tasks.py +46 -0
  14. infrahub/cli/upgrade.py +30 -3
  15. infrahub/computed_attribute/tasks.py +20 -8
  16. infrahub/core/attribute.py +13 -5
  17. infrahub/core/branch/enums.py +1 -1
  18. infrahub/core/branch/models.py +7 -3
  19. infrahub/core/branch/tasks.py +70 -8
  20. infrahub/core/changelog/models.py +4 -12
  21. infrahub/core/constants/__init__.py +3 -0
  22. infrahub/core/constants/infrahubkind.py +1 -0
  23. infrahub/core/diff/model/path.py +4 -0
  24. infrahub/core/diff/payload_builder.py +1 -1
  25. infrahub/core/diff/query/artifact.py +1 -0
  26. infrahub/core/diff/query/field_summary.py +1 -0
  27. infrahub/core/graph/__init__.py +1 -1
  28. infrahub/core/initialization.py +5 -2
  29. infrahub/core/ipam/utilization.py +1 -1
  30. infrahub/core/manager.py +6 -3
  31. infrahub/core/migrations/__init__.py +3 -0
  32. infrahub/core/migrations/exceptions.py +4 -0
  33. infrahub/core/migrations/graph/__init__.py +12 -11
  34. infrahub/core/migrations/graph/load_schema_branch.py +21 -0
  35. infrahub/core/migrations/graph/m013_convert_git_password_credential.py +1 -1
  36. infrahub/core/migrations/graph/m040_duplicated_attributes.py +81 -0
  37. infrahub/core/migrations/graph/m041_profile_attrs_in_db.py +145 -0
  38. infrahub/core/migrations/graph/m042_create_hfid_display_label_in_db.py +164 -0
  39. infrahub/core/migrations/graph/m043_backfill_hfid_display_label_in_db.py +866 -0
  40. infrahub/core/migrations/query/__init__.py +7 -8
  41. infrahub/core/migrations/query/attribute_add.py +8 -6
  42. infrahub/core/migrations/query/attribute_remove.py +134 -0
  43. infrahub/core/migrations/runner.py +54 -0
  44. infrahub/core/migrations/schema/attribute_kind_update.py +9 -3
  45. infrahub/core/migrations/schema/attribute_supports_profile.py +90 -0
  46. infrahub/core/migrations/schema/node_attribute_add.py +35 -4
  47. infrahub/core/migrations/schema/node_attribute_remove.py +13 -109
  48. infrahub/core/migrations/schema/node_kind_update.py +2 -1
  49. infrahub/core/migrations/schema/node_remove.py +2 -1
  50. infrahub/core/migrations/schema/placeholder_dummy.py +3 -2
  51. infrahub/core/migrations/shared.py +52 -19
  52. infrahub/core/node/__init__.py +158 -51
  53. infrahub/core/node/constraints/attribute_uniqueness.py +3 -1
  54. infrahub/core/node/create.py +46 -63
  55. infrahub/core/node/lock_utils.py +70 -44
  56. infrahub/core/node/node_property_attribute.py +230 -0
  57. infrahub/core/node/resource_manager/ip_address_pool.py +2 -1
  58. infrahub/core/node/resource_manager/ip_prefix_pool.py +2 -1
  59. infrahub/core/node/resource_manager/number_pool.py +2 -1
  60. infrahub/core/node/standard.py +1 -1
  61. infrahub/core/protocols.py +7 -1
  62. infrahub/core/query/attribute.py +55 -0
  63. infrahub/core/query/ipam.py +1 -0
  64. infrahub/core/query/node.py +23 -4
  65. infrahub/core/query/relationship.py +1 -0
  66. infrahub/core/registry.py +2 -2
  67. infrahub/core/relationship/constraints/count.py +1 -1
  68. infrahub/core/relationship/model.py +1 -1
  69. infrahub/core/schema/__init__.py +56 -0
  70. infrahub/core/schema/attribute_schema.py +4 -0
  71. infrahub/core/schema/basenode_schema.py +42 -2
  72. infrahub/core/schema/definitions/core/__init__.py +2 -0
  73. infrahub/core/schema/definitions/core/generator.py +2 -0
  74. infrahub/core/schema/definitions/core/group.py +16 -2
  75. infrahub/core/schema/definitions/internal.py +16 -3
  76. infrahub/core/schema/generated/attribute_schema.py +2 -2
  77. infrahub/core/schema/generated/base_node_schema.py +6 -1
  78. infrahub/core/schema/manager.py +22 -1
  79. infrahub/core/schema/node_schema.py +5 -2
  80. infrahub/core/schema/schema_branch.py +300 -8
  81. infrahub/core/schema/schema_branch_display.py +123 -0
  82. infrahub/core/schema/schema_branch_hfid.py +114 -0
  83. infrahub/core/validators/aggregated_checker.py +1 -1
  84. infrahub/core/validators/determiner.py +12 -1
  85. infrahub/core/validators/relationship/peer.py +1 -1
  86. infrahub/core/validators/tasks.py +1 -1
  87. infrahub/database/graph.py +21 -0
  88. infrahub/display_labels/__init__.py +0 -0
  89. infrahub/display_labels/gather.py +48 -0
  90. infrahub/display_labels/models.py +240 -0
  91. infrahub/display_labels/tasks.py +192 -0
  92. infrahub/display_labels/triggers.py +22 -0
  93. infrahub/events/branch_action.py +27 -1
  94. infrahub/events/group_action.py +1 -1
  95. infrahub/events/node_action.py +1 -1
  96. infrahub/generators/constants.py +7 -0
  97. infrahub/generators/models.py +7 -0
  98. infrahub/generators/tasks.py +34 -22
  99. infrahub/git/base.py +4 -1
  100. infrahub/git/integrator.py +23 -15
  101. infrahub/git/models.py +2 -1
  102. infrahub/git/repository.py +22 -5
  103. infrahub/git/tasks.py +66 -10
  104. infrahub/git/utils.py +123 -1
  105. infrahub/graphql/analyzer.py +1 -1
  106. infrahub/graphql/api/endpoints.py +14 -4
  107. infrahub/graphql/manager.py +4 -9
  108. infrahub/graphql/mutations/convert_object_type.py +11 -1
  109. infrahub/graphql/mutations/display_label.py +118 -0
  110. infrahub/graphql/mutations/generator.py +25 -7
  111. infrahub/graphql/mutations/hfid.py +125 -0
  112. infrahub/graphql/mutations/ipam.py +54 -35
  113. infrahub/graphql/mutations/main.py +27 -28
  114. infrahub/graphql/mutations/relationship.py +2 -2
  115. infrahub/graphql/mutations/resource_manager.py +2 -2
  116. infrahub/graphql/mutations/schema.py +5 -5
  117. infrahub/graphql/queries/resource_manager.py +1 -1
  118. infrahub/graphql/resolvers/resolver.py +2 -0
  119. infrahub/graphql/schema.py +4 -0
  120. infrahub/graphql/schema_sort.py +170 -0
  121. infrahub/graphql/types/branch.py +4 -1
  122. infrahub/graphql/types/enums.py +3 -0
  123. infrahub/groups/tasks.py +1 -1
  124. infrahub/hfid/__init__.py +0 -0
  125. infrahub/hfid/gather.py +48 -0
  126. infrahub/hfid/models.py +240 -0
  127. infrahub/hfid/tasks.py +191 -0
  128. infrahub/hfid/triggers.py +22 -0
  129. infrahub/lock.py +67 -16
  130. infrahub/message_bus/types.py +2 -1
  131. infrahub/middleware.py +26 -1
  132. infrahub/permissions/constants.py +2 -0
  133. infrahub/proposed_change/tasks.py +35 -17
  134. infrahub/server.py +21 -4
  135. infrahub/services/__init__.py +8 -5
  136. infrahub/services/adapters/http/__init__.py +5 -0
  137. infrahub/services/adapters/workflow/worker.py +14 -3
  138. infrahub/task_manager/event.py +5 -0
  139. infrahub/task_manager/models.py +7 -0
  140. infrahub/task_manager/task.py +73 -0
  141. infrahub/trigger/catalogue.py +4 -0
  142. infrahub/trigger/models.py +2 -0
  143. infrahub/trigger/setup.py +13 -4
  144. infrahub/trigger/tasks.py +6 -0
  145. infrahub/workers/dependencies.py +10 -1
  146. infrahub/workers/infrahub_async.py +10 -2
  147. infrahub/workflows/catalogue.py +80 -0
  148. infrahub/workflows/initialization.py +21 -0
  149. infrahub/workflows/utils.py +2 -1
  150. infrahub_sdk/checks.py +1 -1
  151. infrahub_sdk/client.py +13 -10
  152. infrahub_sdk/config.py +29 -2
  153. infrahub_sdk/ctl/cli_commands.py +2 -0
  154. infrahub_sdk/ctl/generator.py +4 -0
  155. infrahub_sdk/ctl/graphql.py +184 -0
  156. infrahub_sdk/ctl/schema.py +28 -9
  157. infrahub_sdk/generator.py +7 -1
  158. infrahub_sdk/graphql/__init__.py +12 -0
  159. infrahub_sdk/graphql/constants.py +1 -0
  160. infrahub_sdk/graphql/plugin.py +85 -0
  161. infrahub_sdk/graphql/query.py +77 -0
  162. infrahub_sdk/{graphql.py → graphql/renderers.py} +81 -73
  163. infrahub_sdk/graphql/utils.py +40 -0
  164. infrahub_sdk/protocols.py +14 -0
  165. infrahub_sdk/schema/__init__.py +70 -4
  166. infrahub_sdk/schema/repository.py +8 -0
  167. infrahub_sdk/spec/models.py +7 -0
  168. infrahub_sdk/spec/object.py +53 -44
  169. infrahub_sdk/spec/processors/__init__.py +0 -0
  170. infrahub_sdk/spec/processors/data_processor.py +10 -0
  171. infrahub_sdk/spec/processors/factory.py +34 -0
  172. infrahub_sdk/spec/processors/range_expand_processor.py +56 -0
  173. infrahub_sdk/spec/range_expansion.py +1 -1
  174. infrahub_sdk/transforms.py +1 -1
  175. {infrahub_server-1.5.0b0.dist-info → infrahub_server-1.5.0b2.dist-info}/METADATA +7 -4
  176. {infrahub_server-1.5.0b0.dist-info → infrahub_server-1.5.0b2.dist-info}/RECORD +182 -143
  177. infrahub_testcontainers/container.py +115 -3
  178. infrahub_testcontainers/docker-compose-cluster.test.yml +6 -1
  179. infrahub_testcontainers/docker-compose.test.yml +6 -1
  180. infrahub/core/migrations/graph/m040_profile_attrs_in_db.py +0 -166
  181. {infrahub_server-1.5.0b0.dist-info → infrahub_server-1.5.0b2.dist-info}/LICENSE.txt +0 -0
  182. {infrahub_server-1.5.0b0.dist-info → infrahub_server-1.5.0b2.dist-info}/WHEEL +0 -0
  183. {infrahub_server-1.5.0b0.dist-info → infrahub_server-1.5.0b2.dist-info}/entry_points.txt +0 -0
@@ -29,7 +29,7 @@ INFRAHUB_SERVICES: dict[str, ContainerService] = {
29
29
 
30
30
  PROJECT_ENV_VARIABLES: dict[str, str] = {
31
31
  "MESSAGE_QUEUE_DOCKER_IMAGE": "rabbitmq:3.13.7-management",
32
- "CACHE_DOCKER_IMAGE": "redis:7.2.4",
32
+ "CACHE_DOCKER_IMAGE": "redis:7.2.11",
33
33
  "INFRAHUB_TESTING_DOCKER_IMAGE": "registry.opsmill.io/opsmill/infrahub",
34
34
  "INFRAHUB_TESTING_DOCKER_ENTRYPOINT": f"gunicorn --config backend/infrahub/serve/gunicorn_config.py -w {os.environ.get('INFRAHUB_TESTING_WEB_CONCURRENCY', 4)} --logger-class infrahub.serve.log.GunicornLogger infrahub.server:app", # noqa: E501
35
35
  "INFRAHUB_TESTING_IMAGE_VERSION": infrahub_version,
@@ -152,6 +152,8 @@ class InfrahubDockerCompose(DockerCompose):
152
152
  "INFRAHUB_TESTING_TASKMGR_BACKGROUND_SVC_REPLICAS": "1",
153
153
  "PREFECT_MESSAGING_BROKER": "prefect_redis.messaging",
154
154
  "PREFECT_MESSAGING_CACHE": "prefect_redis.messaging",
155
+ "PREFECT_SERVER_EVENTS_CAUSAL_ORDERING": "prefect_redis.ordering",
156
+ "PREFECT_SERVER_CONCURRENCY_LEASE_STORAGE": "prefect_redis.lease_storage",
155
157
  "PREFECT__SERVER_WEBSERVER_ONLY": "true",
156
158
  "PREFECT_API_DATABASE_MIGRATE_ON_START": "false",
157
159
  "PREFECT_API_BLOCKS_REGISTER_ON_START": "false",
@@ -237,7 +239,9 @@ class InfrahubDockerCompose(DockerCompose):
237
239
  for service_name, service_data in INFRAHUB_SERVICES.items()
238
240
  }
239
241
 
240
- def database_create_backup(self, backup_name: str = "neo4j_database.backup", dest_dir: Path | None = None) -> None:
242
+ def database_create_backup(
243
+ self, backup_name: str = "neo4j_database.backup", dest_dir: Path | None = None, compress: bool = False
244
+ ) -> None:
241
245
  assert self.use_neo4j_enterprise
242
246
 
243
247
  self.exec_in_container(
@@ -245,7 +249,7 @@ class InfrahubDockerCompose(DockerCompose):
245
249
  "neo4j-admin",
246
250
  "database",
247
251
  "backup",
248
- "--compress=false",
252
+ f"--compress={'true' if compress else 'false'}",
249
253
  "--to-path",
250
254
  str(self.internal_backup_dir),
251
255
  ],
@@ -513,3 +517,111 @@ class InfrahubDockerCompose(DockerCompose):
513
517
  )
514
518
  self.start()
515
519
  print("Database restored successfully")
520
+
521
+ def task_manager_create_backup(self, backup_name: str = "prefect.dump", dest_dir: Path | None = None) -> Path:
522
+ """Create a backup of the task manager PostgreSQL database using ``pg_dump``.
523
+
524
+ Args:
525
+ backup_name: Name of the archive file to create. Defaults to ``prefect.dump``.
526
+ dest_dir: Optional host directory where the backup should be copied after it is
527
+ produced. When omitted, the backup remains in ``external_backup_dir``.
528
+
529
+ Returns:
530
+ Path to the backup archive on the host filesystem.
531
+
532
+ Raises:
533
+ FileNotFoundError: If the pg_dump command completes but no archive is produced.
534
+ """
535
+
536
+ service_name = "task-manager-db"
537
+
538
+ try:
539
+ self.get_container(service_name=service_name)
540
+ except ContainerIsNotRunning:
541
+ self.start_container(service_name=service_name)
542
+
543
+ self.external_backup_dir.mkdir(parents=True, exist_ok=True)
544
+
545
+ internal_backup_path = self.internal_backup_dir / backup_name
546
+ dump_command = [
547
+ "pg_dump",
548
+ "--format=custom",
549
+ "--blobs",
550
+ "--no-owner",
551
+ "--no-privileges",
552
+ "--dbname=postgresql://postgres:postgres@localhost:5432/prefect",
553
+ f"--file={internal_backup_path}",
554
+ ]
555
+ self.exec_in_container(command=dump_command, service_name=service_name)
556
+
557
+ source_path = self.external_backup_dir / backup_name
558
+ if not source_path.exists():
559
+ raise FileNotFoundError(f"Backup file {source_path} was not created")
560
+
561
+ final_path = source_path
562
+ if dest_dir:
563
+ dest_dir.mkdir(parents=True, exist_ok=True)
564
+ if dest_dir.resolve() != self.external_backup_dir.resolve():
565
+ final_path = dest_dir / backup_name
566
+ shutil.copy(source_path, final_path)
567
+
568
+ return final_path
569
+
570
+ def task_manager_restore_backup(self, backup_file: Path) -> None:
571
+ """Restore the task manager PostgreSQL database from a ``pg_restore`` archive.
572
+
573
+ Args:
574
+ backup_file: Path to the backup archive on the host filesystem.
575
+
576
+ Raises:
577
+ FileNotFoundError: If the provided backup archive does not exist.
578
+ """
579
+
580
+ if not backup_file.exists():
581
+ raise FileNotFoundError(f"Backup file {backup_file} does not exist")
582
+
583
+ service_name = "task-manager-db"
584
+
585
+ try:
586
+ self.get_container(service_name=service_name)
587
+ except ContainerIsNotRunning:
588
+ self.start_container(service_name=service_name)
589
+
590
+ self.external_backup_dir.mkdir(parents=True, exist_ok=True)
591
+ target_path = self.external_backup_dir / backup_file.name
592
+ shutil.copy(backup_file, target_path)
593
+
594
+ admin_dsn = "postgresql://postgres:postgres@localhost:5432/postgres"
595
+ prefect_dsn = "postgresql://postgres:postgres@localhost:5432/prefect"
596
+ internal_backup_path = self.internal_backup_dir / backup_file.name
597
+
598
+ terminate_sessions_command = [
599
+ "psql",
600
+ f"--dbname={admin_dsn}",
601
+ "--command",
602
+ "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'prefect';",
603
+ ]
604
+ drop_database_command = [
605
+ "psql",
606
+ f"--dbname={admin_dsn}",
607
+ "--command",
608
+ "DROP DATABASE IF EXISTS prefect WITH (FORCE);",
609
+ ]
610
+ create_database_command = [
611
+ "psql",
612
+ f"--dbname={admin_dsn}",
613
+ "--command",
614
+ "CREATE DATABASE prefect OWNER postgres;",
615
+ ]
616
+ restore_command = [
617
+ "pg_restore",
618
+ "--no-owner",
619
+ "--role=postgres",
620
+ f"--dbname={prefect_dsn}",
621
+ str(internal_backup_path),
622
+ ]
623
+
624
+ self.exec_in_container(command=terminate_sessions_command, service_name=service_name)
625
+ self.exec_in_container(command=drop_database_command, service_name=service_name)
626
+ self.exec_in_container(command=create_database_command, service_name=service_name)
627
+ self.exec_in_container(command=restore_command, service_name=service_name)
@@ -37,7 +37,7 @@ services:
37
37
  - ${INFRAHUB_TESTING_MESSAGE_QUEUE_PORT:-0}:15692
38
38
 
39
39
  cache:
40
- image: ${CACHE_DOCKER_IMAGE:-redis:7.2.4}
40
+ image: ${CACHE_DOCKER_IMAGE:-redis:7.2.11}
41
41
  restart: unless-stopped
42
42
  healthcheck:
43
43
  test: ["CMD-SHELL", "redis-cli ping | grep PONG"]
@@ -184,6 +184,8 @@ services:
184
184
 
185
185
  PREFECT_MESSAGING_BROKER:
186
186
  PREFECT_MESSAGING_CACHE:
187
+ PREFECT_SERVER_EVENTS_CAUSAL_ORDERING:
188
+ PREFECT_SERVER_CONCURRENCY_LEASE_STORAGE:
187
189
  PREFECT__SERVER_WEBSERVER_ONLY:
188
190
  PREFECT_API_DATABASE_MIGRATE_ON_START:
189
191
  PREFECT_API_BLOCKS_REGISTER_ON_START:
@@ -225,6 +227,8 @@ services:
225
227
  INFRAHUB_CACHE_ADDRESS: ${INFRAHUB_TESTING_CACHE_ADDRESS}
226
228
  PREFECT_MESSAGING_BROKER: prefect_redis.messaging
227
229
  PREFECT_MESSAGING_CACHE: prefect_redis.messaging
230
+ PREFECT_SERVER_EVENTS_CAUSAL_ORDERING: prefect_redis.ordering
231
+ PREFECT_SERVER_CONCURRENCY_LEASE_STORAGE: prefect_redis.lease_storage
228
232
  PREFECT_REDIS_MESSAGING_HOST: "${INFRAHUB_TESTING_CACHE_ADDRESS:-cache}"
229
233
  PREFECT_REDIS_MESSAGING_DB: "1"
230
234
  PREFECT_REDIS_MESSAGING_CONSUMER_MIN_IDLE_TIME: "30"
@@ -244,6 +248,7 @@ services:
244
248
  - POSTGRES_DB=prefect
245
249
  volumes:
246
250
  - workflow_db:/var/lib/postgresql/data
251
+ - "./${INFRAHUB_TESTING_LOCAL_DB_BACKUP_DIRECTORY}:${INFRAHUB_TESTING_INTERNAL_DB_BACKUP_DIRECTORY}"
247
252
  healthcheck:
248
253
  test: ["CMD-SHELL", "pg_isready"]
249
254
  interval: 10s
@@ -20,7 +20,7 @@ services:
20
20
  - ${INFRAHUB_TESTING_MESSAGE_QUEUE_PORT:-0}:15692
21
21
 
22
22
  cache:
23
- image: ${CACHE_DOCKER_IMAGE:-redis:7.2.4}
23
+ image: ${CACHE_DOCKER_IMAGE:-redis:7.2.11}
24
24
  restart: unless-stopped
25
25
  healthcheck:
26
26
  test: ["CMD-SHELL", "redis-cli ping | grep PONG"]
@@ -95,6 +95,8 @@ services:
95
95
 
96
96
  PREFECT_MESSAGING_BROKER:
97
97
  PREFECT_MESSAGING_CACHE:
98
+ PREFECT_SERVER_EVENTS_CAUSAL_ORDERING:
99
+ PREFECT_SERVER_CONCURRENCY_LEASE_STORAGE:
98
100
  PREFECT__SERVER_WEBSERVER_ONLY:
99
101
  PREFECT_API_DATABASE_MIGRATE_ON_START:
100
102
  PREFECT_API_BLOCKS_REGISTER_ON_START:
@@ -136,6 +138,8 @@ services:
136
138
  INFRAHUB_CACHE_ADDRESS: ${INFRAHUB_TESTING_CACHE_ADDRESS}
137
139
  PREFECT_MESSAGING_BROKER: prefect_redis.messaging
138
140
  PREFECT_MESSAGING_CACHE: prefect_redis.messaging
141
+ PREFECT_SERVER_EVENTS_CAUSAL_ORDERING: prefect_redis.ordering
142
+ PREFECT_SERVER_CONCURRENCY_LEASE_STORAGE: prefect_redis.lease_storage
139
143
  PREFECT_REDIS_MESSAGING_HOST: "${INFRAHUB_TESTING_CACHE_ADDRESS:-cache}"
140
144
  PREFECT_REDIS_MESSAGING_DB: "1"
141
145
  PREFECT_REDIS_MESSAGING_CONSUMER_MIN_IDLE_TIME: "30"
@@ -155,6 +159,7 @@ services:
155
159
  - POSTGRES_DB=prefect
156
160
  volumes:
157
161
  - workflow_db:/var/lib/postgresql/data
162
+ - "./${INFRAHUB_TESTING_LOCAL_DB_BACKUP_DIRECTORY}:${INFRAHUB_TESTING_INTERNAL_DB_BACKUP_DIRECTORY}"
158
163
  healthcheck:
159
164
  test: ["CMD-SHELL", "pg_isready"]
160
165
  interval: 10s
@@ -1,166 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from collections import defaultdict
4
- from typing import TYPE_CHECKING, Any
5
-
6
- from rich.console import Console
7
- from rich.progress import Progress
8
-
9
- from infrahub.core.branch.models import Branch
10
- from infrahub.core.initialization import initialization
11
- from infrahub.core.manager import NodeManager
12
- from infrahub.core.migrations.shared import MigrationResult
13
- from infrahub.core.query import Query, QueryType
14
- from infrahub.core.timestamp import Timestamp
15
- from infrahub.lock import initialize_lock
16
- from infrahub.log import get_logger
17
- from infrahub.profiles.node_applier import NodeProfilesApplier
18
-
19
- from ..shared import ArbitraryMigration
20
-
21
- if TYPE_CHECKING:
22
- from infrahub.core.node import Node
23
- from infrahub.database import InfrahubDatabase
24
-
25
- log = get_logger()
26
-
27
-
28
- class GetProfilesByBranchQuery(Query):
29
- """
30
- Get CoreProfile UUIDs by which branches they have attribute updates on
31
- """
32
-
33
- name = "get_profiles_by_branch"
34
- type = QueryType.READ
35
- insert_return = False
36
-
37
- async def query_init(self, db: InfrahubDatabase, **kwargs: dict[str, Any]) -> None: # noqa: ARG002
38
- query = """
39
- MATCH (profile:CoreProfile)-[:HAS_ATTRIBUTE]->(attr:Attribute)-[e:HAS_VALUE]->(:AttributeValue)
40
- WITH DISTINCT profile.uuid AS profile_uuid, e.branch AS branch
41
- RETURN profile_uuid, collect(branch) AS branches
42
- """
43
- self.add_to_query(query)
44
- self.return_labels = ["profile_uuid", "branches"]
45
-
46
- def get_profile_ids_by_branch(self) -> dict[str, set[str]]:
47
- """Get dictionary of branch names to set of updated profile UUIDs"""
48
- profiles_by_branch = defaultdict(set)
49
- for result in self.get_results():
50
- profile_uuid = result.get_as_type("profile_uuid", str)
51
- branches = result.get_as_type("branches", list[str])
52
- for branch in branches:
53
- profiles_by_branch[branch].add(profile_uuid)
54
- return profiles_by_branch
55
-
56
-
57
- class GetNodesWithProfileUpdatesByBranchQuery(Query):
58
- """
59
- Get Node UUIDs by which branches they have updated profiles on
60
- """
61
-
62
- name = "get_nodes_with_profile_updates_by_branch"
63
- type = QueryType.READ
64
- insert_return = False
65
-
66
- async def query_init(self, db: InfrahubDatabase, **kwargs: dict[str, Any]) -> None: # noqa: ARG002
67
- query = """
68
- MATCH (node:Node)-[e1:IS_RELATED]->(:Relationship {name: "node__profile"})
69
- WHERE NOT node:CoreProfile
70
- WITH DISTINCT node.uuid AS node_uuid, e1.branch AS branch
71
- RETURN node_uuid, collect(branch) AS branches
72
- """
73
- self.add_to_query(query)
74
- self.return_labels = ["node_uuid", "branches"]
75
-
76
- def get_node_ids_by_branch(self) -> dict[str, set[str]]:
77
- """Get dictionary of branch names to set of updated node UUIDs"""
78
- nodes_by_branch = defaultdict(set)
79
- for result in self.get_results():
80
- node_uuid = result.get_as_type("node_uuid", str)
81
- branches = result.get_as_type("branches", list[str])
82
- for branch in branches:
83
- nodes_by_branch[branch].add(node_uuid)
84
- return nodes_by_branch
85
-
86
-
87
- class Migration040(ArbitraryMigration):
88
- """
89
- Save profile attribute values on each node using the profile in the database
90
- For any profile that has updates on a given branch (including default branch)
91
- - run NodeProfilesApplier.apply_profiles on each node related to the profile on that branch
92
- For any node that has an updated relationship to a profile on a given branch
93
- - run NodeProfilesApplier.apply_profiles on the node on that branch
94
- """
95
-
96
- name: str = "040_profile_attrs_in_db"
97
- minimum_version: int = 39
98
-
99
- def __init__(self, *args: Any, **kwargs: Any) -> None:
100
- super().__init__(*args, **kwargs)
101
- self._appliers_by_branch: dict[str, NodeProfilesApplier] = {}
102
-
103
- async def _get_profile_applier(self, db: InfrahubDatabase, branch_name: str) -> NodeProfilesApplier:
104
- if branch_name not in self._appliers_by_branch:
105
- branch = await Branch.get_by_name(db=db, name=branch_name)
106
- self._appliers_by_branch[branch_name] = NodeProfilesApplier(db=db, branch=branch)
107
- return self._appliers_by_branch[branch_name]
108
-
109
- async def validate_migration(self, db: InfrahubDatabase) -> MigrationResult: # noqa: ARG002
110
- return MigrationResult()
111
-
112
- async def execute(self, db: InfrahubDatabase) -> MigrationResult:
113
- console = Console()
114
- result = MigrationResult()
115
- # load schemas from database into registry
116
- initialize_lock()
117
- await initialization(db=db)
118
-
119
- console.print("Gathering profiles for each branch...", end="")
120
- get_profiles_by_branch_query = await GetProfilesByBranchQuery.init(db=db)
121
- await get_profiles_by_branch_query.execute(db=db)
122
- profiles_ids_by_branch = get_profiles_by_branch_query.get_profile_ids_by_branch()
123
-
124
- profiles_by_branch: dict[str, list[Node]] = {}
125
- for branch_name, profile_ids in profiles_ids_by_branch.items():
126
- profiles_map = await NodeManager.get_many(db=db, branch=branch_name, ids=list(profile_ids))
127
- profiles_by_branch[branch_name] = list(profiles_map.values())
128
- console.print("done")
129
-
130
- node_ids_to_update_by_branch: dict[str, set[str]] = defaultdict(set)
131
- total_size = sum(len(profiles) for profiles in profiles_by_branch.values())
132
- with Progress() as progress:
133
- gather_nodes_task = progress.add_task(
134
- "Gathering affected objects for each profile on each branch...", total=total_size
135
- )
136
-
137
- for branch_name, profiles in profiles_by_branch.items():
138
- for profile in profiles:
139
- node_relationship_manager = profile.get_relationship("related_nodes")
140
- node_peers = await node_relationship_manager.get_db_peers(db=db)
141
- node_ids_to_update_by_branch[branch_name].update({str(peer.peer_id) for peer in node_peers})
142
- progress.update(gather_nodes_task, advance=1)
143
-
144
- console.print("Identifying nodes with profile updates by branch...", end="")
145
- get_nodes_with_profile_updates_by_branch_query = await GetNodesWithProfileUpdatesByBranchQuery.init(db=db)
146
- await get_nodes_with_profile_updates_by_branch_query.execute(db=db)
147
- nodes_ids_by_branch = get_nodes_with_profile_updates_by_branch_query.get_node_ids_by_branch()
148
- for branch_name, node_ids in nodes_ids_by_branch.items():
149
- node_ids_to_update_by_branch[branch_name].update(node_ids)
150
- console.print("done")
151
-
152
- right_now = Timestamp()
153
- total_size = sum(len(node_ids) for node_ids in node_ids_to_update_by_branch.values())
154
- with Progress() as progress:
155
- apply_task = progress.add_task("Applying profiles to nodes...", total=total_size)
156
- for branch_name, node_ids in node_ids_to_update_by_branch.items():
157
- applier = await self._get_profile_applier(db=db, branch_name=branch_name)
158
- for node_id in node_ids:
159
- node = await NodeManager.get_one(db=db, branch=branch_name, id=node_id, at=right_now)
160
- if node:
161
- updated_field_names = await applier.apply_profiles(node=node)
162
- if updated_field_names:
163
- await node.save(db=db, fields=updated_field_names, at=right_now)
164
- progress.update(apply_task, advance=1)
165
-
166
- return result