Spaces:
Runtime error
Runtime error
File size: 31,821 Bytes
105b369 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 |
from typing import List, Optional, Union, Tuple
from phi.app.group import AppGroup
from phi.resource.group import ResourceGroup
from phi.docker.app.base import DockerApp
from phi.docker.app.context import DockerBuildContext
from phi.docker.api_client import DockerApiClient
from phi.docker.resource.base import DockerResource
from phi.infra.resources import InfraResources
from phi.workspace.settings import WorkspaceSettings
from phi.utils.log import logger
class DockerResources(InfraResources):
env: str = "dev"
network: str = "phi"
# URL for the Docker server. For example, unix:///var/run/docker.sock or tcp://127.0.0.1:1234
base_url: Optional[str] = None
apps: Optional[List[Union[DockerApp, AppGroup]]] = None
resources: Optional[List[Union[DockerResource, ResourceGroup]]] = None
# -*- Cached Data
_api_client: Optional[DockerApiClient] = None
@property
def docker_client(self) -> DockerApiClient:
if self._api_client is None:
self._api_client = DockerApiClient(base_url=self.base_url)
return self._api_client
def create_resources(
self,
group_filter: Optional[str] = None,
name_filter: Optional[str] = None,
type_filter: Optional[str] = None,
dry_run: Optional[bool] = False,
auto_confirm: Optional[bool] = False,
force: Optional[bool] = None,
pull: Optional[bool] = None,
) -> Tuple[int, int]:
from phi.cli.console import print_info, print_heading, confirm_yes_no
from phi.docker.resource.types import DockerContainer, DockerResourceInstallOrder
logger.debug("-*- Creating DockerResources")
# Build a list of DockerResources to create
resources_to_create: List[DockerResource] = []
if self.resources is not None:
for r in self.resources:
if isinstance(r, ResourceGroup):
resources_from_resource_group = r.get_resources()
if len(resources_from_resource_group) > 0:
for resource_from_resource_group in resources_from_resource_group:
if isinstance(resource_from_resource_group, DockerResource):
resource_from_resource_group.set_workspace_settings(
workspace_settings=self.workspace_settings
)
if resource_from_resource_group.group is None and self.name is not None:
resource_from_resource_group.group = self.name
if resource_from_resource_group.should_create(
group_filter=group_filter,
name_filter=name_filter,
type_filter=type_filter,
):
resources_to_create.append(resource_from_resource_group)
elif isinstance(r, DockerResource):
r.set_workspace_settings(workspace_settings=self.workspace_settings)
if r.group is None and self.name is not None:
r.group = self.name
if r.should_create(
group_filter=group_filter,
name_filter=name_filter,
type_filter=type_filter,
):
r.set_workspace_settings(workspace_settings=self.workspace_settings)
resources_to_create.append(r)
# Build a list of DockerApps to create
apps_to_create: List[DockerApp] = []
if self.apps is not None:
for app in self.apps:
if isinstance(app, AppGroup):
apps_from_app_group = app.get_apps()
if len(apps_from_app_group) > 0:
for app_from_app_group in apps_from_app_group:
if isinstance(app_from_app_group, DockerApp):
if app_from_app_group.group is None and self.name is not None:
app_from_app_group.group = self.name
if app_from_app_group.should_create(group_filter=group_filter):
apps_to_create.append(app_from_app_group)
elif isinstance(app, DockerApp):
if app.group is None and self.name is not None:
app.group = self.name
if app.should_create(group_filter=group_filter):
apps_to_create.append(app)
# Get the list of DockerResources from the DockerApps
if len(apps_to_create) > 0:
logger.debug(f"Found {len(apps_to_create)} apps to create")
for app in apps_to_create:
app.set_workspace_settings(workspace_settings=self.workspace_settings)
app_resources = app.get_resources(build_context=DockerBuildContext(network=self.network))
if len(app_resources) > 0:
# If the app has dependencies, add the resources from the
# dependencies first to the list of resources to create
if app.depends_on is not None:
for dep in app.depends_on:
if isinstance(dep, DockerApp):
dep.set_workspace_settings(workspace_settings=self.workspace_settings)
dep_resources = dep.get_resources(
build_context=DockerBuildContext(network=self.network)
)
if len(dep_resources) > 0:
for dep_resource in dep_resources:
if isinstance(dep_resource, DockerResource):
resources_to_create.append(dep_resource)
# Add the resources from the app to the list of resources to create
for app_resource in app_resources:
if isinstance(app_resource, DockerResource) and app_resource.should_create(
group_filter=group_filter, name_filter=name_filter, type_filter=type_filter
):
resources_to_create.append(app_resource)
# Sort the DockerResources in install order
resources_to_create.sort(key=lambda x: DockerResourceInstallOrder.get(x.__class__.__name__, 5000))
# Deduplicate DockerResources
deduped_resources_to_create: List[DockerResource] = []
for r in resources_to_create:
if r not in deduped_resources_to_create:
deduped_resources_to_create.append(r)
# Implement dependency sorting
final_docker_resources: List[DockerResource] = []
logger.debug("-*- Building DockerResources dependency graph")
for docker_resource in deduped_resources_to_create:
# Logic to follow if resource has dependencies
if docker_resource.depends_on is not None:
# Add the dependencies before the resource itself
for dep in docker_resource.depends_on:
if isinstance(dep, DockerResource):
if dep not in final_docker_resources:
logger.debug(f"-*- Adding {dep.name}, dependency of {docker_resource.name}")
final_docker_resources.append(dep)
# Add the resource to be created after its dependencies
if docker_resource not in final_docker_resources:
logger.debug(f"-*- Adding {docker_resource.name}")
final_docker_resources.append(docker_resource)
else:
# Add the resource to be created if it has no dependencies
if docker_resource not in final_docker_resources:
logger.debug(f"-*- Adding {docker_resource.name}")
final_docker_resources.append(docker_resource)
# Track the total number of DockerResources to create for validation
num_resources_to_create: int = len(final_docker_resources)
num_resources_created: int = 0
if num_resources_to_create == 0:
return 0, 0
if dry_run:
print_heading("--**- Docker resources to create:")
for resource in final_docker_resources:
print_info(f" -+-> {resource.get_resource_type()}: {resource.get_resource_name()}")
print_info(f"\nNetwork: {self.network}")
print_info(f"Total {num_resources_to_create} resources")
return 0, 0
# Validate resources to be created
if not auto_confirm:
print_heading("\n--**-- Confirm resources to create:")
for resource in final_docker_resources:
print_info(f" -+-> {resource.get_resource_type()}: {resource.get_resource_name()}")
print_info(f"\nNetwork: {self.network}")
print_info(f"Total {num_resources_to_create} resources")
confirm = confirm_yes_no("\nConfirm deploy")
if not confirm:
print_info("-*-")
print_info("-*- Skipping create")
print_info("-*-")
return 0, 0
for resource in final_docker_resources:
print_info(f"\n-==+==- {resource.get_resource_type()}: {resource.get_resource_name()}")
if force is True:
resource.force = True
if pull is True:
resource.pull = True
if isinstance(resource, DockerContainer):
if resource.network is None and self.network is not None:
resource.network = self.network
# logger.debug(resource)
try:
_resource_created = resource.create(docker_client=self.docker_client)
if _resource_created:
num_resources_created += 1
else:
if self.workspace_settings is not None and not self.workspace_settings.continue_on_create_failure:
return num_resources_created, num_resources_to_create
except Exception as e:
logger.error(f"Failed to create {resource.get_resource_type()}: {resource.get_resource_name()}")
logger.error(e)
logger.error("Please fix and try again...")
print_heading(f"\n--**-- Resources created: {num_resources_created}/{num_resources_to_create}")
if num_resources_to_create != num_resources_created:
logger.error(
f"Resources created: {num_resources_created} do not match resources required: {num_resources_to_create}"
) # noqa: E501
return num_resources_created, num_resources_to_create
def delete_resources(
self,
group_filter: Optional[str] = None,
name_filter: Optional[str] = None,
type_filter: Optional[str] = None,
dry_run: Optional[bool] = False,
auto_confirm: Optional[bool] = False,
force: Optional[bool] = None,
) -> Tuple[int, int]:
from phi.cli.console import print_info, print_heading, confirm_yes_no
from phi.docker.resource.types import DockerContainer, DockerResourceInstallOrder
logger.debug("-*- Deleting DockerResources")
# Build a list of DockerResources to delete
resources_to_delete: List[DockerResource] = []
if self.resources is not None:
for r in self.resources:
if isinstance(r, ResourceGroup):
resources_from_resource_group = r.get_resources()
if len(resources_from_resource_group) > 0:
for resource_from_resource_group in resources_from_resource_group:
if isinstance(resource_from_resource_group, DockerResource):
resource_from_resource_group.set_workspace_settings(
workspace_settings=self.workspace_settings
)
if resource_from_resource_group.group is None and self.name is not None:
resource_from_resource_group.group = self.name
if resource_from_resource_group.should_delete(
group_filter=group_filter,
name_filter=name_filter,
type_filter=type_filter,
):
resources_to_delete.append(resource_from_resource_group)
elif isinstance(r, DockerResource):
r.set_workspace_settings(workspace_settings=self.workspace_settings)
if r.group is None and self.name is not None:
r.group = self.name
if r.should_delete(
group_filter=group_filter,
name_filter=name_filter,
type_filter=type_filter,
):
r.set_workspace_settings(workspace_settings=self.workspace_settings)
resources_to_delete.append(r)
# Build a list of DockerApps to delete
apps_to_delete: List[DockerApp] = []
if self.apps is not None:
for app in self.apps:
if isinstance(app, AppGroup):
apps_from_app_group = app.get_apps()
if len(apps_from_app_group) > 0:
for app_from_app_group in apps_from_app_group:
if isinstance(app_from_app_group, DockerApp):
if app_from_app_group.group is None and self.name is not None:
app_from_app_group.group = self.name
if app_from_app_group.should_delete(group_filter=group_filter):
apps_to_delete.append(app_from_app_group)
elif isinstance(app, DockerApp):
if app.group is None and self.name is not None:
app.group = self.name
if app.should_delete(group_filter=group_filter):
apps_to_delete.append(app)
# Get the list of DockerResources from the DockerApps
if len(apps_to_delete) > 0:
logger.debug(f"Found {len(apps_to_delete)} apps to delete")
for app in apps_to_delete:
app.set_workspace_settings(workspace_settings=self.workspace_settings)
app_resources = app.get_resources(build_context=DockerBuildContext(network=self.network))
if len(app_resources) > 0:
# Add the resources from the app to the list of resources to delete
for app_resource in app_resources:
if isinstance(app_resource, DockerResource) and app_resource.should_delete(
group_filter=group_filter, name_filter=name_filter, type_filter=type_filter
):
resources_to_delete.append(app_resource)
# # If the app has dependencies, add the resources from the
# # dependencies to the list of resources to delete
# if app.depends_on is not None:
# for dep in app.depends_on:
# if isinstance(dep, DockerApp):
# dep.set_workspace_settings(workspace_settings=self.workspace_settings)
# dep_resources = dep.get_resources(
# build_context=DockerBuildContext(network=self.network)
# )
# if len(dep_resources) > 0:
# for dep_resource in dep_resources:
# if isinstance(dep_resource, DockerResource):
# resources_to_delete.append(dep_resource)
# Sort the DockerResources in install order
resources_to_delete.sort(key=lambda x: DockerResourceInstallOrder.get(x.__class__.__name__, 5000), reverse=True)
# Deduplicate DockerResources
deduped_resources_to_delete: List[DockerResource] = []
for r in resources_to_delete:
if r not in deduped_resources_to_delete:
deduped_resources_to_delete.append(r)
# Implement dependency sorting
final_docker_resources: List[DockerResource] = []
logger.debug("-*- Building DockerResources dependency graph")
for docker_resource in deduped_resources_to_delete:
# Logic to follow if resource has dependencies
if docker_resource.depends_on is not None:
# 1. Reverse the order of dependencies
docker_resource.depends_on.reverse()
# 2. Remove the dependencies if they are already added to the final_docker_resources
for dep in docker_resource.depends_on:
if dep in final_docker_resources:
logger.debug(f"-*- Removing {dep.name}, dependency of {docker_resource.name}")
final_docker_resources.remove(dep)
# 3. Add the resource to be deleted before its dependencies
if docker_resource not in final_docker_resources:
logger.debug(f"-*- Adding {docker_resource.name}")
final_docker_resources.append(docker_resource)
# 4. Add the dependencies back in reverse order
for dep in docker_resource.depends_on:
if isinstance(dep, DockerResource):
if dep not in final_docker_resources:
logger.debug(f"-*- Adding {dep.name}, dependency of {docker_resource.name}")
final_docker_resources.append(dep)
else:
# Add the resource to be deleted if it has no dependencies
if docker_resource not in final_docker_resources:
logger.debug(f"-*- Adding {docker_resource.name}")
final_docker_resources.append(docker_resource)
# Track the total number of DockerResources to delete for validation
num_resources_to_delete: int = len(final_docker_resources)
num_resources_deleted: int = 0
if num_resources_to_delete == 0:
return 0, 0
if dry_run:
print_heading("--**- Docker resources to delete:")
for resource in final_docker_resources:
print_info(f" -+-> {resource.get_resource_type()}: {resource.get_resource_name()}")
print_info("")
print_info(f"\nNetwork: {self.network}")
print_info(f"Total {num_resources_to_delete} resources")
return 0, 0
# Validate resources to be deleted
if not auto_confirm:
print_heading("\n--**-- Confirm resources to delete:")
for resource in final_docker_resources:
print_info(f" -+-> {resource.get_resource_type()}: {resource.get_resource_name()}")
print_info("")
print_info(f"\nNetwork: {self.network}")
print_info(f"Total {num_resources_to_delete} resources")
confirm = confirm_yes_no("\nConfirm delete")
if not confirm:
print_info("-*-")
print_info("-*- Skipping delete")
print_info("-*-")
return 0, 0
for resource in final_docker_resources:
print_info(f"\n-==+==- {resource.get_resource_type()}: {resource.get_resource_name()}")
if force is True:
resource.force = True
if isinstance(resource, DockerContainer):
if resource.network is None and self.network is not None:
resource.network = self.network
# logger.debug(resource)
try:
_resource_deleted = resource.delete(docker_client=self.docker_client)
if _resource_deleted:
num_resources_deleted += 1
else:
if self.workspace_settings is not None and not self.workspace_settings.continue_on_delete_failure:
return num_resources_deleted, num_resources_to_delete
except Exception as e:
logger.error(f"Failed to delete {resource.get_resource_type()}: {resource.get_resource_name()}")
logger.error(e)
logger.error("Please fix and try again...")
print_heading(f"\n--**-- Resources deleted: {num_resources_deleted}/{num_resources_to_delete}")
if num_resources_to_delete != num_resources_deleted:
logger.error(
f"Resources deleted: {num_resources_deleted} do not match resources required: {num_resources_to_delete}"
) # noqa: E501
return num_resources_deleted, num_resources_to_delete
def update_resources(
self,
group_filter: Optional[str] = None,
name_filter: Optional[str] = None,
type_filter: Optional[str] = None,
dry_run: Optional[bool] = False,
auto_confirm: Optional[bool] = False,
force: Optional[bool] = None,
pull: Optional[bool] = None,
) -> Tuple[int, int]:
from phi.cli.console import print_info, print_heading, confirm_yes_no
from phi.docker.resource.types import DockerContainer, DockerResourceInstallOrder
logger.debug("-*- Updating DockerResources")
# Build a list of DockerResources to update
resources_to_update: List[DockerResource] = []
if self.resources is not None:
for r in self.resources:
if isinstance(r, ResourceGroup):
resources_from_resource_group = r.get_resources()
if len(resources_from_resource_group) > 0:
for resource_from_resource_group in resources_from_resource_group:
if isinstance(resource_from_resource_group, DockerResource):
resource_from_resource_group.set_workspace_settings(
workspace_settings=self.workspace_settings
)
if resource_from_resource_group.group is None and self.name is not None:
resource_from_resource_group.group = self.name
if resource_from_resource_group.should_update(
group_filter=group_filter,
name_filter=name_filter,
type_filter=type_filter,
):
resources_to_update.append(resource_from_resource_group)
elif isinstance(r, DockerResource):
r.set_workspace_settings(workspace_settings=self.workspace_settings)
if r.group is None and self.name is not None:
r.group = self.name
if r.should_update(
group_filter=group_filter,
name_filter=name_filter,
type_filter=type_filter,
):
r.set_workspace_settings(workspace_settings=self.workspace_settings)
resources_to_update.append(r)
# Build a list of DockerApps to update
apps_to_update: List[DockerApp] = []
if self.apps is not None:
for app in self.apps:
if isinstance(app, AppGroup):
apps_from_app_group = app.get_apps()
if len(apps_from_app_group) > 0:
for app_from_app_group in apps_from_app_group:
if isinstance(app_from_app_group, DockerApp):
if app_from_app_group.group is None and self.name is not None:
app_from_app_group.group = self.name
if app_from_app_group.should_update(group_filter=group_filter):
apps_to_update.append(app_from_app_group)
elif isinstance(app, DockerApp):
if app.group is None and self.name is not None:
app.group = self.name
if app.should_update(group_filter=group_filter):
apps_to_update.append(app)
# Get the list of DockerResources from the DockerApps
if len(apps_to_update) > 0:
logger.debug(f"Found {len(apps_to_update)} apps to update")
for app in apps_to_update:
app.set_workspace_settings(workspace_settings=self.workspace_settings)
app_resources = app.get_resources(build_context=DockerBuildContext(network=self.network))
if len(app_resources) > 0:
# # If the app has dependencies, add the resources from the
# # dependencies first to the list of resources to update
# if app.depends_on is not None:
# for dep in app.depends_on:
# if isinstance(dep, DockerApp):
# dep.set_workspace_settings(workspace_settings=self.workspace_settings)
# dep_resources = dep.get_resources(
# build_context=DockerBuildContext(network=self.network)
# )
# if len(dep_resources) > 0:
# for dep_resource in dep_resources:
# if isinstance(dep_resource, DockerResource):
# resources_to_update.append(dep_resource)
# Add the resources from the app to the list of resources to update
for app_resource in app_resources:
if isinstance(app_resource, DockerResource) and app_resource.should_update(
group_filter=group_filter, name_filter=name_filter, type_filter=type_filter
):
resources_to_update.append(app_resource)
# Sort the DockerResources in install order
resources_to_update.sort(key=lambda x: DockerResourceInstallOrder.get(x.__class__.__name__, 5000), reverse=True)
# Deduplicate DockerResources
deduped_resources_to_update: List[DockerResource] = []
for r in resources_to_update:
if r not in deduped_resources_to_update:
deduped_resources_to_update.append(r)
# Implement dependency sorting
final_docker_resources: List[DockerResource] = []
logger.debug("-*- Building DockerResources dependency graph")
for docker_resource in deduped_resources_to_update:
# Logic to follow if resource has dependencies
if docker_resource.depends_on is not None:
# Add the dependencies before the resource itself
for dep in docker_resource.depends_on:
if isinstance(dep, DockerResource):
if dep not in final_docker_resources:
logger.debug(f"-*- Adding {dep.name}, dependency of {docker_resource.name}")
final_docker_resources.append(dep)
# Add the resource to be created after its dependencies
if docker_resource not in final_docker_resources:
logger.debug(f"-*- Adding {docker_resource.name}")
final_docker_resources.append(docker_resource)
else:
# Add the resource to be created if it has no dependencies
if docker_resource not in final_docker_resources:
logger.debug(f"-*- Adding {docker_resource.name}")
final_docker_resources.append(docker_resource)
# Track the total number of DockerResources to update for validation
num_resources_to_update: int = len(final_docker_resources)
num_resources_updated: int = 0
if num_resources_to_update == 0:
return 0, 0
if dry_run:
print_heading("--**- Docker resources to update:")
for resource in final_docker_resources:
print_info(f" -+-> {resource.get_resource_type()}: {resource.get_resource_name()}")
print_info("")
print_info(f"\nNetwork: {self.network}")
print_info(f"Total {num_resources_to_update} resources")
return 0, 0
# Validate resources to be updated
if not auto_confirm:
print_heading("\n--**-- Confirm resources to update:")
for resource in final_docker_resources:
print_info(f" -+-> {resource.get_resource_type()}: {resource.get_resource_name()}")
print_info("")
print_info(f"\nNetwork: {self.network}")
print_info(f"Total {num_resources_to_update} resources")
confirm = confirm_yes_no("\nConfirm patch")
if not confirm:
print_info("-*-")
print_info("-*- Skipping update")
print_info("-*-")
return 0, 0
for resource in final_docker_resources:
print_info(f"\n-==+==- {resource.get_resource_type()}: {resource.get_resource_name()}")
if force is True:
resource.force = True
if pull is True:
resource.pull = True
if isinstance(resource, DockerContainer):
if resource.network is None and self.network is not None:
resource.network = self.network
# logger.debug(resource)
try:
_resource_updated = resource.update(docker_client=self.docker_client)
if _resource_updated:
num_resources_updated += 1
else:
if self.workspace_settings is not None and not self.workspace_settings.continue_on_patch_failure:
return num_resources_updated, num_resources_to_update
except Exception as e:
logger.error(f"Failed to update {resource.get_resource_type()}: {resource.get_resource_name()}")
logger.error(e)
logger.error("Please fix and try again...")
print_heading(f"\n--**-- Resources updated: {num_resources_updated}/{num_resources_to_update}")
if num_resources_to_update != num_resources_updated:
logger.error(
f"Resources updated: {num_resources_updated} do not match resources required: {num_resources_to_update}"
) # noqa: E501
return num_resources_updated, num_resources_to_update
def save_resources(
self,
group_filter: Optional[str] = None,
name_filter: Optional[str] = None,
type_filter: Optional[str] = None,
workspace_settings: Optional[WorkspaceSettings] = None,
) -> Tuple[int, int]:
raise NotImplementedError
|