2 # Copyright 2022 Canonical Ltd.
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
16 # For those usages not covered by the Apache License, Version 2.0 please
17 # contact: legal@canonical.com
19 # To get in touch with the maintainers, please contact:
20 # osm-charmers@lists.launchpad.net
23 # Learn more at: https://juju.is/docs/sdk
27 See more: https://charmhub.io/osm
32 from typing
import Any
, Dict
34 from charms
.nginx_ingress_integrator
.v0
.ingress
import IngressRequires
35 from charms
.observability_libs
.v1
.kubernetes_service_patch
import KubernetesServicePatch
36 from charms
.osm_libs
.v0
.utils
import (
38 check_container_ready
,
41 from charms
.osm_nbi
.v0
.nbi
import NbiRequires
42 from lightkube
.models
.core_v1
import ServicePort
43 from ops
.charm
import CharmBase
44 from ops
.framework
import StoredState
45 from ops
.main
import main
46 from ops
.model
import ActiveStatus
, BlockedStatus
, Container
50 logger
= logging
.getLogger(__name__
)
53 class OsmNgUiCharm(CharmBase
):
54 """OSM NG-UI Kubernetes sidecar charm."""
56 _stored
= StoredState()
58 def __init__(self
, *args
):
59 super().__init
__(*args
)
60 self
.ingress
= IngressRequires(
63 "service-hostname": self
.external_hostname
,
64 "service-name": self
.app
.name
,
65 "service-port": SERVICE_PORT
,
68 self
._observe
_charm
_events
()
69 self
._patch
_k
8s
_service
()
70 self
._stored
.set_default(default_site_patched
=False)
71 self
.nbi
= NbiRequires(self
)
72 self
.container
: Container
= self
.unit
.get_container("ng-ui")
75 def external_hostname(self
) -> str:
76 """External hostname property.
79 str: the external hostname from config.
80 If not set, return the ClusterIP service name.
82 return self
.config
.get("external-hostname") or self
.app
.name
84 # ---------------------------------------------------------------------------
85 # Handlers for Charm Events
86 # ---------------------------------------------------------------------------
88 def _on_config_changed(self
, _
) -> None:
89 """Handler for the config-changed event."""
91 self
._validate
_config
()
92 self
._check
_relations
()
93 # Check if the container is ready.
94 # Eventually it will become ready after the first pebble-ready event.
95 check_container_ready(self
.container
)
97 self
._configure
_service
(self
.container
)
98 self
._update
_ingress
_config
()
100 self
._on
_update
_status
()
101 except CharmError
as e
:
102 logger
.debug(e
.message
)
103 self
.unit
.status
= e
.status
105 def _on_update_status(self
, _
=None) -> None:
106 """Handler for the update-status event."""
108 self
._check
_relations
()
109 check_container_ready(self
.container
)
110 check_service_active(self
.container
, "ng-ui")
111 self
.unit
.status
= ActiveStatus()
112 except CharmError
as e
:
113 logger
.debug(e
.message
)
114 self
.unit
.status
= e
.status
116 def _on_nbi_relation_broken(self
, _
) -> None:
117 """Handler for the nbi relation broken event."""
118 # Check Pebble has started in the container
120 check_container_ready(self
.container
)
121 check_service_active(self
.container
, "ng-ui")
122 self
.container
.stop("ng-ui")
123 self
._stored
.default_site_patched
= False
127 self
.unit
.status
= BlockedStatus("need nbi relation")
129 # ---------------------------------------------------------------------------
130 # Validation and configuration and more
131 # ---------------------------------------------------------------------------
133 def _patch_k8s_service(self
) -> None:
134 port
= ServicePort(SERVICE_PORT
, name
=f
"{self.app.name}")
135 self
.service_patcher
= KubernetesServicePatch(self
, [port
])
137 def _observe_charm_events(self
) -> None:
138 event_handler_mapping
= {
139 # Core lifecycle events
140 self
.on
.ng_ui_pebble_ready
: self
._on
_config
_changed
,
141 self
.on
.config_changed
: self
._on
_config
_changed
,
142 self
.on
.update_status
: self
._on
_update
_status
,
144 self
.on
["nbi"].relation_changed
: self
._on
_config
_changed
,
145 self
.on
["nbi"].relation_broken
: self
._on
_nbi
_relation
_broken
,
147 for event
, handler
in event_handler_mapping
.items():
148 self
.framework
.observe(event
, handler
)
150 def _validate_config(self
) -> None:
151 """Validate charm configuration.
154 CharmError: if charm configuration is invalid.
156 logger
.debug("validating charm config")
158 def _check_relations(self
) -> None:
159 """Validate charm relations.
162 CharmError: if charm configuration is invalid.
164 logger
.debug("check for missing relations")
166 if not self
.nbi
.host
or not self
.nbi
.port
:
167 raise CharmError("need nbi relation")
169 def _update_ingress_config(self
) -> None:
170 """Update ingress config in relation."""
172 "service-hostname": self
.external_hostname
,
173 "max-body-size": self
.config
["max-body-size"],
175 if "tls-secret-name" in self
.config
:
176 ingress_config
["tls-secret-name"] = self
.config
["tls-secret-name"]
177 logger
.debug(f
"updating ingress-config: {ingress_config}")
178 self
.ingress
.update_config(ingress_config
)
180 def _configure_service(self
, container
: Container
) -> None:
181 """Add Pebble layer with the ng-ui service."""
182 logger
.debug(f
"configuring {self.app.name} service")
183 self
._patch
_default
_site
(container
)
184 container
.add_layer("ng-ui", self
._get
_layer
(), combine
=True)
187 def _get_layer(self
) -> Dict
[str, Any
]:
188 """Get layer for Pebble."""
190 "summary": "ng-ui layer",
191 "description": "pebble config layer for ng-ui",
194 "override": "replace",
195 "summary": "ng-ui service",
196 "command": 'nginx -g "daemon off;"',
197 "startup": "enabled",
202 def _patch_default_site(self
, container
: Container
) -> None:
203 max_body_size
= self
.config
.get("max-body-size")
205 self
._stored
.default_site_patched
206 and max_body_size
== self
._stored
.default_site_max_body_size
209 default_site_config
= container
.pull("/etc/nginx/sites-available/default").read()
210 default_site_config
= re
.sub(
211 "client_max_body_size .*\n",
212 f
"client_max_body_size {max_body_size}M;\n",
215 default_site_config
= re
.sub(
217 f
"proxy_pass http://{self.nbi.host}:{self.nbi.port};\n",
220 container
.push("/etc/nginx/sites-available/default", default_site_config
)
221 self
._stored
.default_site_patched
= True
222 self
._stored
.default_site_max_body_size
= max_body_size
225 if __name__
== "__main__": # pragma: no cover