|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | + |
| 5 | +from fastapi import status as http_status |
| 6 | + |
| 7 | +from app.api.cloud_account.cloud_accounts_conf.aws import AWSConfigStrategy |
| 8 | +from app.api.cloud_account.cloud_accounts_conf.azure import ( |
| 9 | + AzureCNRConfigStrategy, |
| 10 | + AzureTenantConfigStrategy, |
| 11 | +) |
| 12 | +from app.api.cloud_account.cloud_accounts_conf.cloud_config_strategy import ( |
| 13 | + CloudConfigStrategy, |
| 14 | +) |
| 15 | +from app.api.cloud_account.cloud_accounts_conf.gcp import GCPCNRConfigStrategy |
| 16 | +from app.core.exceptions import ( |
| 17 | + CloudAccountConfigError, |
| 18 | + OptScaleAPIResponseError, |
| 19 | +) |
| 20 | +from app.optscale_api.cloud_accounts import OptScaleCloudAccountAPI |
| 21 | + |
| 22 | +logger = logging.getLogger(__name__) |
| 23 | + |
| 24 | + |
| 25 | +class CloudStrategyConfiguration: |
| 26 | + ALLOWED_PROVIDERS = { |
| 27 | + "aws_cnr": AWSConfigStrategy, |
| 28 | + "gcp_cnr": GCPCNRConfigStrategy, |
| 29 | + "azure_cnr": AzureCNRConfigStrategy, |
| 30 | + "azure_tenant": AzureTenantConfigStrategy, |
| 31 | + } |
| 32 | + |
| 33 | + def __init__( |
| 34 | + self, |
| 35 | + name: str, |
| 36 | + provider_type: str, |
| 37 | + auto_import: bool = True, |
| 38 | + process_recommendations: bool = True, # noqa: E501 |
| 39 | + config: dict = None, |
| 40 | + ): |
| 41 | + self.name = name |
| 42 | + self.type = provider_type |
| 43 | + self.config = config if config else {} |
| 44 | + self.auto_import = auto_import |
| 45 | + self.process_recommendations = process_recommendations |
| 46 | + |
| 47 | + def select_strategy(self): |
| 48 | + """ |
| 49 | + This method checks if the Cloud Account type is allowed. |
| 50 | + If it's valid, an instance of the Cloud Account Class's Strategy |
| 51 | + will be created and validated. |
| 52 | + :return: |
| 53 | + :rtype: |
| 54 | + """ |
| 55 | + if self.type not in self.ALLOWED_PROVIDERS: |
| 56 | + raise OptScaleAPIResponseError( |
| 57 | + title="Wrong Cloud Account", |
| 58 | + error_code="OE0436", |
| 59 | + reason=f"{self.type} is not supported", |
| 60 | + params=[f"{self.type}"], |
| 61 | + status_code=http_status.HTTP_403_FORBIDDEN, |
| 62 | + ) |
| 63 | + |
| 64 | + strategy_class = self.ALLOWED_PROVIDERS[self.type] |
| 65 | + strategy = strategy_class(optscale_cloud_account_api=OptScaleCloudAccountAPI()) |
| 66 | + strategy.validate_config(config=self.config) |
| 67 | + cloud_account_type = self.config.get("type") |
| 68 | + logger.info(f"Cloud Account Conf for {cloud_account_type} has been validated") |
| 69 | + return strategy |
| 70 | + |
| 71 | + |
| 72 | +async def build_payload_dict( |
| 73 | + config: CloudStrategyConfiguration, required_fields: dict | None = None |
| 74 | +): |
| 75 | + """ |
| 76 | + This function builds the configuration dict that will be used |
| 77 | + as payload for linking a given Cloud Account with a user organization. |
| 78 | + :param required_fields: Optional. The required fields to be available in order to build |
| 79 | + the conf. |
| 80 | + :param config: An instance of CloudStrategyConfiguration with the fields to process |
| 81 | + :return: two dictionaries. One is the datasource_conf with the expected fields |
| 82 | + { 'auto_import': False, |
| 83 | + 'config': {'access_key_id': 'ciao', 'secret_access_key': 'cckkckdkkdskd'}, 'name': 'Test', |
| 84 | + 'process_recommendations': False, 'type': 'aws_cnr'} |
| 85 | + The second one is needed to check if there are missing fields. If the missing_fields is |
| 86 | + not empty, it means that one or more of the required fields are missing. |
| 87 | +
|
| 88 | + """ |
| 89 | + if required_fields is None: # pragma: no cover |
| 90 | + required_fields = { |
| 91 | + "name", |
| 92 | + "type", |
| 93 | + "config", |
| 94 | + "auto_import", |
| 95 | + "process_recommendations", |
| 96 | + } |
| 97 | + cloud_account_payload = { |
| 98 | + key: value for key, value in config.__dict__.items() if key in required_fields |
| 99 | + } |
| 100 | + # Ensure all required fields are present |
| 101 | + missing_fields = required_fields - cloud_account_payload.keys() |
| 102 | + return cloud_account_payload, missing_fields |
| 103 | + |
| 104 | + |
| 105 | +class CloudStrategyManager: |
| 106 | + def __init__(self, strategy: CloudConfigStrategy): |
| 107 | + self.strategy = strategy |
| 108 | + |
| 109 | + async def add_cloud_account( |
| 110 | + self, config: CloudStrategyConfiguration, org_id: str, user_access_token: str |
| 111 | + ): |
| 112 | + """ |
| 113 | + Link the given Cloud Account Configuration with |
| 114 | + the user's organization. |
| 115 | +
|
| 116 | + :param config: An instance of CloudStrategyConfiguration with the chosen Cloud Account |
| 117 | + configuration |
| 118 | + :param org_id: The user's organization ID to be linked with the Cloud Account. |
| 119 | + :param user_access_token: The user's access token |
| 120 | + :return: If the datasource is created, a dict like this one will be returned |
| 121 | + { |
| 122 | + "deleted_at": 0, |
| 123 | + "id": "8e8501fa-403a-477b-bd6f-e7569f277f54", |
| 124 | + "created_at": 1736349441, |
| 125 | + "name": "Test2", |
| 126 | + "type": "azure_tenant", |
| 127 | + "config": { |
| 128 | + "client_id": "my_client_id", |
| 129 | + "tenant": "my_tenant_id" |
| 130 | + }, |
| 131 | + "organization_id": "my_org_id", |
| 132 | + "auto_import": false, |
| 133 | + "import_period": 1, |
| 134 | + "last_import_at": 0, |
| 135 | + "last_import_modified_at": 0, |
| 136 | + "account_id": "my_account_id", |
| 137 | + "process_recommendations": false, |
| 138 | + "last_import_attempt_at": 0, |
| 139 | + "last_import_attempt_error": null, |
| 140 | + "last_getting_metrics_at": 0, |
| 141 | + "last_getting_metric_attempt_at": 0, |
| 142 | + "last_getting_metric_attempt_error": null, |
| 143 | + "cleaned_at": 0, |
| 144 | + "parent_id": null |
| 145 | + } |
| 146 | + raises: ValueError if the previously built CloudStrategyConfiguration is tampered. |
| 147 | + Rethrow OptScaleAPIResponseError if an error occurred during the communication with the |
| 148 | + OptScale API. |
| 149 | + """ |
| 150 | + if not isinstance(config, CloudStrategyConfiguration): |
| 151 | + raise CloudAccountConfigError |
| 152 | + |
| 153 | + cloud_account_payload, missing_fields = await build_payload_dict(config) |
| 154 | + if missing_fields: |
| 155 | + logger.error( |
| 156 | + "Something has been altered in the CloudStrategyConfiguration." |
| 157 | + "There are missing required fields in the Cloud Account Conf: {missing_fields}" |
| 158 | + ) # noqa: E501 |
| 159 | + raise ValueError( |
| 160 | + f"Missing required fields in the Cloud Account Conf: {missing_fields}" |
| 161 | + ) |
| 162 | + |
| 163 | + response = await self.strategy.link_cloud_account_to_org( |
| 164 | + config=cloud_account_payload, |
| 165 | + org_id=org_id, |
| 166 | + user_access_token=user_access_token, |
| 167 | + ) |
| 168 | + return response |
0 commit comments