Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add Region service #3

Merged
merged 1 commit into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/spaceone/inventory_v2/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
name = 'inventory_v2'
1 change: 1 addition & 0 deletions src/spaceone/inventory_v2/error/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from spaceone.inventory_v2.error.region import *
9 changes: 9 additions & 0 deletions src/spaceone/inventory_v2/error/region.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from spaceone.core.error import *


class ERROR_NOT_FOUND_USER_IN_REGION(ERROR_BASE):
_message = 'A user "{user_id}" is not exist in region ({region_id}).'


class ERROR_ALREADY_EXIST_USER_IN_REGION(ERROR_BASE):
_message = 'A user "{user_id}" is already exist in region ({region_id}).'
2 changes: 2 additions & 0 deletions src/spaceone/inventory_v2/info/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from spaceone.inventory_v2.info.common_info import *
from spaceone.inventory_v2.info.region_info import *
20 changes: 20 additions & 0 deletions src/spaceone/inventory_v2/info/common_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from google.protobuf.empty_pb2 import Empty
from spaceone.core.pygrpc.message_type import *

__all__ = ['EmptyInfo', 'StatisticsInfo', 'AnalyzeInfo', 'ExportInfo']


def EmptyInfo():
return Empty()


def StatisticsInfo(result):
return change_struct_type(result)


def AnalyzeInfo(result):
return change_struct_type(result)


def ExportInfo(result):
return change_struct_type(result)
38 changes: 38 additions & 0 deletions src/spaceone/inventory_v2/info/region_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import functools
import logging
from spaceone.api.inventory.v2 import region_pb2
from spaceone.core.pygrpc.message_type import *
from spaceone.core import utils
from spaceone.inventory_v2.model.region_model import Region

__all__ = ["RegionInfo", "RegionsInfo"]

_LOGGER = logging.getLogger(__name__)

def RegionInfo(region_vo: Region, minimal=False):
info = {
"region_id": region_vo.region_id,
"name": region_vo.name,
"region_code": region_vo.region_code,
"provider": region_vo.provider,
}

if not minimal:
info.update(
{
"region_key": region_vo.region_key,
"tags": change_struct_type(region_vo.tags),
"domain_id": region_vo.domain_id,
"created_at": utils.datetime_to_iso8601(region_vo.created_at),
"updated_at": utils.datetime_to_iso8601(region_vo.updated_at),
}
)

return region_pb2.RegionInfo(**info)


def RegionsInfo(region_vos, total_count, **kwargs):
return region_pb2.RegionsInfo(
results=list(map(functools.partial(RegionInfo, **kwargs), region_vos)),
total_count=total_count,
)
2 changes: 2 additions & 0 deletions src/spaceone/inventory_v2/interface/grpc/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from spaceone.core.pygrpc.server import GRPCServer
from .region import Region

_all_ = ["app"]

app = GRPCServer()
app.add_service(Region)
45 changes: 45 additions & 0 deletions src/spaceone/inventory_v2/interface/grpc/region.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from spaceone.api.inventory.v2 import region_pb2, region_pb2_grpc
from spaceone.core.pygrpc import BaseAPI

class Region(BaseAPI, region_pb2_grpc.RegionServicer):

pb2 = region_pb2
pb2_grpc = region_pb2_grpc

def create(self, request, context):
params, metadata = self.parse_request(request, context)

with self.locator.get_service('RegionService', metadata) as region_service:
return self.locator.get_info('RegionInfo', region_service.create(params))

def update(self, request, context):
params, metadata = self.parse_request(request, context)

with self.locator.get_service('RegionService', metadata) as region_service:
return self.locator.get_info('RegionInfo', region_service.update(params))

def delete(self, request, context):
params, metadata = self.parse_request(request, context)

with self.locator.get_service('RegionService', metadata) as region_service:
region_service.delete(params)
return self.locator.get_info('EmptyInfo')

def get(self, request, context):
params, metadata = self.parse_request(request, context)

with self.locator.get_service('RegionService', metadata) as region_service:
return self.locator.get_info('RegionInfo', region_service.get(params))

def list(self, request, context):
params, metadata = self.parse_request(request, context)

with self.locator.get_service('RegionService', metadata) as region_service:
region_vos, total_count = region_service.list(params)
return self.locator.get_info('RegionsInfo', region_vos, total_count, minimal=self.get_minimal(params))

def stat(self, request, context):
params, metadata = self.parse_request(request, context)

with self.locator.get_service('RegionService', metadata) as region_service:
return self.locator.get_info('StatisticsInfo', region_service.stat(params))
Empty file.
43 changes: 43 additions & 0 deletions src/spaceone/inventory_v2/lib/resource_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from typing import Tuple
from spaceone.core.error import *


class ResourceManager(object):
resource_keys: list = None
query_method = None

"""
This is used by collector
"""

def find_resources(self, query: dict) -> Tuple[list, int]:
self._check_resource_finder_state()
query["only"] = self.resource_keys

resources = []
vos, total_count = getattr(self, self.query_method)(query)

for vo in vos:
data = {}
for key in self.resource_keys:
data[key] = getattr(vo, key)

resources.append(data)

return resources, total_count

def delete_resources(self, query: dict) -> int:
self._check_resource_finder_state()
query["only"] = self.resource_keys + ["updated_at"]

vos, total_count = getattr(self, self.query_method)(query)
vos.delete()

return total_count

def _check_resource_finder_state(self) -> None:
if not (self.resource_keys and self.query_method):
raise ERROR_UNKNOWN(message="ResourceManager is not set.")

if getattr(self, self.query_method, None) is None:
raise ERROR_UNKNOWN(message="ResourceManager is not set.")
1 change: 1 addition & 0 deletions src/spaceone/inventory_v2/manager/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from spaceone.inventory_v2.manager.region_manager import RegionManager
59 changes: 59 additions & 0 deletions src/spaceone/inventory_v2/manager/region_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import logging
from typing import Tuple

from spaceone.core.model.mongo_model import QuerySet
from spaceone.core.manager import BaseManager
from spaceone.inventory_v2.lib.resource_manager import ResourceManager
from spaceone.inventory_v2.model.region_model import Region

_LOGGER = logging.getLogger(__name__)


class RegionManager(BaseManager, ResourceManager):
resource_keys = ["region_id"]
query_method = "list_regions"

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.region_model: Region = self.locator.get_model("Region")

def create_region(self, params: dict) -> Region:
def _rollback(vo: Region):
_LOGGER.info(f"[ROLLBACK] Delete region : {vo.name} ({vo.region_id})")
vo.delete()

region_vo: Region = self.region_model.create(params)
self.transaction.add_rollback(_rollback, region_vo)

return region_vo

def update_region_by_vo(self, params: dict, region_vo: Region) -> Region:
def _rollback(old_data):
_LOGGER.info(
f'[ROLLBACK] Revert Data : {old_data["name"]} ({old_data["region_id"]})'
)
region_vo.update(old_data)

self.transaction.add_rollback(_rollback, region_vo.to_dict())
return region_vo.update(params)

@staticmethod
def delete_region_by_vo(region_vo: Region) -> None:
region_vo.delete()

def get_region(self, region_id: str, domain_id: str) -> Region:
conditions = {"region_id": region_id, "domain_id": domain_id}

# if workspace_id:
# conditions.update({"workspace_id": workspace_id})

return self.region_model.get(**conditions)

def filter_regions(self, **conditions) -> QuerySet:
return self.region_model.filter(**conditions)

def list_regions(self, query: dict) -> Tuple[QuerySet, int]:
return self.region_model.query(**query)

def stat_regions(self, query: dict) -> dict:
return self.region_model.stat(**query)
1 change: 1 addition & 0 deletions src/spaceone/inventory_v2/model/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from spaceone.inventory_v2.model.region_model import Region
49 changes: 49 additions & 0 deletions src/spaceone/inventory_v2/model/region_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from mongoengine import *
from spaceone.core.model.mongo_model import MongoModel


class Region(MongoModel):
region_id = StringField(max_length=40, generate_id="region", unique=True)
name = StringField(max_length=255)
region_key = StringField(max_length=255)
region_code = StringField(
max_length=255, unique_with=["provider", "domain_id"]
)
provider = StringField(max_length=255)
ref_region = StringField(max_length=255)
tags = DictField()
domain_id = StringField(max_length=40)
updated_by = StringField(default=None, null=True)
created_at = DateTimeField(auto_now_add=True)
updated_at = DateTimeField(auto_now=True)

meta = {
"updatable_fields": ["name", "tags", "updated_by", "updated_at"],
"minimal_fields": ["region_id", "name", "region_code", "provider"],
"ordering": ["name"],
"indexes": [
{
"fields": ["domain_id", "-updated_at", "updated_by"],
"name": "COMPOUND_INDEX_FOR_GC_1",
},
{
"fields": ["domain_id", "region_id"],
"name": "COMPOUND_INDEX_FOR_SEARCH_1",
},
{
"fields": ["domain_id", "provider", "region_code"],
"name": "COMPOUND_INDEX_FOR_SEARCH_2",
},
{
"fields": ["domain_id", "region_key"],
"name": "COMPOUND_INDEX_FOR_SEARCH_3",
},
{"fields": ["region_id", "ref_region"], "name": "COMPOUND_INDEX_FOR_REF_1"},
{
"fields": ["region_code", "provider", "ref_region"],
"name": "COMPOUND_INDEX_FOR_REF_2",
},
"ref_region",
"domain_id",
],
}
1 change: 1 addition & 0 deletions src/spaceone/inventory_v2/service/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from spaceone.inventory_v2.service.region_service import RegionService
Loading
Loading