1 # Copyright (C) 2021 Wind River Systems, Inc.
\r
3 # Licensed under the Apache License, Version 2.0 (the "License");
\r
4 # you may not use this file except in compliance with the License.
\r
5 # You may obtain a copy of the License at
\r
7 # http://www.apache.org/licenses/LICENSE-2.0
\r
9 # Unless required by applicable law or agreed to in writing, software
\r
10 # distributed under the License is distributed on an "AS IS" BASIS,
\r
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
12 # See the License for the specific language governing permissions and
\r
13 # limitations under the License.
\r
15 # pylint: disable=attribute-defined-outside-init
\r
16 from __future__ import annotations
\r
17 from sqlalchemy import create_engine
\r
18 from sqlalchemy.orm import sessionmaker
\r
19 from sqlalchemy.orm.session import Session
\r
21 from o2common.config import config
\r
22 from o2common.service.unit_of_work import AbstractUnitOfWork
\r
24 from o2ims.adapter import ocloud_repository
\r
25 from o2dms.adapter import dms_repository
\r
27 DEFAULT_SESSION_FACTORY = sessionmaker(
\r
29 config.get_postgres_uri(),
\r
30 isolation_level="REPEATABLE READ",
\r
35 class SqlAlchemyUnitOfWork(AbstractUnitOfWork):
\r
36 def __init__(self, session_factory=DEFAULT_SESSION_FACTORY):
\r
37 self.session_factory = session_factory
\r
39 def __enter__(self):
\r
40 self.session = self.session_factory() # type: Session
\r
41 self.oclouds = ocloud_repository\
\r
42 .OcloudSqlAlchemyRepository(self.session)
\r
43 self.resource_types = ocloud_repository\
\r
44 .ResouceTypeSqlAlchemyRepository(self.session)
\r
45 self.resource_pools = ocloud_repository\
\r
46 .ResourcePoolSqlAlchemyRepository(self.session)
\r
47 self.resources = ocloud_repository\
\r
48 .ResourceSqlAlchemyRepository(self.session)
\r
49 self.deployment_managers = ocloud_repository\
\r
50 .DeploymentManagerSqlAlchemyRepository(self.session)
\r
51 self.nfdeployment_descs = dms_repository\
\r
52 .NfDeploymentDescSqlAlchemyRepository(self.session)
\r
53 return super().__enter__()
\r
55 def __exit__(self, *args):
\r
56 super().__exit__(*args)
\r
57 self.session.close()
\r
60 self.session.commit()
\r
63 self.session.rollback()
\r
65 def _collect_new_events(self):
\r
66 for entry in self.oclouds.seen:
\r
68 yield entry.events.pop(0)
\r
69 for entry in self.resource_pools.seen:
\r
71 yield entry.events.pop(0)
\r
72 for entry in self.resources.seen:
\r
74 yield entry.events.pop(0)
\r
75 for entry in self.resource_types.seen:
\r
77 yield entry.events.pop(0)
\r
78 for entry in self.deployment_managers.seen:
\r
80 yield entry.events.pop(0)
\r
81 for entry in self.nfdeployment_descs.seen:
\r
83 yield entry.events.pop(0)
\r