77
88import logging
99import shlex
10+ from typing import Literal
1011
1112import ops
13+ import pydantic
1214from charms .nginx_ingress_integrator .v0 .nginx_route import require_nginx_route
1315
1416# Log messages can be retrieved using juju debug-log
1517logger = logging .getLogger (__name__ )
1618
17- VALID_LOG_LEVELS = ["info" , "debug" , "warning" , "error" , "critical" ]
19+
20+ class HardwareApiConfig (pydantic .BaseModel ):
21+ """Hardware API Charm configuration."""
22+
23+ log_level : Literal ["info" , "debug" , "warning" , "error" , "critical" ] = "info"
24+ port : int = 30000
25+ hostname : str = "str"
1826
1927
2028class HardwareApiCharm (ops .CharmBase ):
2129 """Charm the service."""
2230
2331 def __init__ (self , * args ):
2432 super ().__init__ (* args )
33+ self .typed_config = self .load_config (HardwareApiConfig , errors = "blocked" )
2534 self ._setup_nginx ()
2635 self .framework .observe (
2736 self .on ["hardware-api" ].pebble_ready ,
@@ -32,9 +41,9 @@ def __init__(self, *args):
3241 def _setup_nginx (self ):
3342 require_nginx_route (
3443 charm = self ,
35- service_hostname = str ( self .config [ " hostname" ]) ,
44+ service_hostname = self .typed_config . hostname ,
3645 service_name = self .app .name ,
37- service_port = int ( self .config [ " port" ]) ,
46+ service_port = self .typed_config . port ,
3847 )
3948
4049 def _on_hardware_api_pebble_ready (self , event : ops .PebbleReadyEvent ):
@@ -44,11 +53,6 @@ def _on_hardware_api_pebble_ready(self, event: ops.PebbleReadyEvent):
4453 self .unit .status = ops .ActiveStatus ()
4554
4655 def _on_config_changed (self , event : ops .ConfigChangedEvent ):
47- log_level = str (self .model .config ["log-level" ]).lower ()
48- if log_level not in VALID_LOG_LEVELS :
49- self .unit .status = ops .BlockedStatus (f"invalid log level: '{ log_level } '" )
50- return
51-
5256 container = self .unit .get_container ("hardware-api" )
5357 if not container .can_connect ():
5458 self .unit .status = ops .WaitingStatus ("waiting for Pebble API" )
@@ -57,7 +61,7 @@ def _on_config_changed(self, event: ops.ConfigChangedEvent):
5761
5862 container .add_layer ("hardware-api" , self ._pebble_layer , combine = True )
5963 container .replan ()
60- logger .debug ("Log level changed to '%s'" , log_level )
64+ logger .debug ("Log level changed to '%s'" , self . typed_config . log_level )
6165 self .unit .status = ops .ActiveStatus ()
6266
6367 @property
@@ -82,9 +86,9 @@ def _pebble_layer(self) -> ops.pebble.LayerDict:
8286 "--host" ,
8387 "0.0.0.0" ,
8488 "--port" ,
85- f"{ self .config [ ' port' ] } " ,
89+ f"{ self .typed_config . port } " ,
8690 "--log-level" ,
87- f"{ self .model . config [ 'log-level' ] } " ,
91+ f"{ self .typed_config . log_level } " ,
8892 ]
8993 ),
9094 "startup" : "enabled" ,
0 commit comments