| 1 | package Myriad::Config; | ||
| 2 | |||
| 3 | 5 | ▶ | use Myriad::Class; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | |||
| 5 | our $VERSION = '1.001'; # VERSION | ||
| 6 | our $AUTHORITY = 'cpan:DERIV'; # AUTHORITY | ||
| 7 | |||
| 8 | =encoding utf8 | ||
| 9 | |||
| 10 | =head1 NAME | ||
| 11 | |||
| 12 | Myriad::Config - dynamic configuration management for microservices | ||
| 13 | |||
| 14 | =head1 DESCRIPTION | ||
| 15 | |||
| 16 | Configuration support. | ||
| 17 | |||
| 18 | =cut | ||
| 19 | |||
| 20 | 5 | ▶ | use Getopt::Long qw(GetOptionsFromArray); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 21 | 5 | ▶ | use Pod::Usage; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 22 | 5 | ▶ | use Config::Any; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 23 | 5 | ▶ | use YAML::XS; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 24 | 5 | ▶ | use List::Util qw(pairmap); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 25 | 5 | ▶ | use Ryu::Observable; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 26 | 5 | ▶ | use Myriad::Storage; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 27 | 5 | ▶ | use URI; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 28 | 5 | ▶ | use Myriad::Util::Secret; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 29 | |||
| 30 | 5 | ▶ | use Myriad::Exception::Builder category => 'config'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 31 | |||
| 32 | declare_exception 'ConfigRequired' => ( | ||
| 33 | message => 'A required configuration key was not set' | ||
| 34 | ); | ||
| 35 | |||
| 36 | declare_exception 'UnregisteredConfig' => ( | ||
| 37 | message => 'Config should be registered by calling "config" before usage' | ||
| 38 | ); | ||
| 39 | |||
| 40 | =head1 PACKAGE VARIABLES | ||
| 41 | |||
| 42 | =head2 DEFAULTS | ||
| 43 | |||
| 44 | The C<< %DEFAULTS >> hash provides base values that will be used if no other | ||
| 45 | configuration file, external storage or environment variable provides an | ||
| 46 | alternative. | ||
| 47 | |||
| 48 | =cut | ||
| 49 | |||
| 50 | # Default values | ||
| 51 | |||
| 52 | our %DEFAULTS = ( | ||
| 53 | services => { }, | ||
| 54 | config_path => 'config.yml', | ||
| 55 | transport_redis => 'redis://localhost:6379', | ||
| 56 | transport_redis_cache => 0, | ||
| 57 | transport_cluster => 0, | ||
| 58 | transport_pool_count => 10, | ||
| 59 | transport_wait_time => 15_000, | ||
| 60 | log_level => 'info', | ||
| 61 | library_path => '', | ||
| 62 | opentracing_host => 'localhost', | ||
| 63 | opentracing_port => 6832, | ||
| 64 | subscription_transport => undef, | ||
| 65 | rpc_transport => undef, | ||
| 66 | storage_transport => undef, | ||
| 67 | transport => 'redis', | ||
| 68 | metrics_adapter => 'Statsd', | ||
| 69 | metrics_host => 'localhost', | ||
| 70 | metrics_port => '8125', | ||
| 71 | ); | ||
| 72 | |||
| 73 | =head2 FULLNAME_FOR | ||
| 74 | |||
| 75 | The C<< %FULLNAME_FOR >> hash maps commandline shortcuts for common parameters. | ||
| 76 | |||
| 77 | =cut | ||
| 78 | |||
| 79 | our %FULLNAME_FOR = ( | ||
| 80 | c => 'config_path', | ||
| 81 | l => 'log_level', | ||
| 82 | lib => 'library_path', | ||
| 83 | t => 'transport', | ||
| 84 | s => 'service_name', | ||
| 85 | ); | ||
| 86 | |||
| 87 | |||
| 88 | =head2 SERVICES_CONFIG | ||
| 89 | |||
| 90 | A registry of service configuration defined by the services using the C<< config >> helper. | ||
| 91 | |||
| 92 | =cut | ||
| 93 | |||
| 94 | our %SERVICES_CONFIG; | ||
| 95 | |||
| 96 | =head2 ACTIVE_SERVICES_CONFIG | ||
| 97 | |||
| 98 | A collection of L<Ryu::Observable> instances for notifying services about updates on their | ||
| 99 | configuration. | ||
| 100 | |||
| 101 | =cut | ||
| 102 | |||
| 103 | our %ACTIVE_SERVICES_CONFIG; | ||
| 104 | |||
| 105 | # Our configuration so far. Populated via L</BUILD>, | ||
| 106 | # can be updated by other mechanisms later. | ||
| 107 | has $config; | ||
| 108 | |||
| 109 | has $config_updates_src; | ||
| 110 | |||
| 111 | BUILD (%args) { | ||
| 112 | $config //= {}; | ||
| 113 | $config->{services} //= {}; | ||
| 114 | # Parameter order in decreasing order of preference: | ||
| 115 | # - commandline parameter | ||
| 116 | # - environment | ||
| 117 | # - config file | ||
| 118 | # - defaults | ||
| 119 | |||
| 120 | $self->lookup_from_args($args{commandline}); | ||
| 121 | |||
| 122 | $log->tracef('Defaults %s, shortcuts %s, args %s', \%DEFAULTS, \%FULLNAME_FOR, \%args); | ||
| 123 | $self->lookup_from_env(); | ||
| 124 | |||
| 125 | $config->{config_path} //= $DEFAULTS{config_path}; | ||
| 126 | $self->lookup_from_file($config->{config_path}); | ||
| 127 | |||
| 128 | $config->{$_} //= $DEFAULTS{$_} for keys %DEFAULTS; | ||
| 129 | |||
| 130 | # Populate transports with the default transport if they are not already | ||
| 131 | # configured by the developer | ||
| 132 | my $transport_as_uri = URI->new($config->{transport}); | ||
| 133 | if ($transport_as_uri->has_recognized_scheme) { | ||
| 134 | my $transport_type = $transport_as_uri->scheme; | ||
| 135 | $config->{"transport_$transport_type"} = $transport_as_uri->as_string; | ||
| 136 | $config->{transport} = $transport_as_uri->scheme; | ||
| 137 | } | ||
| 138 | |||
| 139 | $config->{$_} //= $config->{transport} for qw(rpc_transport subscription_transport storage_transport); | ||
| 140 | |||
| 141 | push @INC, split /,:/, $config->{library_path} if $config->{library_path}; | ||
| 142 | |||
| 143 | $config->{$_} = Ryu::Observable->new($config->{$_}) for grep { not ref $config->{$_} } keys %$config; | ||
| 144 | |||
| 145 | $log->debugf("Config is %s", $config); | ||
| 146 | } | ||
| 147 | |||
| 148 | method key ($key) { return $config->{$key} // die 'unknown config key ' . $key } | ||
| 149 | |||
| 150 | method define ($key, $v) { | ||
| 151 | die 'already exists - ' . $key if exists $config->{$key} or exists $DEFAULTS{$key}; | ||
| 152 | $config->{$key} = $DEFAULTS{$key} = Ryu::Observable->new($v); | ||
| 153 | } | ||
| 154 | |||
| 155 | =head2 clear_key | ||
| 156 | |||
| 157 | Delete a single config | ||
| 158 | the best use case for this sub is during tests. | ||
| 159 | |||
| 160 | =cut | ||
| 161 | |||
| 162 | method clear_key($key) { | ||
| 163 | $config->{$key} = undef; | ||
| 164 | } | ||
| 165 | |||
| 166 | =head2 clear_all | ||
| 167 | |||
| 168 | Delete all the config that has been parsed by this module, | ||
| 169 | the best use case for this sub is during tests. | ||
| 170 | |||
| 171 | =cut | ||
| 172 | |||
| 173 | method clear_all { | ||
| 174 | $config = { | ||
| 175 | services => { }, | ||
| 176 | }; | ||
| 177 | } | ||
| 178 | |||
| 179 | =head2 parse_subargs | ||
| 180 | |||
| 181 | A helper to resolve the correct service config | ||
| 182 | |||
| 183 | input is expected to look like: | ||
| 184 | |||
| 185 | <service_name>_[config|instance].<key> | ||
| 186 | |||
| 187 | and this sub will set the correct path to key with the provided value. | ||
| 188 | |||
| 189 | Example: | ||
| 190 | |||
| 191 | dummy_service.config.password | ||
| 192 | |||
| 193 | will end up in | ||
| 194 | |||
| 195 | $config->{services}->{dummy_service}->{config}->{password} | ||
| 196 | |||
| 197 | Takes the following parameters: | ||
| 198 | |||
| 199 | =over 4 | ||
| 200 | |||
| 201 | =item * C<$subarg> - the arguments as passed by the user. | ||
| 202 | |||
| 203 | =item * C<$root> - the level in which we should add the sub arg, we start from $config->{services}. | ||
| 204 | |||
| 205 | =item * C<$value> - the value that we should assign after resolving the config path. | ||
| 206 | |||
| 207 | =back | ||
| 208 | |||
| 209 | =cut | ||
| 210 | |||
| 211 | method parse_subargs ($subarg, $root, $value) { | ||
| 212 | my $instance = $subarg =~ s{[_.]instance[_.](.*)(?=[_.]config)}{} && $1; | ||
| 213 | my $config = $subarg =~ s{[_.]config[_.](.*)$}{} && $1; | ||
| 214 | |||
| 215 | my $service_name = $subarg =~ tr/_/./r; | ||
| 216 | $instance = $instance =~ tr/_/./r if $instance; | ||
| 217 | $config = $config =~ tr/./_/r if $config; | ||
| 218 | |||
| 219 | die 'invalid service name' unless length $service_name; | ||
| 220 | if(length $instance) { | ||
| 221 | $root->{$service_name}{instance}{$instance}{config}{$config} = $value; | ||
| 222 | } else { | ||
| 223 | $root->{$service_name}{config}{$config} = $value; | ||
| 224 | } | ||
| 225 | } | ||
| 226 | |||
| 227 | =head2 lookup_from_args | ||
| 228 | |||
| 229 | Parse the arguments provided from the command line. | ||
| 230 | |||
| 231 | There are many modules that can parse command lines arguments | ||
| 232 | but in our case we have unknown arguments - the services config - that | ||
| 233 | might be passed by the user or might not and they are on top of that nested. | ||
| 234 | |||
| 235 | This sub simply start looking for a match for the arg at hand in C<%DEFAULTS> | ||
| 236 | then it searches in the shortcuts map and lastly it tries to parse it as a subarg. | ||
| 237 | |||
| 238 | Currently this sub takes into account flags (0|1) config and config written as: | ||
| 239 | config=value | ||
| 240 | |||
| 241 | =cut | ||
| 242 | |||
| 243 | method lookup_from_args ($commandline) { | ||
| 244 | return unless $commandline; | ||
| 245 | my $error; | ||
| 246 | |||
| 247 | while (1) { | ||
| 248 | last unless $commandline->@* && ($commandline->[0] =~ /--?./); | ||
| 249 | |||
| 250 | my $arg = shift $commandline->@*; | ||
| 251 | $arg =~ s/--?//; | ||
| 252 | ($arg, my $value) = split '=', $arg; | ||
| 253 | |||
| 254 | # First match arg with expected keys | ||
| 255 | my $key = exists $DEFAULTS{$arg} ? $arg : $FULLNAME_FOR{$arg}; | ||
| 256 | if ($key) { | ||
| 257 | # Either `--example=123` or `--example 123` | ||
| 258 | $value = shift $commandline->@* unless defined $value; | ||
| 259 | $config->{$key} = $value; | ||
| 260 | } elsif ($arg =~ s/service[_|\.]//) { # are we doing service config | ||
| 261 | $value = shift $commandline->@* unless $value; | ||
| 262 | try { | ||
| 263 | $self->parse_subargs($arg, $config->{services}, $value); | ||
| 264 | } catch { | ||
| 265 | $error = "looks like $arg format is wrong can't parse it!"; | ||
| 266 | last; | ||
| 267 | } | ||
| 268 | } else { | ||
| 269 | $error = "don't know how to deal with option $arg"; | ||
| 270 | last | ||
| 271 | } | ||
| 272 | } | ||
| 273 | |||
| 274 | if ($error) { | ||
| 275 | $log->error($error); | ||
| 276 | die pod2usage(1); | ||
| 277 | } | ||
| 278 | } | ||
| 279 | |||
| 280 | =head2 lookup_from_env | ||
| 281 | |||
| 282 | Try to find environment variables that start with C<MYRIAD_*> and parse them. | ||
| 283 | |||
| 284 | =cut | ||
| 285 | |||
| 286 | method lookup_from_env () { | ||
| 287 | $config->{$_} //= $ENV{'MYRIAD_' . uc($_)} for grep { | ||
| 288 | exists $ENV{'MYRIAD_' . uc($_)} | ||
| 289 | } keys %DEFAULTS; | ||
| 290 | |||
| 291 | for(map { /^MYRIAD_SERVICE_(.*)$/ ? [ $_, $1 ] : () } sort keys %ENV) { | ||
| 292 | my ($k, $service) = @$_; | ||
| 293 | $self->parse_subargs( | ||
| 294 | lc($service), | ||
| 295 | $config->{services}, | ||
| 296 | $ENV{$k}, | ||
| 297 | ); | ||
| 298 | } | ||
| 299 | } | ||
| 300 | |||
| 301 | =head2 lookup_from_file | ||
| 302 | |||
| 303 | Fill the config from the config file | ||
| 304 | |||
| 305 | this sub doesn't do much currently since the config | ||
| 306 | structure is modelled exactly like how it should be in the file | ||
| 307 | so it just read the file. | ||
| 308 | |||
| 309 | =cut | ||
| 310 | |||
| 311 | method lookup_from_file ($file_path) { | ||
| 312 | if(-r $file_path) { | ||
| 313 | my ($override) = Config::Any->load_files({ | ||
| 314 | files => [ $file_path ], | ||
| 315 | use_ext => 1 | ||
| 316 | })->@*; | ||
| 317 | |||
| 318 | $log->debugf('override is %s', $override); | ||
| 319 | |||
| 320 | my %expanded = pairmap { | ||
| 321 | ref($b) ? $b->%* : ($a => $b) | ||
| 322 | } $override->%*; | ||
| 323 | |||
| 324 | $config->{$_} //= $expanded{$_} for sort keys %expanded; | ||
| 325 | |||
| 326 | # Merge the services config | ||
| 327 | $config->{services} = { | ||
| 328 | $expanded{services}->%*, | ||
| 329 | $config->{services}->%*, | ||
| 330 | } if $expanded{services}; | ||
| 331 | } | ||
| 332 | } | ||
| 333 | |||
| 334 | =head2 service_config | ||
| 335 | |||
| 336 | Takes a service base package and its current name | ||
| 337 | and tries to resolve its config from: | ||
| 338 | |||
| 339 | 1. The framework storage itself (i.e Redis or Postgres ..etc). | ||
| 340 | 2. From the config parsed earlier (cmd, env, file). | ||
| 341 | |||
| 342 | and if it fails to find a required config it will throw an error. | ||
| 343 | |||
| 344 | it takes | ||
| 345 | |||
| 346 | =over 4 | ||
| 347 | |||
| 348 | =item * C<pkg> - The package name of the service, will be used to lookup for generic config | ||
| 349 | |||
| 350 | =item * C<service_name> - The current service name either from the registry or as it bassed by the user, useful for instance config | ||
| 351 | |||
| 352 | =back | ||
| 353 | |||
| 354 | =cut | ||
| 355 | |||
| 356 | async method service_config ($pkg, $service_name) { | ||
| 357 | my $service_config = {}; | ||
| 358 | my $instance = $service_name =~ s/\[(.*)\]$// && $1; | ||
| 359 | my $available_config = $config->{services}->{$service_name}->{config}; | ||
| 360 | |||
| 361 | my $instance_overrides = {}; | ||
| 362 | $instance_overrides = | ||
| 363 | $config->{services}->{$service_name}->{instance}->{$instance}->{config} if $instance; | ||
| 364 | if(my $declared_config = $SERVICES_CONFIG{$pkg}) { | ||
| 365 | for my $key (keys $declared_config->%*) { | ||
| 366 | my $value; | ||
| 367 | # First try to hit storage | ||
| 368 | my $storage_request = await $self->from_storage($service_name, $instance, $key); | ||
| 369 | $value = $storage_request->{value}; | ||
| 370 | |||
| 371 | # nothing from storage then try other sources | ||
| 372 | |||
| 373 | $value //= $instance_overrides->{$key} // | ||
| 374 | $available_config->{$key} // | ||
| 375 | $declared_config->{$key}->{default} // | ||
| 376 | Myriad::Exception::Config::ConfigRequired->throw(reason => $key); | ||
| 377 | $value = Myriad::Util::Secret->new($value) if $declared_config->{$key}->{secure}; | ||
| 378 | $ACTIVE_SERVICES_CONFIG{$storage_request->{key}} = $service_config->{$key} = Ryu::Observable->new($value); | ||
| 379 | } | ||
| 380 | } | ||
| 381 | |||
| 382 | return $service_config; | ||
| 383 | } | ||
| 384 | |||
| 385 | =head2 service_name | ||
| 386 | |||
| 387 | Check if the developer configured a name for this service. | ||
| 388 | This is different from service_config because we are going | ||
| 389 | to check args and ENV only looking using the default | ||
| 390 | L<Myriad::Registry> assigned name | ||
| 391 | |||
| 392 | =cut | ||
| 393 | |||
| 394 | method service_name($name_from_registry) { | ||
| 395 | $config->{services}->{$name_from_registry}->{config}->{name}; | ||
| 396 | } | ||
| 397 | |||
| 398 | =head2 from_storage | ||
| 399 | |||
| 400 | Tries to find the config key in the storage using L<Myriad::Storage>. | ||
| 401 | |||
| 402 | it takes | ||
| 403 | |||
| 404 | =over 4 | ||
| 405 | |||
| 406 | =item * C<service_name> - The service name. | ||
| 407 | |||
| 408 | =item * C<instance> - If the service has many instances (e.g demo, production) this should the identifier. | ||
| 409 | |||
| 410 | =item * C<key> - The required config key (e.g password, username ..etc). | ||
| 411 | |||
| 412 | =back | ||
| 413 | |||
| 414 | =cut | ||
| 415 | |||
| 416 | async method from_storage ($service_name, $instance, $key) { | ||
| 417 | my $storage = $Myriad::Storage::STORAGE; | ||
| 418 | my $key_service_name = $instance ? "${service_name}[${instance}]" : $service_name; | ||
| 419 | my $config_key = "config.service.$key_service_name/$key"; | ||
| 420 | my $value; | ||
| 421 | if ($storage) { | ||
| 422 | # First try instance specific | ||
| 423 | $value = await $storage->get($config_key); | ||
| 424 | # we are dealing with an instance but no specific value for it | ||
| 425 | # then we try the general one | ||
| 426 | if(!$value && $instance) { | ||
| 427 | $config_key = "config.service.$service_name/$key"; | ||
| 428 | $value = await $storage->get($config_key); | ||
| 429 | } | ||
| 430 | } | ||
| 431 | |||
| 432 | return {key => $config_key, value => $value}; | ||
| 433 | } | ||
| 434 | |||
| 435 | async method listen_for_updates () { | ||
| 436 | my $storage = $Myriad::Storage::STORAGE; | ||
| 437 | if ($storage) { | ||
| 438 | try { | ||
| 439 | # This step might throw | ||
| 440 | my $sub = await $storage->watch_keyspace('config*'); | ||
| 441 | $sub->map(async sub { | ||
| 442 | my $key = shift; | ||
| 443 | if(my $observable = $ACTIVE_SERVICES_CONFIG{$key}) { | ||
| 444 | my $updated_value = await $storage->get($key); | ||
| 445 | if ($observable->value->isa('Myriad::Util::Secret')) { | ||
| 446 | $updated_value = Myriad::Util::Secret->new($updated_value); | ||
| 447 | } | ||
| 448 | $observable->set($updated_value); | ||
| 449 | $log->tracef('Detected an update for config key: %s, new value: %s', $key, $updated_value); | ||
| 450 | } | ||
| 451 | })->resolve->completed->retain->on_fail(sub { | ||
| 452 | $log->warnf('Config: config updates listener failed - %s', shift); | ||
| 453 | }); | ||
| 454 | } catch { | ||
| 455 | $log->trace('Config: transport does not support keyspace notifications'); | ||
| 456 | } | ||
| 457 | } else { | ||
| 458 | $log->warn('Config: Storage is not initiated, cannot listen to config updates'); | ||
| 459 | } | ||
| 460 | } | ||
| 461 | |||
| 462 | method DESTROY { } | ||
| 463 | |||
| 464 | method AUTOLOAD () { | ||
| 465 | my ($k) = our $AUTOLOAD =~ m{^.*::([^:]+)$}; | ||
| 466 | die 'unknown config key ' . $k unless blessed $config->{$k} && $config->{$k}->isa('Ryu::Observable'); | ||
| 467 | my $code = method () { return $self->key($k); }; | ||
| 468 | { no strict 'refs'; *$k = $code; } | ||
| 469 | return $self->$code(); | ||
| 470 | } | ||
| 471 | |||
| 472 | 1; | ||
| 473 | |||
| 474 | =head1 AUTHOR | ||
| 475 | |||
| 476 | Deriv Group Services Ltd. C<< DERIV@cpan.org >>. | ||
| 477 | |||
| 478 | See L<Myriad/CONTRIBUTORS> for full details. | ||
| 479 | |||
| 480 | =head1 LICENSE | ||
| 481 | |||
| 482 | Copyright Deriv Group Services Ltd 2020-2022. Licensed under the same terms as Perl itself. | ||
| 483 | |||