Skip to content

Commit d01d07e

Browse files
SalimKayalolevski
andauthored
feat: add liveness-detector (#1920)
Co-authored-by: Tasko Olevski <[email protected]>
1 parent 1c9204b commit d01d07e

File tree

12 files changed

+2587
-0
lines changed

12 files changed

+2587
-0
lines changed

.github/workflows/ci.yml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,22 @@ jobs:
3838
cd git-https-proxy
3939
go test -v
4040
41+
test-liveness-detector:
42+
runs-on: ubuntu-latest
43+
steps:
44+
- uses: actions/checkout@v4
45+
- name: Install Pixi
46+
uses: prefix-dev/[email protected]
47+
with:
48+
pixi-version: v0.24.2
49+
manifest-path: ./liveness-detector/pyproject.toml
50+
cache: true
51+
- name: Test liveness detector
52+
run: |
53+
cd liveness-detector
54+
pixi run lint-and-fix
55+
pixi run test
56+
4157
test-git-services:
4258
runs-on: ubuntu-latest
4359
steps:

liveness-detector/Dockerfile

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# SPDX-FileCopyrightText: 2024 Idiap Research Institute <[email protected]>
2+
# SPDX-FileContributor: Salim Kayal <[email protected]>
3+
#
4+
# SPDX-License-Identifier: Apache-2.0
5+
6+
FROM ghcr.io/prefix-dev/pixi:0.24.2-bookworm-slim AS build
7+
8+
COPY pixi.lock /app/pixi.lock
9+
COPY pyproject.toml /app/pyproject.toml
10+
COPY liveness_detector /app/liveness_detector
11+
WORKDIR /app
12+
13+
RUN pixi install -e default
14+
15+
RUN <<EOF
16+
echo '#!/bin/bash' > /shell-hook.sh
17+
echo 'export PATH=/app/.pixi/envs/default/bin:${PATH}' >> /shell-hook.sh
18+
echo 'exec "$@"' >> /shell-hook.sh
19+
EOF
20+
21+
FROM docker.io/debian:bookworm-slim AS production
22+
23+
COPY --from=build /app/.pixi/envs/default /app/.pixi/envs/default
24+
COPY --from=build /app/liveness_detector /app/liveness_detector
25+
COPY --chmod=755 --from=build /shell-hook.sh /shell-hook.sh
26+
COPY --chmod=755 scripts/ /
27+
WORKDIR /app
28+
EXPOSE 8888
29+
30+
ENTRYPOINT ["/shell-hook.sh"]
31+
32+
CMD ["uvicorn", "liveness_detector:app", "--port", 8888]
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
Apache License
2+
Version 2.0, January 2004
3+
http://www.apache.org/licenses/
4+
5+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6+
7+
1. Definitions.
8+
9+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10+
11+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12+
13+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14+
15+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16+
17+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18+
19+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20+
21+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22+
23+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24+
25+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26+
27+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28+
29+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30+
31+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32+
33+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34+
35+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36+
37+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38+
39+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40+
41+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42+
43+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44+
45+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46+
47+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48+
49+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50+
51+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52+
53+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54+
55+
END OF TERMS AND CONDITIONS
56+
57+
APPENDIX: How to apply the Apache License to your work.
58+
59+
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60+
61+
Copyright [yyyy] [name of copyright owner]
62+
63+
Licensed under the Apache License, Version 2.0 (the "License");
64+
you may not use this file except in compliance with the License.
65+
You may obtain a copy of the License at
66+
67+
http://www.apache.org/licenses/LICENSE-2.0
68+
69+
Unless required by applicable law or agreed to in writing, software
70+
distributed under the License is distributed on an "AS IS" BASIS,
71+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72+
See the License for the specific language governing permissions and
73+
limitations under the License.

liveness-detector/README.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
<!--
2+
SPDX-FileCopyrightText: 2024 Idiap Research Institute <[email protected]>
3+
SPDX-FileContributor: Salim Kayal <[email protected]>
4+
5+
SPDX-License-Identifier: Apache-2.0
6+
-->
7+
8+
# liveness-detector
9+
10+
This module provides an endpoint to check whether the user is actively using his pod or not
11+
12+
## Installation
13+
14+
In order to kickstart the project ensure [pixi is installed](https://pixi.sh/latest/#installation) as we will be using it for environment and packaging management. Then to install the base dependencies and jupyter kernel for this environment run
15+
16+
```bash
17+
$ pixi install
18+
```
19+
20+
## Testing
21+
22+
running the tests can be achieved by running the following command
23+
24+
```bash
25+
$ pixi run test
26+
```
27+
28+
## Running the server
29+
30+
### shell
31+
32+
Ensure the `PROJECT_SOURCE` environment variable is set then run
33+
34+
```bash
35+
$ pixi run uvicorn liveness_detector:app --port 8888
36+
```
37+
38+
### Docker
39+
40+
build the image with
41+
42+
```bash
43+
$ docker build --target=production --tag=${YOUR_TAG}
44+
```
45+
46+
run it with
47+
48+
```bash
49+
$ docker run -it --rm -v ${YOUR_LOCAL_PROJECT_PATH}:/project:Z -e PROJECT_SOURCE=/project -p 8888:8888
50+
${YOUR_TAG}
51+
```
52+
Connect to it with
53+
54+
```bash
55+
$ curl -sSL 127.0.0.1:8888/healthz
56+
```
57+
58+
### As an init container
59+
60+
mount the `/renku-liveness` folder in the init container and the environment container and run the
61+
`/entrypoint-init-container.sh` script
62+
63+
then from the environment container, run the `/renku-liveness/entrypoint-hook.sh` with the 8888
64+
port forwarded.
65+
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# SPDX-FileCopyrightText: 2024 Idiap Research Institute <[email protected]>
2+
# SPDX-FileContributor: Salim Kayal <[email protected]>
3+
#
4+
# SPDX-License-Identifier: Apache-2.0
5+
6+
import asyncio
7+
8+
from collections.abc import AsyncGenerator
9+
from contextlib import asynccontextmanager
10+
from os import environ, getloadavg
11+
from pathlib import Path
12+
13+
from fastapi import FastAPI
14+
from pydantic import BaseModel
15+
16+
from liveness_detector.activity_watcher import ActivityWatcher
17+
18+
19+
class HealthzResponse(BaseModel):
20+
"""
21+
Represent a health check response containing system and activity information.
22+
23+
This model is used to structure the response for health check endpoints. It
24+
provides details about the current system load average (`load_average`), timestamp
25+
of the last file system activity within a monitored directory (`last_file_activity`),
26+
and timestamp of the last pseudo-terminal activity (`last_tty_activity`).
27+
"""
28+
29+
load_average: float
30+
last_file_activity: int
31+
last_tty_activity: int
32+
33+
34+
watcher = ActivityWatcher(Path(environ["PROJECT_SOURCE"]))
35+
36+
37+
@asynccontextmanager
38+
async def manage_monitoring(app: FastAPI) -> AsyncGenerator[None, None]:
39+
"""Manage the monitoring of the last user activity."""
40+
task = asyncio.create_task(watcher.run_inotify())
41+
yield
42+
task.cancel()
43+
44+
45+
app = FastAPI(lifespan=manage_monitoring)
46+
47+
48+
@app.get("/healthz", response_model=HealthzResponse)
49+
async def is_container_idle() -> HealthzResponse:
50+
"""
51+
Check container idleness in the background and returns the status.
52+
53+
Returns
54+
-------
55+
JSON response with last activity timestamp.
56+
"""
57+
58+
return HealthzResponse(
59+
load_average=getloadavg()[0],
60+
last_tty_activity=watcher.last_tty_activity,
61+
last_file_activity=watcher.last_file_activity,
62+
)
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# SPDX-FileCopyrightText: 2024 Idiap Research Institute <[email protected]>
2+
# SPDX-FileContributor: Salim Kayal <[email protected]>
3+
#
4+
# SPDX-License-Identifier: Apache-2.0
5+
6+
7+
from pathlib import Path
8+
from time import time
9+
10+
from asyncinotify import Inotify, Mask
11+
12+
13+
class ActivityWatcher:
14+
"""
15+
A class to monitor activity within a directory and surrounding pseudo-terminals.
16+
17+
This class utilizes inotify to track file system events (create, delete, modify)
18+
within the workspace directory and additionally monitors access events on pseudo-terminals
19+
at `/dev/pts`. It maintains the last observed activity timestamp and provides methods
20+
to add or remove watch descriptors. The class also offers an asynchronous `run` method
21+
to continuously monitor activity and update the last activity timestamp.
22+
23+
Attributes
24+
----------
25+
last_activity (float): Timestamp of the last observed activity.
26+
workdir (str): The directory to monitor for file system events.
27+
"""
28+
29+
_DIRECTORY_CREATED = Mask.CREATE | Mask.ISDIR
30+
_DIRECTORY_DELETED = Mask.DELETE | Mask.ISDIR
31+
32+
def __init__(self, workdir: Path):
33+
"""
34+
Initialize the ActivityWatcher object.
35+
36+
Args:
37+
workdir (str): The directory to monitor for file system events.
38+
"""
39+
self._last_tty_activity = time()
40+
self._last_file_activity = time()
41+
self.workdir = workdir
42+
43+
@property
44+
def last_file_activity(self) -> int:
45+
return int(self._last_file_activity)
46+
47+
@property
48+
def last_tty_activity(self) -> int:
49+
return int(self._last_tty_activity)
50+
51+
async def run_inotify(self) -> None:
52+
"""
53+
Continuously monitors activity within the specified directory and pseudo-terminals.
54+
55+
This asynchronous method utilizes inotify to monitor the configured directory and
56+
pseudo-terminals. It continuously reads events and updates the `_last_activity`
57+
timestamp. The method also handles directory creation and deletion events by
58+
adding or removing watch descriptors accordingly.
59+
60+
This method should be called as an awaitable coroutine.
61+
"""
62+
with Inotify() as inotify:
63+
workdir_mask = Mask.MODIFY | Mask.CREATE | Mask.DELETE
64+
65+
inotify.add_watch(Path("/dev/pts"), Mask.ACCESS)
66+
inotify.add_watch(self.workdir, workdir_mask)
67+
for path_to_monitor, _, _ in self.workdir.walk():
68+
if path_to_monitor.is_dir():
69+
inotify.add_watch(path_to_monitor, workdir_mask)
70+
71+
async for event in inotify:
72+
if event.mask & Mask.ACCESS == Mask.ACCESS:
73+
self._last_tty_activity = time()
74+
else:
75+
self._last_file_activity = time()
76+
if event.mask & self._DIRECTORY_CREATED == self._DIRECTORY_CREATED:
77+
inotify.add_watch(event.watch.path / event.name, workdir_mask)
78+
elif event.mask & self._DIRECTORY_DELETED == self._DIRECTORY_DELETED:
79+
inotify.rm_watch(event.watch)

0 commit comments

Comments
 (0)