Initial commit
commit
f9530dadba
|
@ -0,0 +1,10 @@
|
|||
venv/
|
||||
build/
|
||||
*.charm
|
||||
.tox/
|
||||
.coverage
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.idea
|
||||
.vscode/
|
||||
.stestr/
|
|
@ -0,0 +1,3 @@
|
|||
[DEFAULT]
|
||||
test_path=./tests/unit
|
||||
top_dir=./tests
|
|
@ -0,0 +1,33 @@
|
|||
# Contributing
|
||||
|
||||
To make contributions to this charm, you'll need a working [development setup](https://juju.is/docs/sdk/dev-setup).
|
||||
|
||||
You can use the environments created by `tox` for development:
|
||||
|
||||
```shell
|
||||
tox --notest -e unit
|
||||
source .tox/unit/bin/activate
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
This project uses `tox` for managing test environments. There are some pre-configured environments
|
||||
that can be used for linting and formatting code when you're preparing contributions to the charm:
|
||||
|
||||
```shell
|
||||
tox -e fmt # update your code according to linting rules
|
||||
tox -e lint # code style
|
||||
tox -e unit # unit tests
|
||||
tox -e integration # integration tests
|
||||
tox # runs 'lint' and 'unit' environments
|
||||
```
|
||||
|
||||
## Build the charm
|
||||
|
||||
Build the charm in this git repository using:
|
||||
|
||||
```shell
|
||||
charmcraft pack
|
||||
```
|
||||
|
||||
<!-- You may want to include any contribution/style guidelines in this document>
|
|
@ -0,0 +1,202 @@
|
|||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -0,0 +1,16 @@
|
|||
# openstack-hypervisor
|
||||
|
||||
Charmhub package name: operator-template
|
||||
More information: https://charmhub.io/openstack-hypervisor
|
||||
|
||||
Describe your charm in one or two sentences.
|
||||
|
||||
## Other resources
|
||||
|
||||
<!-- If your charm is documented somewhere else other than Charmhub, provide a link separately. -->
|
||||
|
||||
- [Read more](https://example.com)
|
||||
|
||||
- [Contributing](CONTRIBUTING.md) <!-- or link to other contribution documentation -->
|
||||
|
||||
- See the [Juju SDK documentation](https://juju.is/docs/sdk) for more information about developing and improving charms.
|
|
@ -0,0 +1,21 @@
|
|||
# This file configures Charmcraft.
|
||||
# See https://juju.is/docs/sdk/charmcraft-config for guidance.
|
||||
|
||||
type: charm
|
||||
bases:
|
||||
- build-on:
|
||||
- name: ubuntu
|
||||
channel: "22.04"
|
||||
run-on:
|
||||
- name: ubuntu
|
||||
channel: "22.04"
|
||||
|
||||
parts:
|
||||
charm:
|
||||
build-packages:
|
||||
- git
|
||||
- libffi-dev
|
||||
- libssl-dev
|
||||
- pkg-config
|
||||
- rustc
|
||||
- cargo
|
|
@ -0,0 +1,28 @@
|
|||
options:
|
||||
snap-channel:
|
||||
default: "yoga/edge"
|
||||
type: string
|
||||
debug:
|
||||
default: False
|
||||
type: boolean
|
||||
dns-domain:
|
||||
default: "openstack.local"
|
||||
type: string
|
||||
dns-servers:
|
||||
default: "8.8.8.8"
|
||||
type: string
|
||||
enable-gateway:
|
||||
default: False
|
||||
type: boolean
|
||||
external-bridge:
|
||||
default: "br-ex"
|
||||
type: string
|
||||
external-bridge-address:
|
||||
default:
|
||||
type: string
|
||||
ip-address:
|
||||
default:
|
||||
type: string
|
||||
physnet-name:
|
||||
default: "physnet1"
|
||||
type: string
|
|
@ -0,0 +1,496 @@
|
|||
# Copyright 2022 Canonical Ltd.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Relation 'requires' side abstraction for database relation.
|
||||
|
||||
This library is a uniform interface to a selection of common database
|
||||
metadata, with added custom events that add convenience to database management,
|
||||
and methods to consume the application related data.
|
||||
|
||||
Following an example of using the DatabaseCreatedEvent, in the context of the
|
||||
application charm code:
|
||||
|
||||
```python
|
||||
|
||||
from charms.data_platform_libs.v0.database_requires import DatabaseRequires
|
||||
|
||||
class ApplicationCharm(CharmBase):
|
||||
# Application charm that connects to database charms.
|
||||
|
||||
def __init__(self, *args):
|
||||
super().__init__(*args)
|
||||
|
||||
# Charm events defined in the database requires charm library.
|
||||
self.database = DatabaseRequires(self, relation_name="database", database_name="database")
|
||||
self.framework.observe(self.database.on.database_created, self._on_database_created)
|
||||
|
||||
def _on_database_created(self, event: DatabaseCreatedEvent) -> None:
|
||||
# Handle the created database
|
||||
|
||||
# Create configuration file for app
|
||||
config_file = self._render_app_config_file(
|
||||
event.username,
|
||||
event.password,
|
||||
event.endpoints,
|
||||
)
|
||||
|
||||
# Start application with rendered configuration
|
||||
self._start_application(config_file)
|
||||
|
||||
# Set active status
|
||||
self.unit.status = ActiveStatus("received database credentials")
|
||||
```
|
||||
|
||||
As shown above, the library provides some custom events to handle specific situations,
|
||||
which are listed below:
|
||||
|
||||
— database_created: event emitted when the requested database is created.
|
||||
— endpoints_changed: event emitted when the read/write endpoints of the database have changed.
|
||||
— read_only_endpoints_changed: event emitted when the read-only endpoints of the database
|
||||
have changed. Event is not triggered if read/write endpoints changed too.
|
||||
|
||||
If it is needed to connect multiple database clusters to the same relation endpoint
|
||||
the application charm can implement the same code as if it would connect to only
|
||||
one database cluster (like the above code example).
|
||||
|
||||
To differentiate multiple clusters connected to the same relation endpoint
|
||||
the application charm can use the name of the remote application:
|
||||
|
||||
```python
|
||||
|
||||
def _on_database_created(self, event: DatabaseCreatedEvent) -> None:
|
||||
# Get the remote app name of the cluster that triggered this event
|
||||
cluster = event.relation.app.name
|
||||
```
|
||||
|
||||
It is also possible to provide an alias for each different database cluster/relation.
|
||||
|
||||
So, it is possible to differentiate the clusters in two ways.
|
||||
The first is to use the remote application name, i.e., `event.relation.app.name`, as above.
|
||||
|
||||
The second way is to use different event handlers to handle each cluster events.
|
||||
The implementation would be something like the following code:
|
||||
|
||||
```python
|
||||
|
||||
from charms.data_platform_libs.v0.database_requires import DatabaseRequires
|
||||
|
||||
class ApplicationCharm(CharmBase):
|
||||
# Application charm that connects to database charms.
|
||||
|
||||
def __init__(self, *args):
|
||||
super().__init__(*args)
|
||||
|
||||
# Define the cluster aliases and one handler for each cluster database created event.
|
||||
self.database = DatabaseRequires(
|
||||
self,
|
||||
relation_name="database",
|
||||
database_name="database",
|
||||
relations_aliases = ["cluster1", "cluster2"],
|
||||
)
|
||||
self.framework.observe(
|
||||
self.database.on.cluster1_database_created, self._on_cluster1_database_created
|
||||
)
|
||||
self.framework.observe(
|
||||
self.database.on.cluster2_database_created, self._on_cluster2_database_created
|
||||
)
|
||||
|
||||
def _on_cluster1_database_created(self, event: DatabaseCreatedEvent) -> None:
|
||||
# Handle the created database on the cluster named cluster1
|
||||
|
||||
# Create configuration file for app
|
||||
config_file = self._render_app_config_file(
|
||||
event.username,
|
||||
event.password,
|
||||
event.endpoints,
|
||||
)
|
||||
...
|
||||
|
||||
def _on_cluster2_database_created(self, event: DatabaseCreatedEvent) -> None:
|
||||
# Handle the created database on the cluster named cluster2
|
||||
|
||||
# Create configuration file for app
|
||||
config_file = self._render_app_config_file(
|
||||
event.username,
|
||||
event.password,
|
||||
event.endpoints,
|
||||
)
|
||||
...
|
||||
|
||||
```
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from collections import namedtuple
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from ops.charm import (
|
||||
CharmEvents,
|
||||
RelationChangedEvent,
|
||||
RelationEvent,
|
||||
RelationJoinedEvent,
|
||||
)
|
||||
from ops.framework import EventSource, Object
|
||||
from ops.model import Relation
|
||||
|
||||
# The unique Charmhub library identifier, never change it
|
||||
LIBID = "0241e088ffa9440fb4e3126349b2fb62"
|
||||
|
||||
# Increment this major API version when introducing breaking changes
|
||||
LIBAPI = 0
|
||||
|
||||
# Increment this PATCH version before using `charmcraft publish-lib` or reset
|
||||
# to 0 if you are raising the major API version.
|
||||
LIBPATCH = 4
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DatabaseEvent(RelationEvent):
|
||||
"""Base class for database events."""
|
||||
|
||||
@property
|
||||
def endpoints(self) -> Optional[str]:
|
||||
"""Returns a comma separated list of read/write endpoints."""
|
||||
return self.relation.data[self.relation.app].get("endpoints")
|
||||
|
||||
@property
|
||||
def password(self) -> Optional[str]:
|
||||
"""Returns the password for the created user."""
|
||||
return self.relation.data[self.relation.app].get("password")
|
||||
|
||||
@property
|
||||
def read_only_endpoints(self) -> Optional[str]:
|
||||
"""Returns a comma separated list of read only endpoints."""
|
||||
return self.relation.data[self.relation.app].get("read-only-endpoints")
|
||||
|
||||
@property
|
||||
def replset(self) -> Optional[str]:
|
||||
"""Returns the replicaset name.
|
||||
|
||||
MongoDB only.
|
||||
"""
|
||||
return self.relation.data[self.relation.app].get("replset")
|
||||
|
||||
@property
|
||||
def tls(self) -> Optional[str]:
|
||||
"""Returns whether TLS is configured."""
|
||||
return self.relation.data[self.relation.app].get("tls")
|
||||
|
||||
@property
|
||||
def tls_ca(self) -> Optional[str]:
|
||||
"""Returns TLS CA."""
|
||||
return self.relation.data[self.relation.app].get("tls-ca")
|
||||
|
||||
@property
|
||||
def uris(self) -> Optional[str]:
|
||||
"""Returns the connection URIs.
|
||||
|
||||
MongoDB, Redis, OpenSearch and Kafka only.
|
||||
"""
|
||||
return self.relation.data[self.relation.app].get("uris")
|
||||
|
||||
@property
|
||||
def username(self) -> Optional[str]:
|
||||
"""Returns the created username."""
|
||||
return self.relation.data[self.relation.app].get("username")
|
||||
|
||||
@property
|
||||
def version(self) -> Optional[str]:
|
||||
"""Returns the version of the database.
|
||||
|
||||
Version as informed by the database daemon.
|
||||
"""
|
||||
return self.relation.data[self.relation.app].get("version")
|
||||
|
||||
|
||||
class DatabaseCreatedEvent(DatabaseEvent):
|
||||
"""Event emitted when a new database is created for use on this relation."""
|
||||
|
||||
|
||||
class DatabaseEndpointsChangedEvent(DatabaseEvent):
|
||||
"""Event emitted when the read/write endpoints are changed."""
|
||||
|
||||
|
||||
class DatabaseReadOnlyEndpointsChangedEvent(DatabaseEvent):
|
||||
"""Event emitted when the read only endpoints are changed."""
|
||||
|
||||
|
||||
class DatabaseEvents(CharmEvents):
|
||||
"""Database events.
|
||||
|
||||
This class defines the events that the database can emit.
|
||||
"""
|
||||
|
||||
database_created = EventSource(DatabaseCreatedEvent)
|
||||
endpoints_changed = EventSource(DatabaseEndpointsChangedEvent)
|
||||
read_only_endpoints_changed = EventSource(DatabaseReadOnlyEndpointsChangedEvent)
|
||||
|
||||
|
||||
Diff = namedtuple("Diff", "added changed deleted")
|
||||
Diff.__doc__ = """
|
||||
A tuple for storing the diff between two data mappings.
|
||||
|
||||
— added — keys that were added.
|
||||
— changed — keys that still exist but have new values.
|
||||
— deleted — keys that were deleted.
|
||||
"""
|
||||
|
||||
|
||||
class DatabaseRequires(Object):
|
||||
"""Requires-side of the database relation."""
|
||||
|
||||
on = DatabaseEvents()
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
charm,
|
||||
relation_name: str,
|
||||
database_name: str,
|
||||
extra_user_roles: str = None,
|
||||
relations_aliases: List[str] = None,
|
||||
):
|
||||
"""Manager of database client relations."""
|
||||
super().__init__(charm, relation_name)
|
||||
self.charm = charm
|
||||
self.database = database_name
|
||||
self.extra_user_roles = extra_user_roles
|
||||
self.local_app = self.charm.model.app
|
||||
self.local_unit = self.charm.unit
|
||||
self.relation_name = relation_name
|
||||
self.relations_aliases = relations_aliases
|
||||
self.framework.observe(
|
||||
self.charm.on[relation_name].relation_joined, self._on_relation_joined_event
|
||||
)
|
||||
self.framework.observe(
|
||||
self.charm.on[relation_name].relation_changed, self._on_relation_changed_event
|
||||
)
|
||||
|
||||
# Define custom event names for each alias.
|
||||
if relations_aliases:
|
||||
# Ensure the number of aliases does not exceed the maximum
|
||||
# of connections allowed in the specific relation.
|
||||
relation_connection_limit = self.charm.meta.requires[relation_name].limit
|
||||
if len(relations_aliases) != relation_connection_limit:
|
||||
raise ValueError(
|
||||
f"The number of aliases must match the maximum number of connections allowed in the relation. "
|
||||
f"Expected {relation_connection_limit}, got {len(relations_aliases)}"
|
||||
)
|
||||
|
||||
for relation_alias in relations_aliases:
|
||||
self.on.define_event(f"{relation_alias}_database_created", DatabaseCreatedEvent)
|
||||
self.on.define_event(
|
||||
f"{relation_alias}_endpoints_changed", DatabaseEndpointsChangedEvent
|
||||
)
|
||||
self.on.define_event(
|
||||
f"{relation_alias}_read_only_endpoints_changed",
|
||||
DatabaseReadOnlyEndpointsChangedEvent,
|
||||
)
|
||||
|
||||
def _assign_relation_alias(self, relation_id: int) -> None:
|
||||
"""Assigns an alias to a relation.
|
||||
|
||||
This function writes in the unit data bag.
|
||||
|
||||
Args:
|
||||
relation_id: the identifier for a particular relation.
|
||||
"""
|
||||
# If no aliases were provided, return immediately.
|
||||
if not self.relations_aliases:
|
||||
return
|
||||
|
||||
# Return if an alias was already assigned to this relation
|
||||
# (like when there are more than one unit joining the relation).
|
||||
if (
|
||||
self.charm.model.get_relation(self.relation_name, relation_id)
|
||||
.data[self.local_unit]
|
||||
.get("alias")
|
||||
):
|
||||
return
|
||||
|
||||
# Retrieve the available aliases (the ones that weren't assigned to any relation).
|
||||
available_aliases = self.relations_aliases[:]
|
||||
for relation in self.charm.model.relations[self.relation_name]:
|
||||
alias = relation.data[self.local_unit].get("alias")
|
||||
if alias:
|
||||
logger.debug("Alias %s was already assigned to relation %d", alias, relation.id)
|
||||
available_aliases.remove(alias)
|
||||
|
||||
# Set the alias in the unit relation databag of the specific relation.
|
||||
relation = self.charm.model.get_relation(self.relation_name, relation_id)
|
||||
relation.data[self.local_unit].update({"alias": available_aliases[0]})
|
||||
|
||||
def _diff(self, event: RelationChangedEvent) -> Diff:
|
||||
"""Retrieves the diff of the data in the relation changed databag.
|
||||
|
||||
Args:
|
||||
event: relation changed event.
|
||||
|
||||
Returns:
|
||||
a Diff instance containing the added, deleted and changed
|
||||
keys from the event relation databag.
|
||||
"""
|
||||
# Retrieve the old data from the data key in the local unit relation databag.
|
||||
old_data = json.loads(event.relation.data[self.local_unit].get("data", "{}"))
|
||||
# Retrieve the new data from the event relation databag.
|
||||
new_data = {
|
||||
key: value for key, value in event.relation.data[event.app].items() if key != "data"
|
||||
}
|
||||
|
||||
# These are the keys that were added to the databag and triggered this event.
|
||||
added = new_data.keys() - old_data.keys()
|
||||
# These are the keys that were removed from the databag and triggered this event.
|
||||
deleted = old_data.keys() - new_data.keys()
|
||||
# These are the keys that already existed in the databag,
|
||||
# but had their values changed.
|
||||
changed = {
|
||||
key for key in old_data.keys() & new_data.keys() if old_data[key] != new_data[key]
|
||||
}
|
||||
|
||||
# TODO: evaluate the possibility of losing the diff if some error
|
||||
# happens in the charm before the diff is completely checked (DPE-412).
|
||||
# Convert the new_data to a serializable format and save it for a next diff check.
|
||||
event.relation.data[self.local_unit].update({"data": json.dumps(new_data)})
|
||||
|
||||
# Return the diff with all possible changes.
|
||||
return Diff(added, changed, deleted)
|
||||
|
||||
def _emit_aliased_event(self, event: RelationChangedEvent, event_name: str) -> None:
|
||||
"""Emit an aliased event to a particular relation if it has an alias.
|
||||
|
||||
Args:
|
||||
event: the relation changed event that was received.
|
||||
event_name: the name of the event to emit.
|
||||
"""
|
||||
alias = self._get_relation_alias(event.relation.id)
|
||||
if alias:
|
||||
getattr(self.on, f"{alias}_{event_name}").emit(
|
||||
event.relation, app=event.app, unit=event.unit
|
||||
)
|
||||
|
||||
def _get_relation_alias(self, relation_id: int) -> Optional[str]:
|
||||
"""Returns the relation alias.
|
||||
|
||||
Args:
|
||||
relation_id: the identifier for a particular relation.
|
||||
|
||||
Returns:
|
||||
the relation alias or None if the relation was not found.
|
||||
"""
|
||||
for relation in self.charm.model.relations[self.relation_name]:
|
||||
if relation.id == relation_id:
|
||||
return relation.data[self.local_unit].get("alias")
|
||||
return None
|
||||
|
||||
def fetch_relation_data(self) -> dict:
|
||||
"""Retrieves data from relation.
|
||||
|
||||
This function can be used to retrieve data from a relation
|
||||
in the charm code when outside an event callback.
|
||||
|
||||
Returns:
|
||||
a dict of the values stored in the relation data bag
|
||||
for all relation instances (indexed by the relation ID).
|
||||
"""
|
||||
data = {}
|
||||
for relation in self.relations:
|
||||
data[relation.id] = {
|
||||
key: value for key, value in relation.data[relation.app].items() if key != "data"
|
||||
}
|
||||
return data
|
||||
|
||||
def _update_relation_data(self, relation_id: int, data: dict) -> None:
|
||||
"""Updates a set of key-value pairs in the relation.
|
||||
|
||||
This function writes in the application data bag, therefore,
|
||||
only the leader unit can call it.
|
||||
|
||||
Args:
|
||||
relation_id: the identifier for a particular relation.
|
||||
data: dict containing the key-value pairs
|
||||
that should be updated in the relation.
|
||||
"""
|
||||
if self.local_unit.is_leader():
|
||||
relation = self.charm.model.get_relation(self.relation_name, relation_id)
|
||||
relation.data[self.local_app].update(data)
|
||||
|
||||
def _on_relation_joined_event(self, event: RelationJoinedEvent) -> None:
|
||||
"""Event emitted when the application joins the database relation."""
|
||||
# If relations aliases were provided, assign one to the relation.
|
||||
self._assign_relation_alias(event.relation.id)
|
||||
|
||||
# Sets both database and extra user roles in the relation
|
||||
# if the roles are provided. Otherwise, sets only the database.
|
||||
if self.extra_user_roles:
|
||||
self._update_relation_data(
|
||||
event.relation.id,
|
||||
{
|
||||
"database": self.database,
|
||||
"extra-user-roles": self.extra_user_roles,
|
||||
},
|
||||
)
|
||||
else:
|
||||
self._update_relation_data(event.relation.id, {"database": self.database})
|
||||
|
||||
def _on_relation_changed_event(self, event: RelationChangedEvent) -> None:
|
||||
"""Event emitted when the database relation has changed."""
|
||||
# Check which data has changed to emit customs events.
|
||||
diff = self._diff(event)
|
||||
|
||||
# Check if the database is created
|
||||
# (the database charm shared the credentials).
|
||||
if "username" in diff.added and "password" in diff.added:
|
||||
# Emit the default event (the one without an alias).
|
||||
logger.info("database created at %s", datetime.now())
|
||||
self.on.database_created.emit(event.relation, app=event.app, unit=event.unit)
|
||||
|
||||
# Emit the aliased event (if any).
|
||||
self._emit_aliased_event(event, "database_created")
|
||||
|
||||
# To avoid unnecessary application restarts do not trigger
|
||||
# “endpoints_changed“ event if “database_created“ is triggered.
|
||||
return
|
||||
|
||||
# Emit an endpoints changed event if the database
|
||||
# added or changed this info in the relation databag.
|
||||
if "endpoints" in diff.added or "endpoints" in diff.changed:
|
||||
# Emit the default event (the one without an alias).
|
||||
logger.info("endpoints changed on %s", datetime.now())
|
||||
self.on.endpoints_changed.emit(event.relation, app=event.app, unit=event.unit)
|
||||
|
||||
# Emit the aliased event (if any).
|
||||
self._emit_aliased_event(event, "endpoints_changed")
|
||||
|
||||
# To avoid unnecessary application restarts do not trigger
|
||||
# “read_only_endpoints_changed“ event if “endpoints_changed“ is triggered.
|
||||
return
|
||||
|
||||
# Emit a read only endpoints changed event if the database
|
||||
# added or changed this info in the relation databag.
|
||||
if "read-only-endpoints" in diff.added or "read-only-endpoints" in diff.changed:
|
||||
# Emit the default event (the one without an alias).
|
||||
logger.info("read-only-endpoints changed on %s", datetime.now())
|
||||
self.on.read_only_endpoints_changed.emit(
|
||||
event.relation, app=event.app, unit=event.unit
|
||||
)
|
||||
|
||||
# Emit the aliased event (if any).
|
||||
self._emit_aliased_event(event, "read_only_endpoints_changed")
|
||||
|
||||
@property
|
||||
def relations(self) -> List[Relation]:
|
||||
"""The list of Relation instances associated with this relation_name."""
|
||||
return list(self.charm.model.relations[self.relation_name])
|
|
@ -0,0 +1,418 @@
|
|||
"""CloudCredentialsProvides and Requires module.
|
||||
|
||||
|
||||
This library contains the Requires and Provides classes for handling
|
||||
the cloud_credentials interface.
|
||||
|
||||
Import `CloudCredentialsRequires` in your charm, with the charm object and the
|
||||
relation name:
|
||||
- self
|
||||
- "cloud_credentials"
|
||||
|
||||
Also provide additional parameters to the charm object:
|
||||
- service
|
||||
- internal_url
|
||||
- public_url
|
||||
- admin_url
|
||||
- region
|
||||
- username
|
||||
- vhost
|
||||
|
||||
Two events are also available to respond to:
|
||||
- connected
|
||||
- ready
|
||||
- goneaway
|
||||
|
||||
A basic example showing the usage of this relation follows:
|
||||
|
||||
```
|
||||
from charms.keystone_k8s.v0.cloud_credentials import CloudCredentialsRequires
|
||||
|
||||
class CloudCredentialsClientCharm(CharmBase):
|
||||
def __init__(self, *args):
|
||||
super().__init__(*args)
|
||||
# CloudCredentials Requires
|
||||
self.cloud_credentials = CloudCredentialsRequires(
|
||||
self, "cloud_credentials",
|
||||
service = "my-service"
|
||||
internal_url = "http://internal-url"
|
||||
public_url = "http://public-url"
|
||||
admin_url = "http://admin-url"
|
||||
region = "region"
|
||||
)
|
||||
self.framework.observe(
|
||||
self.cloud_credentials.on.connected, self._on_cloud_credentials_connected)
|
||||
self.framework.observe(
|
||||
self.cloud_credentials.on.ready, self._on_cloud_credentials_ready)
|
||||
self.framework.observe(
|
||||
self.cloud_credentials.on.goneaway, self._on_cloud_credentials_goneaway)
|
||||
|
||||
def _on_cloud_credentials_connected(self, event):
|
||||
'''React to the CloudCredentials connected event.
|
||||
|
||||
This event happens when n CloudCredentials relation is added to the
|
||||
model before credentials etc have been provided.
|
||||
'''
|
||||
# Do something before the relation is complete
|
||||
pass
|
||||
|
||||
def _on_cloud_credentials_ready(self, event):
|
||||
'''React to the CloudCredentials ready event.
|
||||
|
||||
The CloudCredentials interface will use the provided config for the
|
||||
request to the identity server.
|
||||
'''
|
||||
# CloudCredentials Relation is ready. Do something with the completed relation.
|
||||
pass
|
||||
|
||||
def _on_cloud_credentials_goneaway(self, event):
|
||||
'''React to the CloudCredentials goneaway event.
|
||||
|
||||
This event happens when an CloudCredentials relation is removed.
|
||||
'''
|
||||
# CloudCredentials Relation has goneaway. shutdown services or suchlike
|
||||
pass
|
||||
```
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from ops.framework import (
|
||||
StoredState,
|
||||
EventBase,
|
||||
ObjectEvents,
|
||||
EventSource,
|
||||
Object,
|
||||
)
|
||||
from ops.model import Relation
|
||||
|
||||
# The unique Charmhub library identifier, never change it
|
||||
LIBID = "a5d96cc2686c47eea554ce2210c2d24e"
|
||||
|
||||
# Increment this major API version when introducing breaking changes
|
||||
LIBAPI = 0
|
||||
|
||||
# Increment this PATCH version before using `charmcraft publish-lib` or reset
|
||||
# to 0 if you are raising the major API version
|
||||
LIBPATCH = 2
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CloudCredentialsConnectedEvent(EventBase):
|
||||
"""CloudCredentials connected Event."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class CloudCredentialsReadyEvent(EventBase):
|
||||
"""CloudCredentials ready for use Event."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class CloudCredentialsGoneAwayEvent(EventBase):
|
||||
"""CloudCredentials relation has gone-away Event"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class CloudCredentialsServerEvents(ObjectEvents):
|
||||
"""Events class for `on`"""
|
||||
|
||||
connected = EventSource(CloudCredentialsConnectedEvent)
|
||||
ready = EventSource(CloudCredentialsReadyEvent)
|
||||
goneaway = EventSource(CloudCredentialsGoneAwayEvent)
|
||||
|
||||
|
||||
class CloudCredentialsRequires(Object):
|
||||
"""
|
||||
CloudCredentialsRequires class
|
||||
"""
|
||||
|
||||
on = CloudCredentialsServerEvents()
|
||||
_stored = StoredState()
|
||||
|
||||
def __init__(self, charm, relation_name: str):
|
||||
super().__init__(charm, relation_name)
|
||||
self.charm = charm
|
||||
self.relation_name = relation_name
|
||||
self.framework.observe(
|
||||
self.charm.on[relation_name].relation_joined,
|
||||
self._on_cloud_credentials_relation_joined,
|
||||
)
|
||||
self.framework.observe(
|
||||
self.charm.on[relation_name].relation_changed,
|
||||
self._on_cloud_credentials_relation_changed,
|
||||
)
|
||||
self.framework.observe(
|
||||
self.charm.on[relation_name].relation_departed,
|
||||
self._on_cloud_credentials_relation_changed,
|
||||
)
|
||||
self.framework.observe(
|
||||
self.charm.on[relation_name].relation_broken,
|
||||
self._on_cloud_credentials_relation_broken,
|
||||
)
|
||||
|
||||
def _on_cloud_credentials_relation_joined(self, event):
|
||||
"""CloudCredentials relation joined."""
|
||||
logging.debug("CloudCredentials on_joined")
|
||||
self.on.connected.emit()
|
||||
self.request_credentials()
|
||||
|
||||
def _on_cloud_credentials_relation_changed(self, event):
|
||||
"""CloudCredentials relation changed."""
|
||||
logging.debug("CloudCredentials on_changed")
|
||||
try:
|
||||
self.on.ready.emit()
|
||||
except (AttributeError, KeyError):
|
||||
logger.exception('Error when emitting event')
|
||||
|
||||
def _on_cloud_credentials_relation_broken(self, event):
|
||||
"""CloudCredentials relation broken."""
|
||||
logging.debug("CloudCredentials on_broken")
|
||||
self.on.goneaway.emit()
|
||||
|
||||
@property
|
||||
def _cloud_credentials_rel(self) -> Relation:
|
||||
"""The CloudCredentials relation."""
|
||||
return self.framework.model.get_relation(self.relation_name)
|
||||
|
||||
def get_remote_app_data(self, key: str) -> str:
|
||||
"""Return the value for the given key from remote app data."""
|
||||
data = self._cloud_credentials_rel.data[self._cloud_credentials_rel.app]
|
||||
return data.get(key)
|
||||
|
||||
@property
|
||||
def api_version(self) -> str:
|
||||
"""Return the api_version."""
|
||||
return self.get_remote_app_data('api-version')
|
||||
|
||||
@property
|
||||
def auth_host(self) -> str:
|
||||
"""Return the auth_host."""
|
||||
return self.get_remote_app_data('auth-host')
|
||||
|
||||
@property
|
||||
def auth_port(self) -> str:
|
||||
"""Return the auth_port."""
|
||||
return self.get_remote_app_data('auth-port')
|
||||
|
||||
@property
|
||||
def auth_protocol(self) -> str:
|
||||
"""Return the auth_protocol."""
|
||||
return self.get_remote_app_data('auth-protocol')
|
||||
|
||||
@property
|
||||
def internal_host(self) -> str:
|
||||
"""Return the internal_host."""
|
||||
return self.get_remote_app_data('internal-host')
|
||||
|
||||
@property
|
||||
def internal_port(self) -> str:
|
||||
"""Return the internal_port."""
|
||||
return self.get_remote_app_data('internal-port')
|
||||
|
||||
@property
|
||||
def internal_protocol(self) -> str:
|
||||
"""Return the internal_protocol."""
|
||||
return self.get_remote_app_data('internal-protocol')
|
||||
|
||||
@property
|
||||
def username(self) -> str:
|
||||
"""Return the username."""
|
||||
return self.get_remote_app_data('username')
|
||||
|
||||
@property
|
||||
def password(self) -> str:
|
||||
"""Return the password."""
|
||||
return self.get_remote_app_data('password')
|
||||
|
||||
@property
|
||||
def project_name(self) -> str:
|
||||
"""Return the project name."""
|
||||
return self.get_remote_app_data('project-name')
|
||||
|
||||
@property
|
||||
def project_id(self) -> str:
|
||||
"""Return the project id."""
|
||||
return self.get_remote_app_data('project-id')
|
||||
|
||||
@property
|
||||
def user_domain_name(self) -> str:
|
||||
"""Return the name of the user domain."""
|
||||
return self.get_remote_app_data('user-domain-name')
|
||||
|
||||
@property
|
||||
def user_domain_id(self) -> str:
|
||||
"""Return the id of the user domain."""
|
||||
return self.get_remote_app_data('user-domain-id')
|
||||
|
||||
@property
|
||||
def project_domain_name(self) -> str:
|
||||
"""Return the name of the project domain."""
|
||||
return self.get_remote_app_data('project-domain-name')
|
||||
|
||||
@property
|
||||
def project_domain_id(self) -> str:
|
||||
"""Return the id of the project domain."""
|
||||
return self.get_remote_app_data('project-domain-id')
|
||||
|
||||
@property
|
||||
def region(self) -> str:
|
||||
"""Return the region for the auth urls."""
|
||||
return self.get_remote_app_data('region')
|
||||
|
||||
def request_credentials(self) -> None:
|
||||
"""Request credentials from the CloudCredentials server."""
|
||||
if self.model.unit.is_leader():
|
||||
logging.debug(f'Requesting credentials for {self.charm.app.name}')
|
||||
app_data = self._cloud_credentials_rel.data[self.charm.app]
|
||||
app_data['username'] = self.charm.app.name
|
||||
|
||||
|
||||
class HasCloudCredentialsClientsEvent(EventBase):
|
||||
"""Has CloudCredentialsClients Event."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class ReadyCloudCredentialsClientsEvent(EventBase):
|
||||
"""CloudCredentialsClients Ready Event."""
|
||||
|
||||
def __init__(self, handle, relation_id, relation_name, username):
|
||||
super().__init__(handle)
|
||||
self.relation_id = relation_id
|
||||
self.relation_name = relation_name
|
||||
self.username = username
|
||||
|
||||
def snapshot(self):
|
||||
return {
|
||||
"relation_id": self.relation_id,
|
||||
"relation_name": self.relation_name,
|
||||
"username": self.username,
|
||||
}
|
||||
|
||||
def restore(self, snapshot):
|
||||
super().restore(snapshot)
|
||||
self.relation_id = snapshot["relation_id"]
|
||||
self.relation_name = snapshot["relation_name"]
|
||||
self.username = snapshot["username"]
|
||||
|
||||
|
||||
class CloudCredentialsClientsGoneAwayEvent(EventBase):
|
||||
"""Has CloudCredentialsClientsGoneAwayEvent Event."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class CloudCredentialsClientEvents(ObjectEvents):
|
||||
"""Events class for `on`"""
|
||||
|
||||
has_cloud_credentials_clients = EventSource(
|
||||
HasCloudCredentialsClientsEvent
|
||||
)
|
||||
ready_cloud_credentials_clients = EventSource(
|
||||
ReadyCloudCredentialsClientsEvent
|
||||
)
|
||||
cloud_credentials_clients_gone = EventSource(
|
||||
CloudCredentialsClientsGoneAwayEvent
|
||||
)
|
||||
|
||||
|
||||
class CloudCredentialsProvides(Object):
|
||||
"""
|
||||
CloudCredentialsProvides class
|
||||
"""
|
||||
|
||||
on = CloudCredentialsClientEvents()
|
||||
_stored = StoredState()
|
||||
|
||||
def __init__(self, charm, relation_name):
|
||||
super().__init__(charm, relation_name)
|
||||
self.charm = charm
|
||||
self.relation_name = relation_name
|
||||
self.framework.observe(
|
||||
self.charm.on[relation_name].relation_joined,
|
||||
self._on_cloud_credentials_relation_joined,
|
||||
)
|
||||
self.framework.observe(
|
||||
self.charm.on[relation_name].relation_changed,
|
||||
self._on_cloud_credentials_relation_changed,
|
||||
)
|
||||
self.framework.observe(
|
||||
self.charm.on[relation_name].relation_broken,
|
||||
self._on_cloud_credentials_relation_broken,
|
||||
)
|
||||
|
||||
def _on_cloud_credentials_relation_joined(self, event):
|
||||
"""Handle CloudCredentials joined."""
|
||||
logging.debug("CloudCredentialsProvides on_joined")
|
||||
self.on.has_cloud_credentials_clients.emit()
|
||||
|
||||
def _on_cloud_credentials_relation_changed(self, event):
|
||||
"""Handle CloudCredentials changed."""
|
||||
logging.debug("CloudCredentials on_changed")
|
||||
REQUIRED_KEYS = ['username']
|
||||
|
||||
values = [
|
||||
event.relation.data[event.relation.app].get(k)
|
||||
for k in REQUIRED_KEYS
|
||||
]
|
||||
# Validate data on the relation
|
||||
if all(values):
|
||||
username = event.relation.data[event.relation.app]['username']
|
||||
self.on.ready_cloud_credentials_clients.emit(
|
||||
event.relation.id,
|
||||
event.relation.name,
|
||||
username,
|
||||
)
|
||||
|
||||
def _on_cloud_credentials_relation_broken(self, event):
|
||||
"""Handle CloudCredentials broken."""
|
||||
logging.debug("CloudCredentialsProvides on_departed")
|
||||
self.on.cloud_credentials_clients_gone.emit()
|
||||
|
||||
def set_cloud_credentials(self, relation_name: int,
|
||||
relation_id: str,
|
||||
api_version: str,
|
||||
auth_host: str,
|
||||
auth_port: str,
|
||||
auth_protocol: str,
|
||||
internal_host: str,
|
||||
internal_port: str,
|
||||
internal_protocol: str,
|
||||
username: str,
|
||||
password: str,
|
||||
project_name: str,
|
||||
project_id: str,
|
||||
user_domain_name: str,
|
||||
user_domain_id: str,
|
||||
project_domain_name: str,
|
||||
project_domain_id: str,
|
||||
region: str):
|
||||
logging.debug("Setting cloud_credentials connection information.")
|
||||
_cloud_credentials_rel = None
|
||||
for relation in self.framework.model.relations[relation_name]:
|
||||
if relation.id == relation_id:
|
||||
_cloud_credentials_rel = relation
|
||||
if not _cloud_credentials_rel:
|
||||
# Relation has disappeared so don't send the data
|
||||
return
|
||||
app_data = _cloud_credentials_rel.data[self.charm.app]
|
||||
app_data["api-version"] = api_version
|
||||
app_data["auth-host"] = auth_host
|
||||
app_data["auth-port"] = str(auth_port)
|
||||
app_data["auth-protocol"] = auth_protocol
|
||||
app_data["internal-host"] = internal_host
|
||||
app_data["internal-port"] = str(internal_port)
|
||||
app_data["internal-protocol"] = internal_protocol
|
||||
app_data["username"] = username
|
||||
app_data["password"] = password
|
||||
app_data["project-name"] = project_name
|
||||
app_data["project-id"] = project_id
|
||||
app_data["user-domain-name"] = user_domain_name
|
||||
app_data["user-domain-id"] = user_domain_id
|
||||
app_data["project-domain-name"] = project_domain_name
|
||||
app_data["project-domain-id"] = project_domain_id
|
||||
app_data["region"] = region
|
|
@ -0,0 +1,439 @@
|
|||
"""IdentityCredentialsProvides and Requires module.
|
||||
|
||||
|
||||
This library contains the Requires and Provides classes for handling
|
||||
the identity_credentials interface.
|
||||
|
||||
Import `IdentityCredentialsRequires` in your charm, with the charm object and the
|
||||
relation name:
|
||||
- self
|
||||
- "identity_credentials"
|
||||
|
||||
Also provide additional parameters to the charm object:
|
||||
- service
|
||||
- internal_url
|
||||
- public_url
|
||||
- admin_url
|
||||
- region
|
||||
- username
|
||||
- vhost
|
||||
|
||||
Two events are also available to respond to:
|
||||
- connected
|
||||
- ready
|
||||
- goneaway
|
||||
|
||||
A basic example showing the usage of this relation follows:
|
||||
|
||||
```
|
||||
from charms.keystone_k8s.v0.identity_credentials import IdentityCredentialsRequires
|
||||
|
||||
class IdentityCredentialsClientCharm(CharmBase):
|
||||
def __init__(self, *args):
|
||||
super().__init__(*args)
|
||||
# IdentityCredentials Requires
|
||||
self.identity_credentials = IdentityCredentialsRequires(
|
||||
self, "identity_credentials",
|
||||
service = "my-service"
|
||||
internal_url = "http://internal-url"
|
||||
public_url = "http://public-url"
|
||||
admin_url = "http://admin-url"
|
||||
region = "region"
|
||||
)
|
||||
self.framework.observe(
|
||||
self.identity_credentials.on.connected, self._on_identity_credentials_connected)
|
||||
self.framework.observe(
|
||||
self.identity_credentials.on.ready, self._on_identity_credentials_ready)
|
||||
self.framework.observe(
|
||||
self.identity_credentials.on.goneaway, self._on_identity_credentials_goneaway)
|
||||
|
||||
def _on_identity_credentials_connected(self, event):
|
||||
'''React to the IdentityCredentials connected event.
|
||||
|
||||
This event happens when IdentityCredentials relation is added to the
|
||||
model before credentials etc have been provided.
|
||||
'''
|
||||
# Do something before the relation is complete
|
||||
pass
|
||||
|
||||
def _on_identity_credentials_ready(self, event):
|
||||
'''React to the IdentityCredentials ready event.
|
||||
|
||||
The IdentityCredentials interface will use the provided config for the
|
||||
request to the identity server.
|
||||
'''
|
||||
# IdentityCredentials Relation is ready. Do something with the completed relation.
|
||||
pass
|
||||
|
||||
def _on_identity_credentials_goneaway(self, event):
|
||||
'''React to the IdentityCredentials goneaway event.
|
||||
|
||||
This event happens when an IdentityCredentials relation is removed.
|
||||
'''
|
||||
# IdentityCredentials Relation has goneaway. shutdown services or suchlike
|
||||
pass
|
||||
```
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from ops.framework import (
|
||||
StoredState,
|
||||
EventBase,
|
||||
ObjectEvents,
|
||||
EventSource,
|
||||
Object,
|
||||
)
|
||||
from ops.model import (
|
||||
Relation,
|
||||
SecretNotFoundError,
|
||||
)
|
||||
|
||||
# The unique Charmhub library identifier, never change it
|
||||
LIBID = "b5fa18d4427c4ab9a269c3a2fbed545c"
|
||||
|
||||
# Increment this major API version when introducing breaking changes
|
||||
LIBAPI = 0
|
||||
|
||||
# Increment this PATCH version before using `charmcraft publish-lib` or reset
|
||||
# to 0 if you are raising the major API version
|
||||
LIBPATCH = 1
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class IdentityCredentialsConnectedEvent(EventBase):
|
||||
"""IdentityCredentials connected Event."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class IdentityCredentialsReadyEvent(EventBase):
|
||||
"""IdentityCredentials ready for use Event."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class IdentityCredentialsGoneAwayEvent(EventBase):
|
||||
"""IdentityCredentials relation has gone-away Event"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class IdentityCredentialsServerEvents(ObjectEvents):
|
||||
"""Events class for `on`"""
|
||||
|
||||
connected = EventSource(IdentityCredentialsConnectedEvent)
|
||||
ready = EventSource(IdentityCredentialsReadyEvent)
|
||||
goneaway = EventSource(IdentityCredentialsGoneAwayEvent)
|
||||
|
||||
|
||||
class IdentityCredentialsRequires(Object):
|
||||
"""
|
||||
IdentityCredentialsRequires class
|
||||
"""
|
||||
|
||||
on = IdentityCredentialsServerEvents()
|
||||
_stored = StoredState()
|
||||
|
||||
def __init__(self, charm, relation_name: str):
|
||||
super().__init__(charm, relation_name)
|
||||
self.charm = charm
|
||||
self.relation_name = relation_name
|
||||
self.framework.observe(
|
||||
self.charm.on[relation_name].relation_joined,
|
||||
self._on_identity_credentials_relation_joined,
|
||||
)
|
||||
self.framework.observe(
|
||||
self.charm.on[relation_name].relation_changed,
|
||||
self._on_identity_credentials_relation_changed,
|
||||
)
|
||||
self.framework.observe(
|
||||
self.charm.on[relation_name].relation_departed,
|
||||
self._on_identity_credentials_relation_changed,
|
||||
)
|
||||
self.framework.observe(
|
||||
self.charm.on[relation_name].relation_broken,
|
||||
self._on_identity_credentials_relation_broken,
|
||||
)
|
||||
|
||||
def _on_identity_credentials_relation_joined(self, event):
|
||||
"""IdentityCredentials relation joined."""
|
||||
logging.debug("IdentityCredentials on_joined")
|
||||
self.on.connected.emit()
|
||||
self.request_credentials()
|
||||
|
||||
def _on_identity_credentials_relation_changed(self, event):
|
||||
"""IdentityCredentials relation changed."""
|
||||
logging.debug("IdentityCredentials on_changed")
|
||||
try:
|
||||
self.on.ready.emit()
|
||||
except (AttributeError, KeyError):
|
||||
logger.exception('Error when emitting event')
|
||||
|
||||
def _on_identity_credentials_relation_broken(self, event):
|
||||
"""IdentityCredentials relation broken."""
|
||||
logging.debug("IdentityCredentials on_broken")
|
||||
self.on.goneaway.emit()
|
||||
|
||||
@property
|
||||
def _identity_credentials_rel(self) -> Relation:
|
||||
"""The IdentityCredentials relation."""
|
||||
return self.framework.model.get_relation(self.relation_name)
|
||||
|
||||
def get_remote_app_data(self, key: str) -> str:
|
||||
"""Return the value for the given key from remote app data."""
|
||||
data = self._identity_credentials_rel.data[self._identity_credentials_rel.app]
|
||||
return data.get(key)
|
||||
|
||||
@property
|
||||
def api_version(self) -> str:
|
||||
"""Return the api_version."""
|
||||
return self.get_remote_app_data('api-version')
|
||||
|
||||
@property
|
||||
def auth_host(self) -> str:
|
||||
"""Return the auth_host."""
|
||||
return self.get_remote_app_data('auth-host')
|
||||
|
||||
@property
|
||||
def auth_port(self) -> str:
|
||||
"""Return the auth_port."""
|
||||
return self.get_remote_app_data('auth-port')
|
||||
|
||||
@property
|
||||
def auth_protocol(self) -> str:
|
||||
"""Return the auth_protocol."""
|
||||
return self.get_remote_app_data('auth-protocol')
|
||||
|
||||
@property
|
||||
def internal_host(self) -> str:
|
||||
"""Return the internal_host."""
|
||||
return self.get_remote_app_data('internal-host')
|
||||
|
||||
@property
|
||||
def internal_port(self) -> str:
|
||||
"""Return the internal_port."""
|
||||
return self.get_remote_app_data('internal-port')
|
||||
|
||||
@property
|
||||
def internal_protocol(self) -> str:
|
||||
"""Return the internal_protocol."""
|
||||
return self.get_remote_app_data('internal-protocol')
|
||||
|
||||
@property
|
||||
def credentials(self) -> str:
|
||||
return self.get_remote_app_data('credentials')
|
||||
|
||||
@property
|
||||
def username(self) -> str:
|
||||
credentials_id = self.get_remote_app_data('credentials')
|
||||
if not credentials_id:
|
||||
return None
|
||||
|
||||
try:
|
||||
credentials = self.charm.model.get_secret(id=credentials_id)
|
||||
return credentials.get_content().get("username")
|
||||
except SecretNotFoundError:
|
||||
logger.warning(f"Secret {credentials_id} not found")
|
||||
return None
|
||||
|
||||
@property
|
||||
def password(self) -> str:
|
||||
credentials_id = self.get_remote_app_data('credentials')
|
||||
if not credentials_id:
|
||||
return None
|
||||
|
||||
try:
|
||||
credentials = self.charm.model.get_secret(id=credentials_id)
|
||||
return credentials.get_content().get("password")
|
||||
except SecretNotFoundError:
|
||||
logger.warning(f"Secret {credentials_id} not found")
|
||||
return None
|
||||
|
||||
@property
|
||||
def project_name(self) -> str:
|
||||
"""Return the project name."""
|
||||
return self.get_remote_app_data('project-name')
|
||||
|
||||
@property
|
||||
def project_id(self) -> str:
|
||||
"""Return the project id."""
|
||||
return self.get_remote_app_data('project-id')
|
||||
|
||||
@property
|
||||
def user_domain_name(self) -> str:
|
||||
"""Return the name of the user domain."""
|
||||
return self.get_remote_app_data('user-domain-name')
|
||||
|
||||
@property
|
||||
def user_domain_id(self) -> str:
|
||||
"""Return the id of the user domain."""
|
||||
return self.get_remote_app_data('user-domain-id')
|
||||
|
||||
@property
|
||||
def project_domain_name(self) -> str:
|
||||
"""Return the name of the project domain."""
|
||||
return self.get_remote_app_data('project-domain-name')
|
||||
|
||||
@property
|
||||
def project_domain_id(self) -> str:
|
||||
"""Return the id of the project domain."""
|
||||
return self.get_remote_app_data('project-domain-id')
|
||||
|
||||
@property
|
||||
def region(self) -> str:
|
||||
"""Return the region for the auth urls."""
|
||||
return self.get_remote_app_data('region')
|
||||
|
||||
def request_credentials(self) -> None:
|
||||
"""Request credentials from the IdentityCredentials server."""
|
||||
if self.model.unit.is_leader():
|
||||
logging.debug(f'Requesting credentials for {self.charm.app.name}')
|
||||
app_data = self._identity_credentials_rel.data[self.charm.app]
|
||||
app_data['username'] = self.charm.app.name
|
||||
|
||||
|
||||
class HasIdentityCredentialsClientsEvent(EventBase):
|
||||
"""Has IdentityCredentialsClients Event."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class ReadyIdentityCredentialsClientsEvent(EventBase):
|
||||
"""IdentityCredentialsClients Ready Event."""
|
||||
|
||||
def __init__(self, handle, relation_id, relation_name, username):
|
||||
super().__init__(handle)
|
||||
self.relation_id = relation_id
|
||||
self.relation_name = relation_name
|
||||
self.username = username
|
||||
|
||||
def snapshot(self):
|
||||
return {
|
||||
"relation_id": self.relation_id,
|
||||
"relation_name": self.relation_name,
|
||||
"username": self.username,
|
||||
}
|
||||
|
||||
def restore(self, snapshot):
|
||||
super().restore(snapshot)
|
||||
self.relation_id = snapshot["relation_id"]
|
||||
self.relation_name = snapshot["relation_name"]
|
||||
self.username = snapshot["username"]
|
||||
|
||||
|
||||
class IdentityCredentialsClientsGoneAwayEvent(EventBase):
|
||||
"""Has IdentityCredentialsClientsGoneAwayEvent Event."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class IdentityCredentialsClientEvents( |