Application¤
The asab.Application
class maintains the global application state. You can provide your own implementation by
creating a subclass. There should be only one Application
object in the process.
Creating a new ASAB application:
To create a new ASAB application, just create a subclass of asab.Application
object and use the run()
method:
import asab
class MyApplication(asab.Application):
pass
if __name__ == '__main__':
app = MyApplication()
app.run()
Then run the application from your terminal
and you should see the following output:
The app will be running until you stop it by pressing Ctrl+C
.
To create an application that performs some operations and then stops, use the stop()
method.
import asab
class MyApplication(asab.Application):
async def main(self):
print("Hello world!")
self.stop()
if __name__ == '__main__':
app = MyApplication()
app.run()
with the output:
Application Lifecycle¤
Runtime of the Application
object is driven by asyncio
event loop which runs asynchronous tasks and callbacks, performs network IO operations, and runs subprocesses.
ASAB is designed around the inversion of control principle. It means that the ASAB is in control of the application lifecycle. The custom-written code receives the flow from ASAB via callbacks or handlers. Inversion of control is used to increase modularity of the code and make it extensible.
The application lifecycle is divided into 3 phases: init-time, run-time, and exit-time.
Init-time¤
The init-time happens during Application
constructor call.
At this time:
- Configuration and command line arguments are loaded and
asab.Config
object is accessed. - Asynchronous callback
Application.initialize()
is executed. - Application housekeeping is scheduled.
- Publish-Subscribe message Application.init! is published.
The asynchronous callback Application.initialize()
is intended to be overridden by a user.
This is where you typically load Modules and register Services, see Modules and Services section.
class MyApplication(asab.Application):
async def initialize(self):
# Custom initialization
from module_sample import Module
self.add_module(Module)
Run-time¤
The run-time starts after all the modules and services are loaded. This is where the application typically spends the most time. At this time:
- Publish-Subscribe message Application.run! is published.
- The asynchronous callback
Application.main()
is executed.
The coroutine Application.main()
is intended to be overwritten by a user.
If main()
method is completed without calling stop()
, then the application will run forever.
Exit-time¤
The method Application.stop()
gracefully terminates the run-time and commences the exit-time.
This method is automatically called by SIGINT
and SIGTERM
.
It also includes a response to Ctrl-C
on UNIX-like systems.
When this method is called exactly three times, it abruptly exits the application (aka emergency abort).
Note
You need to install the win32api
module to use Ctrl-C
or an emergency abort properly with ASAB on Windows.
It is an optional dependency of ASAB.
The parameter exit_code
allows you to specify the application exit code.
At exit-time:
- Publish-Subscribe message Application.exit! is published.
- Asynchronous callback
Application.finalize()
is executed.
Application.finalize()
is intended to be overridden by an user.
It can be used for storing backup data for the next start of the application, custom operations when terminating services, sending signals to other applications etc.
Command-line parser¤
The method create_argument_parser()
creates an argparse.ArgumentParser
. This method can be overloaded to adjust command-line argument parser.
The application object calls this method during init-time to process command-line arguments. You can overload this method to provide your own implementation of a command-line argument parser.
The Description
attribute is a text that will be displayed in a help text (--help
).
It is expected that your own value will be provided. The default value is ""
(empty string).
Default ASAB arguments:
Argument | Type | Action |
---|---|---|
-c , --config |
str | Specify a path to a configuration file |
-d , --daemonize |
bool | Run daemonized (in the background) |
-k , --kill |
bool | Kill a running daemon and quit |
-l , --log-file |
str | Specify a path to a log file |
-s , --syslog |
bool | Enable logging to a syslog |
-v , --verbose |
bool | Print more information (enable debug output) |
-w , --web-api |
str | Activate Asab web API (default listening port is 0.0.0.0:8080) |
--startup-housekeeping |
Trigger housekeeping event immediately after application startup |
UTC Time¤
The method time()
returns the current "event loop time"
in seconds since the epoch as a floating point number.
The specific date of the epoch and the handling of leap seconds is platform dependent.
On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC)
and leap seconds are not counted towards the time in seconds since the epoch.
This is commonly referred to as Unix time.
A call of the time.time()
function could be expensive.
This method provides a cheaper version of the call that returns a current wall time in UTC.
Reference¤
asab.application.Application
¤
The base application object that maintains the global application state.
You can provide your own implementation by creating a subclass. It is intended to be a Singleton.
Examples:
class MyApplication(asab.Application):
async def main(self):
print("Hello world!")
self.stop()
if __name__ == "__main__":
app = MyApplication()
app.run()
Source code in asab/application.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 |
|
ExitCode: typing.Union[int, str] = os.EX_OK
instance-attribute
¤
The actual value of the exit code that can be set via set_exit_code()
method.
Examples:
The example of the exit code handling in the main()
function of the application:
Exit code | Meaning |
---|---|
0 | success |
1 | abnormal termination of a program perhaps as a result a minor problem in the code |
"!RESTART!" | hard restart of the whole application |
Modules: list[asab.Module] = []
instance-attribute
¤
A list of modules that has been added to the application.
Services: dict[str, asab.Service] = {}
instance-attribute
¤
A dictionary of registered services.
__init__(args=None, modules=[])
¤
Initialize the Application provided with arguments and modules.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
args
|
Optional[list]
|
sequence of arguments to be parsed by |
None
|
modules
|
list
|
list of ASAB modules to be added by |
[]
|
Examples:
class MyApplication(asab.Application):
def __init__(self):
super().__init__(modules=[asab.web.Module, asab.zookeeper.Module])
Source code in asab/application.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
|
add_module(module_class)
¤
Load a new module.
Source code in asab/application.py
create_argument_parser(prog=None, usage=None, description=None, epilog=None, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True)
¤
Create an argparse.ArgumentParser
object supplemented by default ASAB arguments.
This method can be overridden to adjust argparse configuration.
Refer to the Python standard library to argparse.ArgumentParser
for the details.
Source code in asab/application.py
finalize()
async
¤
get_pidfile_path()
¤
Get the path for PID file from the configuration.
PID file is a file that contains process id of the ASAB process. It is used for interaction with OS respective it's control of running services.
- If the
pidfile
is set to the empty string, return None. - If
pidfile
is set to "!", return the default PID file path (in/var/run/
folder). This is the default value.
Example of PID path configuration:
Returns:
Type | Description |
---|---|
Optional[str]
|
The path to the |
Source code in asab/application.py
get_service(service_name)
¤
Get a new service by its name.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
service_name
|
str
|
Name of the service to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Service]
|
The service object associated with the provided service_name, |
Optional[Service]
|
or None if the service is not registered. |
Source code in asab/application.py
initialize()
async
¤
main()
async
¤
parse_arguments(args=None)
¤
Parse the command line arguments and set the default values for the configuration accordingly.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
args
|
The arguments to parse. If not set, sys.argv[1:] will be used. |
None
|
Returns:
Type | Description |
---|---|
The arguments that were parsed. |
Source code in asab/application.py
restart()
¤
Schedule a hard restart of the whole application.
This function works by using os.execv()
, which replaces the current process with a new one (without creating a new process ID).
Arguments and environment variables will be retained.
Warning
Please note that this will work on Unix-based systems only, as it uses a feature specific to Unix.
Hint
Be careful while using this function, make sure you have some control
over when and how this function is being called to avoid any unexpected process restarts.
It is not common to use these types of function calls in Python applications.
Source code in asab/application.py
run()
¤
Run the application.
Returns:
Type | Description |
---|---|
int
|
Exit code of the finalized process. |
Source code in asab/application.py
set_exit_code(exit_code, force=False)
¤
Set the exit code of the application.
If force
is False
, the exit code will be set only if the previous value is lower than the new one.
If force
is True
, the exit code value is set to exit_code
value disregarding the previous value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
exit_code
|
str | int
|
The exit code value. |
required |
force
|
bool
|
Force the exit code reassignment. |
False
|
Source code in asab/application.py
stop(exit_code=None)
¤
Gracefully terminate the run-time and commence the exit-time.
This method is automatically called by SIGINT
and SIGTERM
.
It also includes a response to Ctrl-C
on UNIX-like system.
When this method is called 3x, it abruptly exits the application (aka emergency abort).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
exit_code
|
int
|
Exit code of the finalized process. |
None
|
Source code in asab/application.py
time()
¤
Return UTC UNIX timestamp using a loop time (a fast way how to get a wall clock time).
Returns:
Type | Description |
---|---|
float
|
Current UTC UNIX timestamp. |