summaryrefslogtreecommitdiff
path: root/python-pyctuator.spec
blob: f51004e55ddddbd05e2aa9a8897119577ad29941 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
%global _empty_manifest_terminate_build 0
Name:		python-pyctuator
Version:	1.0.2
Release:	1
Summary:	A Python implementation of the Spring Actuator API for popular web frameworks
License:	Apache Software License
URL:		https://github.com/SolarEdgeTech/pyctuator
Source0:	https://mirrors.nju.edu.cn/pypi/web/packages/9f/8f/d3a3bcb18d39e9d23b280cf1cd2b1b4c8b1463f1290dffc5972c0cac290c/pyctuator-1.0.2.tar.gz
BuildArch:	noarch

Requires:	python3-psutil
Requires:	python3-flask
Requires:	python3-fastapi
Requires:	python3-uvicorn
Requires:	python3-sqlalchemy
Requires:	python3-PyMySQL
Requires:	python3-cryptography
Requires:	python3-redis
Requires:	python3-aiohttp
Requires:	python3-tornado

%description
[![PyPI](https://img.shields.io/pypi/v/pyctuator?color=green&style=plastic)](https://pypi.org/project/pyctuator/)
[![build](https://github.com/SolarEdgeTech/pyctuator/workflows/build/badge.svg)](https://github.com/SolarEdgeTech/pyctuator/)
[![Codecov](https://img.shields.io/codecov/c/github/SolarEdgeTech/pyctuator?style=plastic)](https://codecov.io/gh/SolarEdgeTech/pyctuator)

# Pyctuator

Monitor Python web apps using 
[Spring Boot Admin](https://github.com/codecentric/spring-boot-admin). 

Pyctuator supports **[Flask](https://palletsprojects.com/p/flask/)**, **[FastAPI](https://fastapi.tiangolo.com/)**, **[aiohttp](https://docs.aiohttp.org/)** and **[Tornado](https://www.tornadoweb.org/)**. **Django** support is planned as well.

The following video shows a FastAPI web app being monitored and controled using Spring Boot Admin.
 
![Pyctuator Example](examples/images/Pyctuator_Screencast.gif)

The complete example can be found in [Advanced example](examples/Advanced/README.md).

## Requirements
Python 3.9+

Pyctuator has zero hard dependencies.

## Installing
Install Pyctuator using pip: `pip3 install pyctuator`

## Why?
Many Java shops use Spring Boot as their main web framework for developing
microservices. 
These organizations often use Spring Actuator together with Spring Boot Admin
to monitor their microservices' status, gain access to applications'
 state and configuration, manipulate log levels, etc.
 
While Spring Boot is suitable for many use-cases, it is very common for organizations 
to also have a couple of Python microservices, as Python is often more suitable for 
some types of applications. The most common examples are Data Science and Machine Learning
applications.

Setting up a proper monitoring tool for these microservices is a complex task, and might
not be justified for just a few Python microservices in a sea of Java microservices.

This is where Pyctuator comes in. It allows you to easily integrate your Python
microservices into your existing Spring Boot Admin deployment.

## Main Features
Pyctuator is a partial Python implementation of the 
[Spring Actuator API](https://docs.spring.io/spring-boot/docs/2.1.8.RELEASE/actuator-api/html/)  . 

It currently supports the following Actuator features:

* **Application details**
* **Metrics**
    * Memory usage
    * Disk usage 
    * Custom metrics
* **Health monitors**
    * Built in MySQL health monitor
    * Built in Redis health monitor
    * Custom health monitors
* **Environment**
* **Loggers** - Easily change log levels during runtime
* **Log file** - Tail the application's log file
* **Thread dump** - See which threads are running
* **HTTP traces** - Tail recent HTTP requests, including status codes and latency

## Quickstart
The examples below show a minimal integration of **FastAPI**, **Flask** and **aiohttp** applications with **Pyctuator**.

After installing Flask/FastAPI/aiohttp and Pyctuator, start by launching a local Spring Boot Admin instance:

```sh
docker run --rm -p 8080:8080 --add-host=host.docker.internal:host-gateway michayaak/spring-boot-admin:2.2.3-1
```

Then go to `http://localhost:8080` to get to the web UI.

### Flask
The following example is complete and should run as is.

```python
from flask import Flask
from pyctuator.pyctuator import Pyctuator

app_name = "Flask App with Pyctuator"
app = Flask(app_name)


@app.route("/")
def hello():
    return "Hello World!"


Pyctuator(
    app,
    app_name,
    app_url="http://host.docker.internal:5000",
    pyctuator_endpoint_url="http://host.docker.internal:5000/pyctuator",
    registration_url="http://localhost:8080/instances"
)

app.run(debug=False, port=5000)
```

The application will automatically register with Spring Boot Admin upon start up.

Log in to the Spring Boot Admin UI at `http://localhost:8080` to interact with the application. 

### FastAPI
The following example is complete and should run as is.

```python
from fastapi import FastAPI
from uvicorn import Server

from uvicorn.config import Config
from pyctuator.pyctuator import Pyctuator


app_name = "FastAPI App with Pyctuator"
app = FastAPI(title=app_name)


@app.get("/")
def hello():
    return "Hello World!"


Pyctuator(
    app,
    "FastAPI Pyctuator",
    app_url="http://host.docker.internal:8000",
    pyctuator_endpoint_url="http://host.docker.internal:8000/pyctuator",
    registration_url="http://localhost:8080/instances"
)

Server(config=(Config(app=app, loop="asyncio"))).run()
```

The application will automatically register with Spring Boot Admin upon start up.

Log in to the Spring Boot Admin UI at `http://localhost:8080` to interact with the application. 

### aiohttp
The following example is complete and should run as is.

```python
from aiohttp import web
from pyctuator.pyctuator import Pyctuator

app = web.Application()
routes = web.RouteTableDef()

@routes.get("/")
def hello():
    return web.Response(text="Hello World!")

Pyctuator(
    app,
    "aiohttp Pyctuator",
    app_url="http://host.docker.internal:8888",
    pyctuator_endpoint_url="http://host.docker.internal:8888/pyctuator",
    registration_url="http://localhost:8080/instances"
)

app.add_routes(routes)
web.run_app(app, port=8888)
```

The application will automatically register with Spring Boot Admin upon start up.

Log in to the Spring Boot Admin UI at `http://localhost:8080` to interact with the application.

### Registration Notes
When registering a service in Spring Boot Admin, note that:
* **Docker** - If the Spring Boot Admin is running in a container while the managed service is running in the docker-host directly, the `app_url` and `pyctuator_endpoint_url` should use `host.docker.internal` as the url's host so Spring Boot Admin will be able to connect to the monitored service.
* **Http Traces** - In order for the "Http Traces" tab to be able to hide requests sent by Spring Boot Admin to the Pyctuator endpoint, `pyctuator_endpoint_url` must be using the same host and port as `app_url`.
* **HTTPS** - If Pyctuator is to be registered with Spring Boot Admin using HTTPS and the default SSL context is inappropriate, you can provide your own `ssl.SSLContext` using the `ssl_context` optional parameter of the `Pyctuator` constructor.
* **Insecure HTTPS** - If Spring Boot Admin is using HTTPS with self-signed certificate, set the `PYCTUATOR_REGISTRATION_NO_CERT` environment variable so Pyctuator will disable certificate validation when registering (and deregistering).

## Advanced Configuration
The following sections are intended for advanced users who want to configure advanced Pyctuator features.

### Application Info
While Pyctuator only needs to know the application's name, we recommend that applications monitored by Spring 
Boot Admin will show additional build and git details. 
This becomes handy when scaling out a service to multiple instances by showing the version of each instance.
To do so, you can provide additional build and git info using methods of the Pyctuator object:

```python
pyctuator = Pyctuator(...)  # arguments removed for brevity

pyctuator.set_build_info(
    name="app",
    version="1.3.1",
    time=datetime.fromisoformat("2019-12-21T10:09:54.876091"),
)

pyctuator.set_git_info(
    commit="7d4fef3",
    time=datetime.fromisoformat("2019-12-24T14:18:32.123432"),
    branch="origin/master",
)
```

Once you configure build and git info, you should see them in the Details tab of Spring Boot Admin:

![Detailed Build Info](examples/images/Main_Details_BuildInfo.png)

### Additional Application Info
In addition to adding build and git info, Pyctuator allows adding arbitrary application details to the "Info" section in SBA.

This is done by initializing the `additional_app_info` parameter with an arbitrary dictionary.
For example, you can provide links to your application's metrics:
```python
Pyctuator(
  app,
  "Flask Pyctuator",
  app_url=f"http://172.18.0.1:5000",
  pyctuator_endpoint_url=f"http://172.18.0.1:5000/pyctuator",
  registration_url=f"http://localhost:8080/instances",
  app_description="Demonstrate Spring Boot Admin Integration with Flask",
  additional_app_info=dict(
    serviceLinks=dict(
      metrics="http://xyz/service/metrics"
    ),
    podLinks=dict(
      metrics=["http://xyz/pod/metrics/memory", "http://xyz/pod/metrics/cpu"]
    )
  )
)
```

This will result with the following Info page in SBA:
![img.png](examples/images/Additional_App_Info.png)

### DB Health
For services that use SQL database via SQLAlchemy, Pyctuator can easily monitor and expose the connection's health 
using the DbHealthProvider class as demonstrated below:

```python
engine = create_engine("mysql+pymysql://root:root@localhost:3306")
pyctuator = Pyctuator(...)  # arguments removed for brevity
pyctuator.register_health_provider(DbHealthProvider(engine))
```

Once you configure the health provider, you should see DB health info in the Details tab of Spring Boot Admin:

![DB Health](examples/images/Main_DB_Health.png)

### Redis health
If your service is using Redis, Pyctuator can monitor the connection to Redis by simply initializing a `RedisHealthProvider`:

```python
r = redis.Redis()
pyctuator = Pyctuator(...)  # arguments removed for brevity
pyctuator.register_health_provider(RedisHealthProvider(r))
```

### Custom Environment
Out of the box, Pyctuator exposes Python's environment variables to Spring Boot Admin.

In addition, an application may register an environment provider to provide additional configuration that should be exposed via Spring Boot Admin. 

When the environment provider is called it should return a dictionary describing the environment. The returned dictionary is exposed to Spring Boot Admin.

Since Spring Boot Admin doesn't support hierarchical environment (only a flat key/value mapping), the provided environment is flattened as dot-delimited keys.

Pyctuator tries to hide secrets from being exposed to Spring Boot Admin by replacing the values of "suspicious" keys with ***.

Suspicious keys are keys that contain the words "secret", "password" and some forms of "key".

For example, if an application's configuration looks like this:

```python
config = {
    "a": "s1",
    "b": {
        "secret": "ha ha",
        "c": 625,
    },
    "d": {
        "e": True,
        "f": "hello",
        "g": {
            "h": 123,
            "i": "abcde"
        }
    }
}
```

An environment provider can be registered like so:

```python
pyctuator.register_environment_provider("config", lambda: config)
```

### Filesystem and Memory Metrics
Pyctuator can provide filesystem and memory metrics.

To enable these metrics, install [psutil](https://github.com/giampaolo/psutil)

Note that the `psutil` dependency is **optional** and is only required if you want to enable filesystem and memory monitoring.

### Loggers
Pyctuator leverages Python's builtin `logging` framework and allows controlling log levels at runtime.
 
Note that in order to control uvicorn's log level, you need to provide a logger object when instantiating it. For example:
```python
myFastAPIServer = Server(
    config=Config(
        logger=logging.getLogger("uvi"), 
        app=app, 
        loop="asyncio"
    )
)
```

### Spring Boot Admin Using Basic Authentication
Pyctuator supports registration with Spring Boot Admin that requires basic authentications. The credentials are provided when initializing the Pyctuator instance as follows:
```python
# NOTE: Never include secrets in your code !!!
auth = BasicAuth(os.getenv("sba-username"), os.getenv("sba-password"))

Pyctuator(
    app,
    "Flask Pyctuator",
    app_url="http://localhost:5000",
    pyctuator_endpoint_url=f"http://localhost:5000/pyctuator",
    registration_url=f"http://spring-boot-admin:8080/instances",
    registration_auth=auth,
)
``` 

### Protecting Pyctuator with authentication
Since there are numerous standard approaches to protect an API, Pyctuator doesn't explicitly support any of them. Instead, Pyctuator allows to customize its integration with the web-framework.
See the example in [fastapi_with_authentication_example_app.py](examples/FastAPI/fastapi_with_authentication_example_app.py).

## Full blown examples
The `examples` folder contains full blown Python projects that are built using [Poetry](https://python-poetry.org/).

To run these examples, you'll need to have Spring Boot Admin running in a local docker container. A Spring Boot Admin Docker image is available [here](https://hub.docker.com/r/michayaak/spring-boot-admin).

Unless the example includes a docker-compose file, you'll need to start Spring Boot Admin using docker directly:
```sh
docker run --rm -p 8080:8080 --add-host=host.docker.internal:host-gateway michayaak/spring-boot-admin:2.2.3-1
```
(the docker image's tag represents the version of Spring Boot Admin, so if you need to use version `2.0.0`, use `michayaak/spring-boot-admin:2.0.0` instead, note it accepts connections on port 8082).

The examples include
* [FastAPI Example](examples/FastAPI/README.md) - demonstrates integrating Pyctuator with the FastAPI web framework.
* [Flask Example](examples/Flask/README.md) - demonstrates integrating Pyctuator with the Flask web framework.
* [Advanced Example](examples/Advanced/README.md) - demonstrates configuring and using all the advanced features of Pyctuator.

## Contributing
To set up a development environment, make sure you have Python 3.9 or newer installed, and run `make bootstrap`.

Use `make check` to run static analysis tools.

Use `make test` to run tests.


%package -n python3-pyctuator
Summary:	A Python implementation of the Spring Actuator API for popular web frameworks
Provides:	python-pyctuator
BuildRequires:	python3-devel
BuildRequires:	python3-setuptools
BuildRequires:	python3-pip
%description -n python3-pyctuator
[![PyPI](https://img.shields.io/pypi/v/pyctuator?color=green&style=plastic)](https://pypi.org/project/pyctuator/)
[![build](https://github.com/SolarEdgeTech/pyctuator/workflows/build/badge.svg)](https://github.com/SolarEdgeTech/pyctuator/)
[![Codecov](https://img.shields.io/codecov/c/github/SolarEdgeTech/pyctuator?style=plastic)](https://codecov.io/gh/SolarEdgeTech/pyctuator)

# Pyctuator

Monitor Python web apps using 
[Spring Boot Admin](https://github.com/codecentric/spring-boot-admin). 

Pyctuator supports **[Flask](https://palletsprojects.com/p/flask/)**, **[FastAPI](https://fastapi.tiangolo.com/)**, **[aiohttp](https://docs.aiohttp.org/)** and **[Tornado](https://www.tornadoweb.org/)**. **Django** support is planned as well.

The following video shows a FastAPI web app being monitored and controled using Spring Boot Admin.
 
![Pyctuator Example](examples/images/Pyctuator_Screencast.gif)

The complete example can be found in [Advanced example](examples/Advanced/README.md).

## Requirements
Python 3.9+

Pyctuator has zero hard dependencies.

## Installing
Install Pyctuator using pip: `pip3 install pyctuator`

## Why?
Many Java shops use Spring Boot as their main web framework for developing
microservices. 
These organizations often use Spring Actuator together with Spring Boot Admin
to monitor their microservices' status, gain access to applications'
 state and configuration, manipulate log levels, etc.
 
While Spring Boot is suitable for many use-cases, it is very common for organizations 
to also have a couple of Python microservices, as Python is often more suitable for 
some types of applications. The most common examples are Data Science and Machine Learning
applications.

Setting up a proper monitoring tool for these microservices is a complex task, and might
not be justified for just a few Python microservices in a sea of Java microservices.

This is where Pyctuator comes in. It allows you to easily integrate your Python
microservices into your existing Spring Boot Admin deployment.

## Main Features
Pyctuator is a partial Python implementation of the 
[Spring Actuator API](https://docs.spring.io/spring-boot/docs/2.1.8.RELEASE/actuator-api/html/)  . 

It currently supports the following Actuator features:

* **Application details**
* **Metrics**
    * Memory usage
    * Disk usage 
    * Custom metrics
* **Health monitors**
    * Built in MySQL health monitor
    * Built in Redis health monitor
    * Custom health monitors
* **Environment**
* **Loggers** - Easily change log levels during runtime
* **Log file** - Tail the application's log file
* **Thread dump** - See which threads are running
* **HTTP traces** - Tail recent HTTP requests, including status codes and latency

## Quickstart
The examples below show a minimal integration of **FastAPI**, **Flask** and **aiohttp** applications with **Pyctuator**.

After installing Flask/FastAPI/aiohttp and Pyctuator, start by launching a local Spring Boot Admin instance:

```sh
docker run --rm -p 8080:8080 --add-host=host.docker.internal:host-gateway michayaak/spring-boot-admin:2.2.3-1
```

Then go to `http://localhost:8080` to get to the web UI.

### Flask
The following example is complete and should run as is.

```python
from flask import Flask
from pyctuator.pyctuator import Pyctuator

app_name = "Flask App with Pyctuator"
app = Flask(app_name)


@app.route("/")
def hello():
    return "Hello World!"


Pyctuator(
    app,
    app_name,
    app_url="http://host.docker.internal:5000",
    pyctuator_endpoint_url="http://host.docker.internal:5000/pyctuator",
    registration_url="http://localhost:8080/instances"
)

app.run(debug=False, port=5000)
```

The application will automatically register with Spring Boot Admin upon start up.

Log in to the Spring Boot Admin UI at `http://localhost:8080` to interact with the application. 

### FastAPI
The following example is complete and should run as is.

```python
from fastapi import FastAPI
from uvicorn import Server

from uvicorn.config import Config
from pyctuator.pyctuator import Pyctuator


app_name = "FastAPI App with Pyctuator"
app = FastAPI(title=app_name)


@app.get("/")
def hello():
    return "Hello World!"


Pyctuator(
    app,
    "FastAPI Pyctuator",
    app_url="http://host.docker.internal:8000",
    pyctuator_endpoint_url="http://host.docker.internal:8000/pyctuator",
    registration_url="http://localhost:8080/instances"
)

Server(config=(Config(app=app, loop="asyncio"))).run()
```

The application will automatically register with Spring Boot Admin upon start up.

Log in to the Spring Boot Admin UI at `http://localhost:8080` to interact with the application. 

### aiohttp
The following example is complete and should run as is.

```python
from aiohttp import web
from pyctuator.pyctuator import Pyctuator

app = web.Application()
routes = web.RouteTableDef()

@routes.get("/")
def hello():
    return web.Response(text="Hello World!")

Pyctuator(
    app,
    "aiohttp Pyctuator",
    app_url="http://host.docker.internal:8888",
    pyctuator_endpoint_url="http://host.docker.internal:8888/pyctuator",
    registration_url="http://localhost:8080/instances"
)

app.add_routes(routes)
web.run_app(app, port=8888)
```

The application will automatically register with Spring Boot Admin upon start up.

Log in to the Spring Boot Admin UI at `http://localhost:8080` to interact with the application.

### Registration Notes
When registering a service in Spring Boot Admin, note that:
* **Docker** - If the Spring Boot Admin is running in a container while the managed service is running in the docker-host directly, the `app_url` and `pyctuator_endpoint_url` should use `host.docker.internal` as the url's host so Spring Boot Admin will be able to connect to the monitored service.
* **Http Traces** - In order for the "Http Traces" tab to be able to hide requests sent by Spring Boot Admin to the Pyctuator endpoint, `pyctuator_endpoint_url` must be using the same host and port as `app_url`.
* **HTTPS** - If Pyctuator is to be registered with Spring Boot Admin using HTTPS and the default SSL context is inappropriate, you can provide your own `ssl.SSLContext` using the `ssl_context` optional parameter of the `Pyctuator` constructor.
* **Insecure HTTPS** - If Spring Boot Admin is using HTTPS with self-signed certificate, set the `PYCTUATOR_REGISTRATION_NO_CERT` environment variable so Pyctuator will disable certificate validation when registering (and deregistering).

## Advanced Configuration
The following sections are intended for advanced users who want to configure advanced Pyctuator features.

### Application Info
While Pyctuator only needs to know the application's name, we recommend that applications monitored by Spring 
Boot Admin will show additional build and git details. 
This becomes handy when scaling out a service to multiple instances by showing the version of each instance.
To do so, you can provide additional build and git info using methods of the Pyctuator object:

```python
pyctuator = Pyctuator(...)  # arguments removed for brevity

pyctuator.set_build_info(
    name="app",
    version="1.3.1",
    time=datetime.fromisoformat("2019-12-21T10:09:54.876091"),
)

pyctuator.set_git_info(
    commit="7d4fef3",
    time=datetime.fromisoformat("2019-12-24T14:18:32.123432"),
    branch="origin/master",
)
```

Once you configure build and git info, you should see them in the Details tab of Spring Boot Admin:

![Detailed Build Info](examples/images/Main_Details_BuildInfo.png)

### Additional Application Info
In addition to adding build and git info, Pyctuator allows adding arbitrary application details to the "Info" section in SBA.

This is done by initializing the `additional_app_info` parameter with an arbitrary dictionary.
For example, you can provide links to your application's metrics:
```python
Pyctuator(
  app,
  "Flask Pyctuator",
  app_url=f"http://172.18.0.1:5000",
  pyctuator_endpoint_url=f"http://172.18.0.1:5000/pyctuator",
  registration_url=f"http://localhost:8080/instances",
  app_description="Demonstrate Spring Boot Admin Integration with Flask",
  additional_app_info=dict(
    serviceLinks=dict(
      metrics="http://xyz/service/metrics"
    ),
    podLinks=dict(
      metrics=["http://xyz/pod/metrics/memory", "http://xyz/pod/metrics/cpu"]
    )
  )
)
```

This will result with the following Info page in SBA:
![img.png](examples/images/Additional_App_Info.png)

### DB Health
For services that use SQL database via SQLAlchemy, Pyctuator can easily monitor and expose the connection's health 
using the DbHealthProvider class as demonstrated below:

```python
engine = create_engine("mysql+pymysql://root:root@localhost:3306")
pyctuator = Pyctuator(...)  # arguments removed for brevity
pyctuator.register_health_provider(DbHealthProvider(engine))
```

Once you configure the health provider, you should see DB health info in the Details tab of Spring Boot Admin:

![DB Health](examples/images/Main_DB_Health.png)

### Redis health
If your service is using Redis, Pyctuator can monitor the connection to Redis by simply initializing a `RedisHealthProvider`:

```python
r = redis.Redis()
pyctuator = Pyctuator(...)  # arguments removed for brevity
pyctuator.register_health_provider(RedisHealthProvider(r))
```

### Custom Environment
Out of the box, Pyctuator exposes Python's environment variables to Spring Boot Admin.

In addition, an application may register an environment provider to provide additional configuration that should be exposed via Spring Boot Admin. 

When the environment provider is called it should return a dictionary describing the environment. The returned dictionary is exposed to Spring Boot Admin.

Since Spring Boot Admin doesn't support hierarchical environment (only a flat key/value mapping), the provided environment is flattened as dot-delimited keys.

Pyctuator tries to hide secrets from being exposed to Spring Boot Admin by replacing the values of "suspicious" keys with ***.

Suspicious keys are keys that contain the words "secret", "password" and some forms of "key".

For example, if an application's configuration looks like this:

```python
config = {
    "a": "s1",
    "b": {
        "secret": "ha ha",
        "c": 625,
    },
    "d": {
        "e": True,
        "f": "hello",
        "g": {
            "h": 123,
            "i": "abcde"
        }
    }
}
```

An environment provider can be registered like so:

```python
pyctuator.register_environment_provider("config", lambda: config)
```

### Filesystem and Memory Metrics
Pyctuator can provide filesystem and memory metrics.

To enable these metrics, install [psutil](https://github.com/giampaolo/psutil)

Note that the `psutil` dependency is **optional** and is only required if you want to enable filesystem and memory monitoring.

### Loggers
Pyctuator leverages Python's builtin `logging` framework and allows controlling log levels at runtime.
 
Note that in order to control uvicorn's log level, you need to provide a logger object when instantiating it. For example:
```python
myFastAPIServer = Server(
    config=Config(
        logger=logging.getLogger("uvi"), 
        app=app, 
        loop="asyncio"
    )
)
```

### Spring Boot Admin Using Basic Authentication
Pyctuator supports registration with Spring Boot Admin that requires basic authentications. The credentials are provided when initializing the Pyctuator instance as follows:
```python
# NOTE: Never include secrets in your code !!!
auth = BasicAuth(os.getenv("sba-username"), os.getenv("sba-password"))

Pyctuator(
    app,
    "Flask Pyctuator",
    app_url="http://localhost:5000",
    pyctuator_endpoint_url=f"http://localhost:5000/pyctuator",
    registration_url=f"http://spring-boot-admin:8080/instances",
    registration_auth=auth,
)
``` 

### Protecting Pyctuator with authentication
Since there are numerous standard approaches to protect an API, Pyctuator doesn't explicitly support any of them. Instead, Pyctuator allows to customize its integration with the web-framework.
See the example in [fastapi_with_authentication_example_app.py](examples/FastAPI/fastapi_with_authentication_example_app.py).

## Full blown examples
The `examples` folder contains full blown Python projects that are built using [Poetry](https://python-poetry.org/).

To run these examples, you'll need to have Spring Boot Admin running in a local docker container. A Spring Boot Admin Docker image is available [here](https://hub.docker.com/r/michayaak/spring-boot-admin).

Unless the example includes a docker-compose file, you'll need to start Spring Boot Admin using docker directly:
```sh
docker run --rm -p 8080:8080 --add-host=host.docker.internal:host-gateway michayaak/spring-boot-admin:2.2.3-1
```
(the docker image's tag represents the version of Spring Boot Admin, so if you need to use version `2.0.0`, use `michayaak/spring-boot-admin:2.0.0` instead, note it accepts connections on port 8082).

The examples include
* [FastAPI Example](examples/FastAPI/README.md) - demonstrates integrating Pyctuator with the FastAPI web framework.
* [Flask Example](examples/Flask/README.md) - demonstrates integrating Pyctuator with the Flask web framework.
* [Advanced Example](examples/Advanced/README.md) - demonstrates configuring and using all the advanced features of Pyctuator.

## Contributing
To set up a development environment, make sure you have Python 3.9 or newer installed, and run `make bootstrap`.

Use `make check` to run static analysis tools.

Use `make test` to run tests.


%package help
Summary:	Development documents and examples for pyctuator
Provides:	python3-pyctuator-doc
%description help
[![PyPI](https://img.shields.io/pypi/v/pyctuator?color=green&style=plastic)](https://pypi.org/project/pyctuator/)
[![build](https://github.com/SolarEdgeTech/pyctuator/workflows/build/badge.svg)](https://github.com/SolarEdgeTech/pyctuator/)
[![Codecov](https://img.shields.io/codecov/c/github/SolarEdgeTech/pyctuator?style=plastic)](https://codecov.io/gh/SolarEdgeTech/pyctuator)

# Pyctuator

Monitor Python web apps using 
[Spring Boot Admin](https://github.com/codecentric/spring-boot-admin). 

Pyctuator supports **[Flask](https://palletsprojects.com/p/flask/)**, **[FastAPI](https://fastapi.tiangolo.com/)**, **[aiohttp](https://docs.aiohttp.org/)** and **[Tornado](https://www.tornadoweb.org/)**. **Django** support is planned as well.

The following video shows a FastAPI web app being monitored and controled using Spring Boot Admin.
 
![Pyctuator Example](examples/images/Pyctuator_Screencast.gif)

The complete example can be found in [Advanced example](examples/Advanced/README.md).

## Requirements
Python 3.9+

Pyctuator has zero hard dependencies.

## Installing
Install Pyctuator using pip: `pip3 install pyctuator`

## Why?
Many Java shops use Spring Boot as their main web framework for developing
microservices. 
These organizations often use Spring Actuator together with Spring Boot Admin
to monitor their microservices' status, gain access to applications'
 state and configuration, manipulate log levels, etc.
 
While Spring Boot is suitable for many use-cases, it is very common for organizations 
to also have a couple of Python microservices, as Python is often more suitable for 
some types of applications. The most common examples are Data Science and Machine Learning
applications.

Setting up a proper monitoring tool for these microservices is a complex task, and might
not be justified for just a few Python microservices in a sea of Java microservices.

This is where Pyctuator comes in. It allows you to easily integrate your Python
microservices into your existing Spring Boot Admin deployment.

## Main Features
Pyctuator is a partial Python implementation of the 
[Spring Actuator API](https://docs.spring.io/spring-boot/docs/2.1.8.RELEASE/actuator-api/html/)  . 

It currently supports the following Actuator features:

* **Application details**
* **Metrics**
    * Memory usage
    * Disk usage 
    * Custom metrics
* **Health monitors**
    * Built in MySQL health monitor
    * Built in Redis health monitor
    * Custom health monitors
* **Environment**
* **Loggers** - Easily change log levels during runtime
* **Log file** - Tail the application's log file
* **Thread dump** - See which threads are running
* **HTTP traces** - Tail recent HTTP requests, including status codes and latency

## Quickstart
The examples below show a minimal integration of **FastAPI**, **Flask** and **aiohttp** applications with **Pyctuator**.

After installing Flask/FastAPI/aiohttp and Pyctuator, start by launching a local Spring Boot Admin instance:

```sh
docker run --rm -p 8080:8080 --add-host=host.docker.internal:host-gateway michayaak/spring-boot-admin:2.2.3-1
```

Then go to `http://localhost:8080` to get to the web UI.

### Flask
The following example is complete and should run as is.

```python
from flask import Flask
from pyctuator.pyctuator import Pyctuator

app_name = "Flask App with Pyctuator"
app = Flask(app_name)


@app.route("/")
def hello():
    return "Hello World!"


Pyctuator(
    app,
    app_name,
    app_url="http://host.docker.internal:5000",
    pyctuator_endpoint_url="http://host.docker.internal:5000/pyctuator",
    registration_url="http://localhost:8080/instances"
)

app.run(debug=False, port=5000)
```

The application will automatically register with Spring Boot Admin upon start up.

Log in to the Spring Boot Admin UI at `http://localhost:8080` to interact with the application. 

### FastAPI
The following example is complete and should run as is.

```python
from fastapi import FastAPI
from uvicorn import Server

from uvicorn.config import Config
from pyctuator.pyctuator import Pyctuator


app_name = "FastAPI App with Pyctuator"
app = FastAPI(title=app_name)


@app.get("/")
def hello():
    return "Hello World!"


Pyctuator(
    app,
    "FastAPI Pyctuator",
    app_url="http://host.docker.internal:8000",
    pyctuator_endpoint_url="http://host.docker.internal:8000/pyctuator",
    registration_url="http://localhost:8080/instances"
)

Server(config=(Config(app=app, loop="asyncio"))).run()
```

The application will automatically register with Spring Boot Admin upon start up.

Log in to the Spring Boot Admin UI at `http://localhost:8080` to interact with the application. 

### aiohttp
The following example is complete and should run as is.

```python
from aiohttp import web
from pyctuator.pyctuator import Pyctuator

app = web.Application()
routes = web.RouteTableDef()

@routes.get("/")
def hello():
    return web.Response(text="Hello World!")

Pyctuator(
    app,
    "aiohttp Pyctuator",
    app_url="http://host.docker.internal:8888",
    pyctuator_endpoint_url="http://host.docker.internal:8888/pyctuator",
    registration_url="http://localhost:8080/instances"
)

app.add_routes(routes)
web.run_app(app, port=8888)
```

The application will automatically register with Spring Boot Admin upon start up.

Log in to the Spring Boot Admin UI at `http://localhost:8080` to interact with the application.

### Registration Notes
When registering a service in Spring Boot Admin, note that:
* **Docker** - If the Spring Boot Admin is running in a container while the managed service is running in the docker-host directly, the `app_url` and `pyctuator_endpoint_url` should use `host.docker.internal` as the url's host so Spring Boot Admin will be able to connect to the monitored service.
* **Http Traces** - In order for the "Http Traces" tab to be able to hide requests sent by Spring Boot Admin to the Pyctuator endpoint, `pyctuator_endpoint_url` must be using the same host and port as `app_url`.
* **HTTPS** - If Pyctuator is to be registered with Spring Boot Admin using HTTPS and the default SSL context is inappropriate, you can provide your own `ssl.SSLContext` using the `ssl_context` optional parameter of the `Pyctuator` constructor.
* **Insecure HTTPS** - If Spring Boot Admin is using HTTPS with self-signed certificate, set the `PYCTUATOR_REGISTRATION_NO_CERT` environment variable so Pyctuator will disable certificate validation when registering (and deregistering).

## Advanced Configuration
The following sections are intended for advanced users who want to configure advanced Pyctuator features.

### Application Info
While Pyctuator only needs to know the application's name, we recommend that applications monitored by Spring 
Boot Admin will show additional build and git details. 
This becomes handy when scaling out a service to multiple instances by showing the version of each instance.
To do so, you can provide additional build and git info using methods of the Pyctuator object:

```python
pyctuator = Pyctuator(...)  # arguments removed for brevity

pyctuator.set_build_info(
    name="app",
    version="1.3.1",
    time=datetime.fromisoformat("2019-12-21T10:09:54.876091"),
)

pyctuator.set_git_info(
    commit="7d4fef3",
    time=datetime.fromisoformat("2019-12-24T14:18:32.123432"),
    branch="origin/master",
)
```

Once you configure build and git info, you should see them in the Details tab of Spring Boot Admin:

![Detailed Build Info](examples/images/Main_Details_BuildInfo.png)

### Additional Application Info
In addition to adding build and git info, Pyctuator allows adding arbitrary application details to the "Info" section in SBA.

This is done by initializing the `additional_app_info` parameter with an arbitrary dictionary.
For example, you can provide links to your application's metrics:
```python
Pyctuator(
  app,
  "Flask Pyctuator",
  app_url=f"http://172.18.0.1:5000",
  pyctuator_endpoint_url=f"http://172.18.0.1:5000/pyctuator",
  registration_url=f"http://localhost:8080/instances",
  app_description="Demonstrate Spring Boot Admin Integration with Flask",
  additional_app_info=dict(
    serviceLinks=dict(
      metrics="http://xyz/service/metrics"
    ),
    podLinks=dict(
      metrics=["http://xyz/pod/metrics/memory", "http://xyz/pod/metrics/cpu"]
    )
  )
)
```

This will result with the following Info page in SBA:
![img.png](examples/images/Additional_App_Info.png)

### DB Health
For services that use SQL database via SQLAlchemy, Pyctuator can easily monitor and expose the connection's health 
using the DbHealthProvider class as demonstrated below:

```python
engine = create_engine("mysql+pymysql://root:root@localhost:3306")
pyctuator = Pyctuator(...)  # arguments removed for brevity
pyctuator.register_health_provider(DbHealthProvider(engine))
```

Once you configure the health provider, you should see DB health info in the Details tab of Spring Boot Admin:

![DB Health](examples/images/Main_DB_Health.png)

### Redis health
If your service is using Redis, Pyctuator can monitor the connection to Redis by simply initializing a `RedisHealthProvider`:

```python
r = redis.Redis()
pyctuator = Pyctuator(...)  # arguments removed for brevity
pyctuator.register_health_provider(RedisHealthProvider(r))
```

### Custom Environment
Out of the box, Pyctuator exposes Python's environment variables to Spring Boot Admin.

In addition, an application may register an environment provider to provide additional configuration that should be exposed via Spring Boot Admin. 

When the environment provider is called it should return a dictionary describing the environment. The returned dictionary is exposed to Spring Boot Admin.

Since Spring Boot Admin doesn't support hierarchical environment (only a flat key/value mapping), the provided environment is flattened as dot-delimited keys.

Pyctuator tries to hide secrets from being exposed to Spring Boot Admin by replacing the values of "suspicious" keys with ***.

Suspicious keys are keys that contain the words "secret", "password" and some forms of "key".

For example, if an application's configuration looks like this:

```python
config = {
    "a": "s1",
    "b": {
        "secret": "ha ha",
        "c": 625,
    },
    "d": {
        "e": True,
        "f": "hello",
        "g": {
            "h": 123,
            "i": "abcde"
        }
    }
}
```

An environment provider can be registered like so:

```python
pyctuator.register_environment_provider("config", lambda: config)
```

### Filesystem and Memory Metrics
Pyctuator can provide filesystem and memory metrics.

To enable these metrics, install [psutil](https://github.com/giampaolo/psutil)

Note that the `psutil` dependency is **optional** and is only required if you want to enable filesystem and memory monitoring.

### Loggers
Pyctuator leverages Python's builtin `logging` framework and allows controlling log levels at runtime.
 
Note that in order to control uvicorn's log level, you need to provide a logger object when instantiating it. For example:
```python
myFastAPIServer = Server(
    config=Config(
        logger=logging.getLogger("uvi"), 
        app=app, 
        loop="asyncio"
    )
)
```

### Spring Boot Admin Using Basic Authentication
Pyctuator supports registration with Spring Boot Admin that requires basic authentications. The credentials are provided when initializing the Pyctuator instance as follows:
```python
# NOTE: Never include secrets in your code !!!
auth = BasicAuth(os.getenv("sba-username"), os.getenv("sba-password"))

Pyctuator(
    app,
    "Flask Pyctuator",
    app_url="http://localhost:5000",
    pyctuator_endpoint_url=f"http://localhost:5000/pyctuator",
    registration_url=f"http://spring-boot-admin:8080/instances",
    registration_auth=auth,
)
``` 

### Protecting Pyctuator with authentication
Since there are numerous standard approaches to protect an API, Pyctuator doesn't explicitly support any of them. Instead, Pyctuator allows to customize its integration with the web-framework.
See the example in [fastapi_with_authentication_example_app.py](examples/FastAPI/fastapi_with_authentication_example_app.py).

## Full blown examples
The `examples` folder contains full blown Python projects that are built using [Poetry](https://python-poetry.org/).

To run these examples, you'll need to have Spring Boot Admin running in a local docker container. A Spring Boot Admin Docker image is available [here](https://hub.docker.com/r/michayaak/spring-boot-admin).

Unless the example includes a docker-compose file, you'll need to start Spring Boot Admin using docker directly:
```sh
docker run --rm -p 8080:8080 --add-host=host.docker.internal:host-gateway michayaak/spring-boot-admin:2.2.3-1
```
(the docker image's tag represents the version of Spring Boot Admin, so if you need to use version `2.0.0`, use `michayaak/spring-boot-admin:2.0.0` instead, note it accepts connections on port 8082).

The examples include
* [FastAPI Example](examples/FastAPI/README.md) - demonstrates integrating Pyctuator with the FastAPI web framework.
* [Flask Example](examples/Flask/README.md) - demonstrates integrating Pyctuator with the Flask web framework.
* [Advanced Example](examples/Advanced/README.md) - demonstrates configuring and using all the advanced features of Pyctuator.

## Contributing
To set up a development environment, make sure you have Python 3.9 or newer installed, and run `make bootstrap`.

Use `make check` to run static analysis tools.

Use `make test` to run tests.


%prep
%autosetup -n pyctuator-1.0.2

%build
%py3_build

%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
	find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
	find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
	find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
	find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
	find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .

%files -n python3-pyctuator -f filelist.lst
%dir %{python3_sitelib}/*

%files help -f doclist.lst
%{_docdir}/*

%changelog
* Fri May 05 2023 Python_Bot <Python_Bot@openeuler.org> - 1.0.2-1
- Package Spec generated