move existing stuff to archive dir (for now)

This commit is contained in:
Alex Tau 2025-04-27 20:39:07 +03:00
parent ae1204449c
commit 4fc491f61a
32 changed files with 0 additions and 0 deletions

3
archive-arch/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
.venv
__pycache__
alerting/credentials.json

661
archive-arch/LICENSE Normal file
View file

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 2024 Alex Tau
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

34
archive-arch/README.md Normal file
View file

@ -0,0 +1,34 @@
# lego-monitoring
DISCLAIMER: This repository does not have anything to do with the LEGO Group. "lego" is the internal name of my home server.
## Prerequisites
* `pacman -S libolm arch-audit`
* `pip -r requirements.txt`
## Configuring
* Invite the bot account to the room (you have to accept the invite manually)
* Copy `config.example.json` to `config.json`, edit as necessary
* Run `alerting/login.py` once to login into Matrix
* (optional) Create an `alerting` group and give `config.json`'s ownership and read rights to it, to allow sending alerts from less-privileged users
### Setting up login alerts
* Copy `lego-login-alert` to your `/etc/sudoers.d`
* Add this to your `/etc/ssh/sshd_config`:
```
# login alerts
ForceCommand /opt/lego-monitoring/wrappers/login_wrapper.sh
```
## Running
* `prettyprint.py` -- check and print all sensors
* `service.py` -- launch service
* `assets/lego-monitoring.service` is a systemd unit that starts `service.py`
### Disabling checks
Put names of checks into config's `disabled_checks` to disable them. See `service.py` for check names.

View file

@ -0,0 +1,73 @@
from dataclasses import dataclass
from typing import Optional
import nio
from alerting.enum import AlertType, Severity
from misc import cvars
from misc.config import get_config
@dataclass
class Alert:
alert_type: AlertType
message: str
severity: Severity
html_message: Optional[str] = None
async def get_client() -> nio.AsyncClient:
"""
Returns a Matrix client.
It is better to call get_client once and use it for multiple send_alert calls
"""
matrix_cfg = cvars.config.get().matrix
client = nio.AsyncClient(matrix_cfg.homeserver)
client.access_token = matrix_cfg.access_token
client.user_id = matrix_cfg.user_id
client.device_id = matrix_cfg.device_id
return client
def format_message(alert: Alert) -> str:
match alert.severity:
case Severity.INFO:
severity_emoji = ""
case Severity.WARNING:
severity_emoji = "⚠️"
case Severity.CRITICAL:
severity_emoji = "🆘"
message = f"{severity_emoji} {alert.alert_type} Alert\n{alert.message}"
if alert.html_message:
html_message = f"{severity_emoji} {alert.alert_type} Alert<br>{alert.html_message}"
return message, html_message
else:
return message, None
async def send_alert(alert: Alert) -> None:
try:
client = cvars.matrix_client.get()
except LookupError: # being called standalone
cvars.config.set(get_config())
temp_client = True
client = await get_client()
cvars.matrix_client.set(client)
else:
temp_client = False
room_id = cvars.config.get().matrix.room_id
message, html_message = format_message(alert)
content = {
"msgtype": "m.text",
"body": message,
}
if html_message:
content["format"] = "org.matrix.custom.html"
content["formatted_body"] = html_message
await client.room_send(
room_id=room_id,
message_type="m.room.message",
content=content,
)
if temp_client:
await client.close()

View file

@ -0,0 +1,53 @@
import asyncio
import json
import logging
import os
import signal
import tempfile
from dataclasses import asdict
from alerting.alerts import Alert, send_alert
from misc.common import TMP_DIR
handler_lock = asyncio.Lock()
async def handler():
"""
Is executed when SIGUSR1 is received.
Checks for new alerts, sends them in 10 seconds
"""
alert_counts: list[list] = []
async with handler_lock:
await asyncio.sleep(10)
alert_files = [f for f in os.listdir(str(TMP_DIR)) if f.startswith("alert-")]
for fname in alert_files:
fpath = str(TMP_DIR / fname)
with open(fpath) as f:
alert = Alert(**json.load(f))
for pair in alert_counts:
if alert == pair[0]:
pair[1] += 1
break
else:
alert_counts.append([alert, 1])
os.unlink(fpath)
for pair in alert_counts:
if pair[1] > 1:
pair[0].message += f" ({pair[1]} times)"
pair[0].html_message += f" ({pair[1]} times)"
logging.info(f"Sending delayed alert of type {pair[0].alert_type}")
await send_alert(pair[0])
def send_alert_delayed(alert: Alert) -> None:
"""
Put alert into a temporary file to be sent later.
Intended as an IPC mechanism
"""
alert_json = json.dumps(asdict(alert))
with tempfile.NamedTemporaryFile(prefix="alert-", dir=str(TMP_DIR), delete=False) as af:
af.write(alert_json.encode())
with open(str(TMP_DIR / "pid")) as pf:
pid = int(pf.read().strip())
os.kill(pid, signal.SIGUSR1)

View file

@ -0,0 +1,22 @@
from enum import StrEnum
class AlertType(StrEnum):
TEST = "TEST"
ERROR = "ERROR"
RAM = "RAM"
CPU = "CPU"
TEMP = "TEMP"
VULN = "VULN"
LOGIN = "LOGIN"
SMART = "SMART" # TODO
RAID = "RAID"
DISKS = "DISKS"
UPS = "UPS"
UPDATE = "UPDATE"
class Severity(StrEnum):
INFO = "INFO"
WARNING = "WARNING"
CRITICAL = "CRITICAL"

46
archive-arch/alerting/login.py Executable file
View file

@ -0,0 +1,46 @@
#!/usr/bin/env python3
import getpass
import json
import os
from nio import AsyncClient, LoginResponse
from misc.common import CONFIG_FILE
async def main() -> None:
try:
with open(CONFIG_FILE) as f:
cfg = json.load(f)
if "matrix" in cfg:
print(f"Creds already configured in {CONFIG_FILE}")
raise SystemExit
cfg["matrix"] = {}
except (FileNotFoundError, json.JSONDecodeError):
open(CONFIG_FILE, "w").close()
os.chmod(CONFIG_FILE, 0o600)
cfg = {"matrix": {}}
homeserver = input("Homeserver: ")
user_id = input("User ID: ")
device_name = input("Device name: ")
room_id = input("Room ID: ")
password = getpass.getpass()
client = AsyncClient(homeserver, user_id)
resp = await client.login(password, device_name=device_name)
await client.close()
if isinstance(resp, LoginResponse):
cfg["matrix"]["homeserver"] = homeserver
cfg["matrix"]["user_id"] = resp.user_id
cfg["matrix"]["device_id"] = resp.device_id
cfg["matrix"]["access_token"] = resp.access_token
cfg["matrix"]["room_id"] = room_id
with open(CONFIG_FILE, "w") as f:
json.dump(cfg, f, indent=2)
print(f"Logged in as {resp.user_id}. Credentials saved to {CONFIG_FILE}")
else:
raise Exception(f"Failed to log in: {resp}")

View file

@ -0,0 +1,3 @@
Defaults env_keep += "SSH_CLIENT"
ALL ALL=(ALL:ALL) NOPASSWD:SETENV: /opt/lego-monitoring/wrappers/send_login_alert.sh
ALL ALL=(ALL:ALL) NOPASSWD:SETENV: /opt/lego-monitoring/wrappers/send_local_login_alert.sh

View file

@ -0,0 +1,11 @@
[Unit]
After=docker.service
[Service]
ExecStart=/opt/lego-monitoring/.venv/bin/python /opt/lego-monitoring/service.py
Type=exec
Restart=always
RestartSec=5s
[Install]
WantedBy=multi-user.target

View file

@ -0,0 +1,33 @@
{
"checks": {
"docker_registry": {
"hub_url": "https://hub.docker.com/",
"images": [
"gitlab/gitlab-ce"
]
},
"raid": {
"lvs": [
"Data/lvol0"
]
},
"wearout": {
"disks": [
{
"name": "/dev/sda",
"severity": "WARNING"
},
{
"name": "/dev/nvme0",
"severity": "CRITICAL"
}
]
},
"login": {
"hostname": "example.com"
}
},
"disabled_checks": [
"nonexistent_check"
]
}

View file

@ -0,0 +1,53 @@
import asyncio
import datetime
import logging
from typing import Callable, Coroutine
from alerting import alerts
async def _call_check(check: Callable | Coroutine, *args, **kwargs) -> list[alerts.Alert]:
if isinstance(check, Callable):
result = check(*args, **kwargs)
if isinstance(result, Coroutine):
result = await result
elif isinstance(check, Coroutine):
result = await check
else:
raise TypeError(f"check is {type(check)}, neither function nor coroutine")
return result
async def interval_checker(check: Callable | Coroutine, interval: datetime.timedelta, *args, **kwargs):
interval_secs = interval.total_seconds()
while True:
logging.info(f"Calling {check.__name__}")
result = await _call_check(check, *args, **kwargs)
logging.info(f"Got {len(result)} alerts")
for alert in result:
await alerts.send_alert(alert)
await asyncio.sleep(interval_secs)
async def scheduled_checker(
check: Callable | Coroutine, period: datetime.timedelta, when: datetime.time, *args, **kwargs
):
match period:
case datetime.timedelta(days=1):
while True:
now = datetime.datetime.now()
next_datetime = datetime.datetime.combine(datetime.date.today(), when)
if next_datetime < now:
next_datetime += datetime.timedelta(days=1)
logging.info(f"Scheduled to call {check.__name__} at {next_datetime.isoformat()}")
await asyncio.sleep(
(next_datetime - now).total_seconds()
) # might be negative at this point, asyncio doesn't care
logging.info(f"Calling {check.__name__}")
result = await _call_check(check, *args, **kwargs)
logging.info(f"Got {len(result)} alerts")
for alert in result:
await alerts.send_alert(alert)
case _:
raise NotImplementedError

276
archive-arch/misc/checks.py Normal file
View file

@ -0,0 +1,276 @@
import logging
import traceback
from datetime import timedelta
from alerting import alerts
from alerting.enum import AlertType, Severity
from misc import cvars, docker_registry, sensors, vuln
from misc.disks import LVAttr, WearoutIndicator, get_wearout_reading
IS_TESTING = False
def temp_check() -> list[alerts.Alert]:
alert_list = []
temps = sensors.Sensors.get_temperatures()
for _, sensor_list in temps.items():
for sensor in sensor_list:
if sensor.sensor_type == "nct6687":
continue # little valuable info and too low limits there, might as well ignore it
if sensor.critical_temp is not None and (IS_TESTING or sensor.current_temp > sensor.critical_temp):
alert = alerts.Alert(
alert_type=AlertType("TEMP"),
message=f"{sensor.sensor_type} {sensor.sensor_label}: {sensor.current_temp}°C > {sensor.critical_temp}°C",
severity=Severity.CRITICAL,
)
elif sensor.highest_temp is not None and (IS_TESTING or sensor.current_temp > sensor.highest_temp):
alert = alerts.Alert(
alert_type=AlertType("TEMP"),
message=f"{sensor.sensor_type} {sensor.sensor_label}: {sensor.current_temp}°C > {sensor.highest_temp}°C",
severity=Severity.WARNING,
)
else:
continue
alert_list.append(alert)
return alert_list
def cpu_check() -> list[alerts.Alert]:
sensor = sensors.Sensors.get_cpu()
if IS_TESTING or sensor.current_load > sensor.critical_load:
alert = alerts.Alert(
alert_type=AlertType("CPU"),
message=f"{sensor.current_load}% > {sensor.critical_load}%",
severity=Severity.CRITICAL,
)
elif IS_TESTING or sensor.current_load > sensor.highest_load:
alert = alerts.Alert(
alert_type=AlertType("CPU"),
message=f"{sensor.current_load}% > {sensor.highest_load}%",
severity=Severity.WARNING,
)
else:
return []
return [alert]
def ram_check() -> list[alerts.Alert]:
sensor = sensors.Sensors.get_ram()
if IS_TESTING or sensor.current_avail < sensor.critical_avail:
alert = alerts.Alert(
alert_type=AlertType("RAM"),
message=f"{(sensor.current_avail / 1024**3):.2f} GiB < {(sensor.critical_avail / 1024**3):.2f} GiB",
severity=Severity.CRITICAL,
)
elif IS_TESTING or sensor.current_avail < sensor.warning_avail:
alert = alerts.Alert(
alert_type=AlertType("RAM"),
message=f"{(sensor.current_avail / 1024**3):.2f} GiB < {(sensor.warning_avail / 1024**3):.2f} GiB",
severity=Severity.WARNING,
)
else:
return []
return [alert]
async def vuln_check() -> list[alerts.Alert]:
vulns = await vuln.get_vulns()
alert_list = []
for v in vulns:
if IS_TESTING or v.fixed or v.severity in (vuln.Severity.HIGH, vuln.Severity.CRITICAL):
match v.severity:
case vuln.Severity.LOW:
severity = Severity.INFO
case vuln.Severity.MEDIUM:
severity = Severity.WARNING
case vuln.Severity.HIGH | vuln.Severity.CRITICAL:
severity = Severity.CRITICAL
message = f"{v.id}: {v.vuln_type} in {','.join(v.packages)}"
html_message = f"<a href='{v.link}'>{v.id}</a>: {v.vuln_type} in {','.join(v.packages)}"
if v.fixed:
message.append(f" -- update to {v.fixed} ASAP")
html_message.append(f" -- update to {v.fixed} ASAP")
alert = alerts.Alert(
alert_type=AlertType.VULN,
message=message,
html_message=html_message,
severity=severity,
)
alert_list.append(alert)
return alert_list
async def ups_check() -> list[alerts.Alert]:
sensor = await sensors.Sensors.get_ups()
if not sensor:
return
alert_list = []
if IS_TESTING or sensor.battery_charge_percentage < sensor.battery_critical_percentage:
alert_list.append(
alerts.Alert(
alert_type=AlertType.UPS,
message=f"Battery is under {sensor.battery_critical_percentage}%\n{sensor.battery_charge_percentage}% ({timedelta(seconds=sensor.battery_runtime)}) remaining.",
severity=Severity.CRITICAL,
)
)
elif IS_TESTING or sensor.battery_charge_percentage < sensor.battery_warning_percentage:
alert_list.append(
alerts.Alert(
alert_type=AlertType.UPS,
message=f"Battery is under {sensor.battery_warning_percentage}%\n{sensor.battery_charge_percentage}% ({timedelta(seconds=sensor.battery_runtime)}) remaining.",
severity=Severity.WARNING,
)
)
for status in sensor.ups_status:
if IS_TESTING or status == sensors.UPSStatus.UPS_OVERLOAD:
alert_list.append(
alerts.Alert(alert_type=AlertType.UPS, message=f"UPS is overloaded!", severity=Severity.CRITICAL)
)
elif IS_TESTING or status == sensors.UPSStatus.ON_BATTERY:
alert_list.append(
alerts.Alert(
alert_type=AlertType.UPS,
message=f"UPS is on battery.\n{sensor.battery_charge_percentage}% ({timedelta(seconds=sensor.battery_runtime)}) remaining.",
severity=Severity.INFO,
)
)
elif IS_TESTING or status == sensors.UPSStatus.UPS_TRIM:
alert_list.append(
alerts.Alert(
alert_type=AlertType.UPS,
message=f"Overvoltage detected: trimming voltage to nominal.",
severity=Severity.INFO,
)
)
elif IS_TESTING or status == sensors.UPSStatus.UPS_BOOST:
alert_list.append(
alerts.Alert(
alert_type=AlertType.UPS,
message=f"Undervoltage detected: boosting voltage to nominal.",
severity=Severity.INFO,
)
)
return alert_list
async def docker_registry_check() -> list[alerts.Alert]:
updated_images = await docker_registry.get_updated_images()
alert_list = []
for image in updated_images:
alert_list.append(
alerts.Alert(
alert_type=AlertType.UPDATE,
message=f"{image} docker image: new version available",
severity=Severity.INFO,
)
)
return alert_list
def raid_check() -> list[alerts.Alert]:
check_config = cvars.config.get().checks.raid
alert_list = []
for lv in check_config.lvs:
try:
lv_attr = LVAttr.from_cli(lv)
except Exception as exc:
alert_list.append(
alerts.Alert(
alert_type=AlertType.ERROR,
message=f"Could not check RAID LV {lv}: {repr(exc)}, see logs",
severity=Severity.CRITICAL,
)
)
logging.error(traceback.format_exc())
continue
# sanity check
if lv_attr.vol_type not in [LVAttr.VolType.RAID, LVAttr.VolType.RAID_NOSYNC]:
alert_list.append(
alerts.Alert(
alert_type=AlertType.ERROR,
message=f"LV {lv} is not of RAID type",
severity=Severity.CRITICAL,
)
)
continue
if IS_TESTING:
alert_list.append(
alerts.Alert(
alert_type=AlertType.RAID,
message=f"Test alert: LV {lv} health is {lv_attr.health}",
severity=Severity.INFO,
)
)
match lv_attr.health:
case LVAttr.Health.PARTIAL:
alert_list.append(
alerts.Alert(
alert_type=AlertType.RAID,
message=f"LV {lv} operating in partial mode; one of PVs has failed",
severity=Severity.CRITICAL,
)
)
case LVAttr.Health.UNKNOWN:
alert_list.append(
alerts.Alert(
alert_type=AlertType.RAID,
message=f"LV {lv}'s state is unknown",
severity=Severity.CRITICAL,
)
)
case LVAttr.Health.REFRESH_NEEDED:
alert_list.append(
alerts.Alert(
alert_type=AlertType.RAID,
message=f"LV {lv} has suffered a write error; run a refresh or replace the failing PV",
severity=Severity.WARNING,
)
)
case LVAttr.Health.MISMATCHES:
alert_list.append(
alerts.Alert(
alert_type=AlertType.RAID,
message=f"LV {lv} is partially incoherent; run a repairing scrub operation",
severity=Severity.WARNING,
)
)
return alert_list
def disk_wearout_check() -> list[alerts.Alert]:
check_config = cvars.config.get().checks.wearout
alert_list = []
for disk in check_config.disks:
try:
wearout_reading = get_wearout_reading(disk.name)
except Exception as exc:
alert_list.append(
alerts.Alert(
alert_type=AlertType.ERROR,
message=f"Could not check wearout for disk {disk.name}: {repr(exc)}, see logs",
severity=Severity.CRITICAL,
)
)
logging.error(traceback.format_exc())
continue
if IS_TESTING or wearout_reading.current_reading < wearout_reading.threshold_reading:
match wearout_reading.indicator:
case WearoutIndicator.REALLOCATED_SECTORS:
message = f"Disk {disk.name} has reallocated sectors (curr {wearout_reading.current_reading}, thresh {wearout_reading.threshold_reading})"
case WearoutIndicator.SPARE_BLOCKS:
message = f"Disk {disk.name} has too few spare blocks (curr {wearout_reading.current_reading}, thresh {wearout_reading.threshold_reading})"
alert_list.append(
alerts.Alert(alert_type=AlertType.DISKS, message=message, severity=Severity[disk.severity])
)
return alert_list

View file

@ -0,0 +1,6 @@
import os
import tempfile
from pathlib import Path
CONFIG_FILE = (Path(os.path.dirname(os.path.realpath(__file__))) / ".." / "config.json").resolve()
TMP_DIR = Path(tempfile.gettempdir()) / "lego-monitoring"

View file

@ -0,0 +1,65 @@
import json
from dataclasses import dataclass
from alt_utils import NestedDeserializableDataclass
from alerting.enum import Severity
from misc.common import CONFIG_FILE
@dataclass
class MatrixConfig:
homeserver: str
user_id: str
device_id: str
access_token: str
room_id: str
@dataclass
class CheckDockerRegistryConfig:
hub_url: str
images: list[str]
@dataclass
class CheckRaidConfig:
lvs: list[str]
@dataclass
class CheckWearoutDiskConfig:
name: str
severity: Severity
@dataclass
class CheckWearoutConfig(NestedDeserializableDataclass):
disks: list[CheckWearoutDiskConfig]
@dataclass
class CheckLoginConfig:
hostname: str
@dataclass
class ChecksConfig(NestedDeserializableDataclass):
docker_registry: CheckDockerRegistryConfig
raid: CheckRaidConfig
wearout: CheckWearoutConfig
login: CheckLoginConfig
@dataclass
class Config(NestedDeserializableDataclass):
matrix: MatrixConfig
checks: ChecksConfig
disabled_checks: list[str]
def get_config() -> Config:
with open(CONFIG_FILE) as f:
cfg_dict = json.load(f)
cfg = Config.from_dict(cfg_dict)
return cfg

View file

@ -0,0 +1,8 @@
from contextvars import ContextVar
import nio
from misc.config import Config
config: ContextVar[Config] = ContextVar("config")
matrix_client: ContextVar[nio.AsyncClient] = ContextVar("matrix_client")

191
archive-arch/misc/disks.py Normal file
View file

@ -0,0 +1,191 @@
import json
import subprocess
from dataclasses import dataclass
from enum import Enum, StrEnum
from typing import Optional, Self
@dataclass
class LVAttr:
"""https://man.archlinux.org/man/lvs.8#NOTES"""
class VolType(StrEnum):
CACHE = "C"
MIRRORED = "m"
MIRRORED_NOSYNC = "M"
ORIGIN = "o"
ORIGIN_MERGING_SNAPSHOT = "O"
INTEGRITY = "g"
RAID = "r"
RAID_NOSYNC = "R"
SNAPSHOT = "s"
MERGING_SNAPSHOT = "S"
PVMOVE = "p"
VIRTUAL = "v"
IMAGE = "i"
IMAGE_OUT_OF_SYNC = "I"
MIRROR_LOG = "l"
CONVERTING = "c"
THIN = "V"
THIN_POOL = "t"
THIN_POOL_DATA = "T"
VDO_POOL = "d"
VDO_POOL_DATA = "D"
METADATA = "e"
NORMAL = "-"
class Permissions(StrEnum):
WRITABLE = "w"
READONLY = "r"
READONLY_ACTIVATED = "R"
class AllocationPolicy(StrEnum):
ANYWHERE = "a"
ANYWHERE_LOCKED = "A"
CONTIGUOUS = "c"
CONTIGUOUS_LOCKED = "C"
INHERITED = "i"
INHERITED_LOCKED = "I"
CLING = "l"
CLING_LOCKED = "L"
NORMAL = "n"
NORMAL_LOCKED = "N"
class State(StrEnum):
ACTIVE = "a"
HISTORICAL = "h"
SUSPENDED = "s"
INVALID_SNAPSHOT = "I"
INVALID_SUSPENDED_SNAPSHOT = "S"
SNAPSHOT_MERGE_FAILED = "m"
SUSPENDED_SNAPSHOT_MERGE_FAILED = "M"
DEVICE_PRESENT_NO_TABLES = "d"
DEVICE_PRESENT_INACTIVE_TABLE = "i"
THIN_POOL_CHECK_NEEDED = "c"
SUSPENDED_THIN_POOL_CHECK_NEEDED = "C"
UNKNOWN = "X"
class IsOpen(StrEnum):
OPEN = "o"
CLOSED = "-"
UNKNOWN = "X"
class TargetType(StrEnum):
CACHE = "C"
MIRROR = "m"
RAID = "r"
SNAPSHOT = "s"
THIN = "t"
UNKNOWN = "u"
VIRTUAL = "v"
NORMAL = "-"
class Health(StrEnum):
# for all
PARTIAL = "p"
UNKNOWN = "X"
OK = "-"
# for RAID
REFRESH_NEEDED = "r"
MISMATCHES = "m"
WRITEMOSTLY = "w"
RESHAPING = "s"
REMOVE = "R"
# for thin pools and LVs
FAILED = "F"
OUT_OF_SPACE = "D"
METADATA_READ_ONLY = "M"
# for writecache
ERROR = "E"
vol_type: VolType
permissions: Permissions
allocation_policy: AllocationPolicy
fixed_minor: bool
state: State
is_open: IsOpen
target_type: TargetType
zero_before_use: bool
health: Health
skip_activation: bool
name: Optional[str] = None
@classmethod
def from_str(cls, attr_str: str, name: Optional[str] = None) -> Self:
kwargs = {}
kwargs["vol_type"] = cls.VolType(attr_str[0])
kwargs["permissions"] = cls.Permissions(attr_str[1])
kwargs["allocation_policy"] = cls.AllocationPolicy(attr_str[2])
kwargs["fixed_minor"] = True if attr_str[3] == "m" else False
kwargs["state"] = cls.State(attr_str[4])
kwargs["is_open"] = cls.IsOpen(attr_str[5])
kwargs["target_type"] = cls.TargetType(attr_str[6])
kwargs["zero_before_use"] = True if attr_str[7] == "z" else False
kwargs["health"] = cls.Health(attr_str[8])
kwargs["skip_activation"] = True if attr_str[9] == "k" else False
kwargs["name"] = name
return cls(**kwargs)
@classmethod
def from_cli(cls, name: str) -> Self:
json_obj = json.loads(subprocess.run(["lvs", "--reportformat=json", name], capture_output=True).stdout)
attr_str = json_obj["report"][0]["lv"][0]["lv_attr"]
return cls.from_str(attr_str, name)
class WearoutIndicator(Enum):
REALLOCATED_SECTORS = 0
SPARE_BLOCKS = 1
@dataclass
class WearoutReading:
indicator: WearoutIndicator
current_reading: int
threshold_reading: int
def _get_wearout_reading_from_smartctl_output(smartctl_output: dict) -> WearoutReading:
disk_protocol = smartctl_output["device"]["protocol"]
rotation_rate = smartctl_output.get("rotation_rate", 0)
match rotation_rate:
case 0: # assuming non-rotating media is an SSD
indicator = WearoutIndicator.SPARE_BLOCKS
match disk_protocol:
case "ATA":
attr_table = smartctl_output["ata_smart_attributes"]["table"]
for a in attr_table:
if a["name"] == "Available_Reservd_Space":
value = a["value"]
threshold = a["thresh"]
break
else:
raise Exception(f"no Available_Reservd_Space on ATA SSD")
case "NVMe":
value = smartctl_output["nvme_smart_health_information_log"]["available_spare"]
threshold = smartctl_output["nvme_smart_health_information_log"]["available_spare_threshold"]
case _:
indicator = WearoutIndicator.REALLOCATED_SECTORS
match disk_protocol:
case "ATA":
attr_table = smartctl_output["ata_smart_attributes"]["table"]
for a in attr_table:
if a["name"] == "Reallocated_Sector_Ct":
value = a["value"]
threshold = a["thresh"]
break
else:
raise Exception(f"no Reallocated_Sector_Ct on ATA HDD")
case "NVMe": # ? NVMe HDDs are very rare, if they even exist
raise NotImplementedError
return WearoutReading(indicator, current_reading=value, threshold_reading=threshold)
def get_wearout_reading(disk: str) -> WearoutReading:
smartctl_output = json.loads(subprocess.run(["smartctl", "-ja", disk], capture_output=True).stdout.decode("utf-8"))
wearout_reading = _get_wearout_reading_from_smartctl_output(smartctl_output)
return wearout_reading

View file

@ -0,0 +1,129 @@
import datetime
import ipaddress
import json
import logging
import re
import socket
import traceback
from typing import Optional
from urllib.parse import urlparse
import uplink
from alerting import alerts
from alerting.enum import AlertType, Severity
from misc import cvars
class DockerHubClient(uplink.Consumer):
@uplink.returns.json
@uplink.get("v2/namespaces/{namespace}/repositories/{repository}/tags/latest")
def get_latest_tag(self, namespace: uplink.Path, repository: uplink.Path): ...
class DockerRegistryAuthorizer(uplink.Consumer):
@uplink.returns.json
@uplink.get()
def _get_token_unprotected(self, service: uplink.Query, scope: uplink.Query): ...
async def get_token(self, service: Optional[str], scope: Optional[str]) -> str:
host = urlparse(self.session.base_url).hostname
ips = set()
try:
ips.add(ipaddress.ip_address(host))
except:
addrinfo = socket.getaddrinfo(host, None)
for t in addrinfo:
ips.add(ipaddress.ip_address(t[4][0]))
for ip in ips:
if not ip.is_global:
raise Exception(f"{host} resolved to {ip} which is not global")
return (await self._get_token_unprotected(service, scope))["token"]
class DockerRegistryClient(uplink.Consumer):
@uplink.get("v2/{namespace}/{repository}/manifests/latest")
def _test_manifest(self, namespace: uplink.Path, repository: uplink.Path): ...
@uplink.returns.json
@uplink.get("v2/{namespace}/{repository}/manifests/latest")
def _get_manifest(self, namespace: uplink.Path, repository: uplink.Path): ...
@uplink.get("v2/{namespace}/{repository}/blobs/{digest}")
def _get_blob(self, namespace: uplink.Path, repository: uplink.Path, digest: uplink.Path): ...
async def get_auth_requirements(self, namespace: str, repository: str) -> Optional[tuple[str, str, str]]:
response = await self._test_manifest(namespace, repository)
if 200 <= response.status_code < 300:
return None
auth_regex = re.compile(r"([^\s,]+) ?[=] ?\"?([^\s,\"]+)\"?")
auth_keys = dict(auth_regex.findall(response.headers["Www-Authenticate"]))
return (auth_keys["realm"], auth_keys.get("service", None), auth_keys.get("scope", None))
async def get_updated_datetime_iso(self, namespace: str, repository: str) -> str:
manifest = await self._get_manifest(namespace, repository)
config_digest = manifest["config"]["digest"]
blob = json.loads(await (await self._get_blob(namespace, repository, digest=config_digest)).content.read())
return blob["created"]
async def get_updated_images() -> list[str]:
check_config = cvars.config.get().checks.docker_registry
hub_client = DockerHubClient(base_url=check_config.hub_url, client=uplink.AiohttpClient())
now = datetime.datetime.now(datetime.timezone.utc)
updated_images = []
for image in check_config.images:
image_split = image.split("/")
match len(image_split):
case 2:
namespace, repository = image_split
try:
last_updated_iso = (await hub_client.get_latest_tag(namespace=namespace, repository=repository))[
"tag_last_pushed"
]
except Exception as exc:
await alerts.send_alert(
alerts.Alert(
alert_type=AlertType.ERROR,
message=f"Could not query Docker Hub: {repr(exc)}, see logs",
severity=Severity.CRITICAL,
)
)
logging.error(traceback.format_exc())
return []
case 3:
registry, namespace, repository = image_split
registry_client = DockerRegistryClient(base_url=f"https://{registry}/", client=uplink.AiohttpClient())
try:
requirements = await registry_client.get_auth_requirements(namespace, repository)
if requirements is not None:
registry_authorizer = DockerRegistryAuthorizer(
base_url=requirements[0], client=uplink.AiohttpClient()
)
token = await registry_authorizer.get_token(requirements[1], requirements[2])
registry_client.session.headers["Authorization"] = f"Bearer {token}"
last_updated_iso = await registry_client.get_updated_datetime_iso(
namespace=namespace, repository=repository
)
except Exception as exc:
await alerts.send_alert(
alerts.Alert(
alert_type=AlertType.ERROR,
message=f"Could not query Docker registry {registry}: {repr(exc)}, see logs",
severity=Severity.CRITICAL,
)
)
logging.error(traceback.format_exc())
return []
case _:
raise Exception(f"Invalid image spec: {image}")
last_updated = datetime.datetime.fromisoformat(last_updated_iso)
logging.info(f"Image {image} last updated at {last_updated}")
if now - last_updated <= datetime.timedelta(days=1):
updated_images.append(image)
return updated_images

View file

@ -0,0 +1,167 @@
import subprocess
from dataclasses import dataclass
from enum import StrEnum
from psutil import cpu_percent, sensors_temperatures, virtual_memory
from alerting import alerts
from alerting.enum import AlertType, Severity
@dataclass
class TemperatureSensor:
sensor_type: str
sensor_label: str
current_temp: float
highest_temp: float | None = None
critical_temp: float | None = None
@dataclass
class CpuSensor:
current_load: float
highest_load: float = 90
critical_load: float = 95
@dataclass
class RamSensor:
current_avail: int
current_avail_percentage: float
warning_avail: int = 4 * 1024**3
critical_avail: int = 2 * 1024**3
class UPSStatus(StrEnum):
"""https://networkupstools.org/docs/developer-guide.chunked/new-drivers.html#_status_data"""
ON_LINE = "OL"
ON_BATTERY = "OB"
BATTERY_LOW = "LB"
BATTERY_HIGH = "HB"
BATTERY_REPLACE = "RB"
BATTERY_CHARGING = "CHRG"
BATTERY_DISCHARGING = "DISCHRG"
UPS_BYPASS = "BYPASS"
"""Battery and connected devices are not protected from power outage!"""
UPS_OFFLINE = "OFF"
UPS_OVERLOAD = "OVER"
UPS_CALIBRATION = "CAL"
UPS_TRIM = "TRIM"
UPS_BOOST = "BOOST"
UPS_FSD = "FSD"
@dataclass
class UPSSensor:
ups_status: list[UPSStatus] = None
battery_charge_percentage: int = None
battery_warning_percentage: int = 20
battery_critical_percentage: int = 10
battery_runtime: int = 1000
class Sensors:
@staticmethod
def get_temperatures() -> dict[str, list[TemperatureSensor]]:
psutil_temp_sensors = sensors_temperatures()
temp_sensors = {}
for s_type, sensors in psutil_temp_sensors.items():
if s_type not in temp_sensors.keys():
temp_sensors[s_type] = []
match (s_type):
case "nvme":
for sensor in sensors:
temp_sensors[s_type].append(
TemperatureSensor(
sensor_type=s_type,
sensor_label=sensor.label,
current_temp=sensor.current,
highest_temp=sensor.high,
critical_temp=sensor.critical,
)
)
case "amdgpu":
temp_sensors[s_type].append(
TemperatureSensor(
sensor_type=s_type,
sensor_label="Integrated GPU",
current_temp=sensors[0].current,
)
)
case "k10temp":
temp_sensors[s_type].append(
TemperatureSensor(
sensor_type=s_type,
sensor_label="AMD CPU",
current_temp=sensors[0].current,
critical_temp=95.0, # hardcoded because we have R9 7900X
)
)
case "nct6687":
lables = {
"AMD TSI Addr 98h": "CPU",
"Diode 0 (curr)": "System",
"Thermistor 15": "VRM MOSFET",
"Thermistor 1": "Platform Controller Hub (Peripherals)",
"Thermistor 16": "CPU Socket",
}
for sensor in sensors[:-2]:
real_label = lables[sensor.label]
temp_sensors[s_type].append(
TemperatureSensor(
sensor_type=s_type,
sensor_label=real_label,
current_temp=sensor.current,
highest_temp=sensor.high or None,
critical_temp=sensor.critical or None,
)
)
return temp_sensors
@staticmethod
def get_cpu() -> CpuSensor:
return CpuSensor(current_load=cpu_percent())
@staticmethod
def get_ram() -> RamSensor:
ram = virtual_memory()
return RamSensor(current_avail=ram.available, current_avail_percentage=ram.percent)
@staticmethod
async def get_ups() -> None | UPSSensor:
try:
raw_data = subprocess.run(["upsc", "cp1300"], stdout=subprocess.PIPE, encoding="utf-8")
except FileNotFoundError:
await alerts.send_alert(
alerts.Alert(
alert_type=AlertType.ERROR,
message="upsc is not installed!",
severity=Severity.CRITICAL,
)
)
return None
sensor_data = UPSSensor()
for line in raw_data.stdout.splitlines():
sensor, value = line.split(": ")[:2]
match sensor:
case "battery.charge":
sensor_data.battery_charge_percentage = int(value)
case "battery.charge.low":
sensor_data.battery_critical_percentage = int(value)
case "battery.charge.warning":
sensor_data.battery_warning_percentage = int(value)
case "battery.runtime":
sensor_data.battery_runtime = int(value)
case "ups.status":
sensor_data.ups_status = [UPSStatus(status) for status in value.split()]
case _:
...
return sensor_data

68
archive-arch/misc/vuln.py Normal file
View file

@ -0,0 +1,68 @@
import json
import logging
import subprocess
import traceback
from dataclasses import dataclass
from enum import StrEnum
from typing import Optional
from alerting import alerts
from alerting.enum import AlertType, Severity
class Severity(StrEnum):
LOW = "Low"
MEDIUM = "Medium"
HIGH = "High"
CRITICAL = "Critical"
@dataclass
class Vulnerability:
id: str
link: str
vuln_type: str
packages: list[str]
severity: Severity
fixed: Optional[str]
def _parse_arch_audit_output(output: str) -> list[Vulnerability]:
arch_audit_json = json.loads(output)
vulnerabilities = []
for v in arch_audit_json:
vulnerability = Vulnerability(
id=v["name"],
link=f"https://security.archlinux.org/{v['name']}",
vuln_type=v["type"],
packages=v["packages"],
severity=v["severity"],
fixed=v["fixed"],
)
vulnerabilities.append(vulnerability)
return vulnerabilities
async def get_vulns() -> list[Vulnerability]:
try:
arch_audit_output = subprocess.check_output(["arch-audit", "--json"])
except FileNotFoundError:
await alerts.send_alert(
alerts.Alert(
alert_type=AlertType.ERROR,
message="arch-audit not installed!",
severity=Severity.CRITICAL,
)
)
return []
except Exception as exc:
await alerts.send_alert(
alerts.Alert(
alert_type=AlertType.ERROR,
message=f"arch-audit failed to run: {repr(exc)}, see logs",
severity=Severity.CRITICAL,
)
)
logging.error(traceback.format_exc())
return []
return _parse_arch_audit_output(arch_audit_output)

25
archive-arch/prettyprint.py Executable file
View file

@ -0,0 +1,25 @@
#!/usr/bin/env python3
from colorama import Back, Style
from misc.sensors import Sensors
def pretty_print():
s = Sensors.get_temperatures()
for k, v in s.items():
print(f"{Back.CYAN}{k}{Style.RESET_ALL}")
for sensors in v:
print(f"{sensors.sensor_label}: {sensors.current_temp}°C")
print()
s = Sensors.get_cpu()
print(f"Used CPU: {s.current_load}%")
s = Sensors.get_ram()
print(f"Available RAM: {(s.current_avail / 1024**3):.2f} ({s.current_avail_percentage}%) GiB")
if __name__ == "__main__":
pretty_print()

View file

@ -0,0 +1,6 @@
colorama==0.4.6
psutil==5.9.8
matrix-nio[e2e]==0.24.0
uplink[aiohttp]==0.9.7
setuptools==75.2.0
alt-utils==0.0.4

View file

@ -0,0 +1,54 @@
import asyncio
import logging
import os
import socket
import sys
import traceback
from alerting import alerts
from alerting.delayed import send_alert_delayed
from alerting.enum import AlertType, Severity
from misc.config import get_config
async def main():
check_config = get_config().checks.login
try:
from_where = os.environ["SSH_CLIENT"].split()[0]
except:
from_where = "localhost"
is_local = True
else:
is_local = False
if not is_local and len(sys.argv) > 1 and sys.argv[1] == "local-only":
return
try:
actual_user = os.environ["SUDO_USER"]
except Exception as exc:
await alerts.send_alert(
alerts.Alert(
alert_type=AlertType.ERROR,
message=f"Failed to determine username for login from {from_where}: {repr(exc)}, see logs",
severity=Severity.CRITICAL,
)
)
logging.error(traceback.format_exc())
return
if not is_local:
rdns_result = socket.getnameinfo((from_where, 0), 0)[0]
message = f"Login from {from_where} as {actual_user} on {check_config.hostname}"
html_message = f"Login from <code>{from_where}</code> ({rdns_result}) as {actual_user} on <code>{check_config.hostname}</code>"
else:
message = f"Login from {from_where} as {actual_user} on {check_config.hostname}"
html_message = f"Login from {from_where} as {actual_user} on <code>{check_config.hostname}</code>"
alert = alerts.Alert(alert_type=AlertType.LOGIN, message=message, severity=Severity.INFO, html_message=html_message)
send_alert_delayed(alert)
if __name__ == "__main__":
asyncio.run(main())

View file

@ -0,0 +1,42 @@
#!/usr/bin/env python3
import asyncio
from os import environ
from sys import argv
from alerting import alerts
from alerting.enum import AlertType, Severity
type_priority_map = {
"ONLINE": Severity.INFO, # UPS is back online
"ONBATT": Severity.WARNING, # UPS is on battery
"LOWBATT": Severity.CRITICAL, # UPS is on battery and has a low battery (is critical)
"FSD": Severity.CRITICAL, # UPS is being shutdown by the primary (FSD = "Forced Shutdown")
"COMMOK": Severity.INFO, # Communications established with the UPS
"COMMBAD": Severity.WARNING, # Communications lost to the UPS
"SHUTDOWN": Severity.CRITICAL, # The system is being shutdown
"REPLBATT": Severity.WARNING, # The UPS battery is bad and needs to be replaced
"NOCOMM": Severity.WARNING, # A UPS is unavailable (cant be contacted for monitoring)
"NOPARENT": Severity.CRITICAL, # upsmon parent process died - shutdown impossible
"CAL": Severity.INFO, # UPS calibration in progress
"NOTCAL": Severity.INFO, # UPS calibration finished
"OFF": Severity.CRITICAL, # UPS administratively OFF or asleep
"NOTOFF": Severity.INFO, # UPS no longer administratively OFF or asleep
"BYPASS": Severity.WARNING, # UPS on bypass (powered, not protecting)
"NOTBYPASS": Severity.INFO, # UPS no longer on bypass
None: Severity.CRITICAL, # unknown alert type
}
async def main():
"""Sends an alert about a UPS event. Meant to be used from upsmon with NOTIFYCMD"""
if len(argv) != 2:
raise Exception("provide exactly one argument: alert message")
message = argv[1]
typestr = environ.get("NOTIFYTYPE", None)
severity = type_priority_map[typestr]
alert = alerts.Alert(alert_type=AlertType.UPS, message=message, severity=severity)
await alerts.send_alert(alert)
if __name__ == "__main__":
asyncio.run(main())

90
archive-arch/service.py Executable file
View file

@ -0,0 +1,90 @@
#!/usr/bin/env python3
import asyncio
import datetime
import logging
import os
import shutil
import signal
from alerting import alerts, delayed
from misc import checks, cvars
from misc.checkers import interval_checker, scheduled_checker
from misc.common import TMP_DIR
from misc.config import get_config
logging.basicConfig(level=logging.INFO)
stopping = False
def stop_gracefully(signum, frame):
global stopping
stopping = True
def create_temp_dir() -> None:
try:
os.mkdir(str(TMP_DIR))
except FileExistsError:
pass
os.chmod(str(TMP_DIR), 0o770)
try:
shutil.chown(str(TMP_DIR), user="root", group="alerting")
except LookupError:
shutil.chown(str(TMP_DIR), user="root", group="root")
with open(str(TMP_DIR / "pid"), "w") as pf:
pf.write(str(os.getpid()))
async def main():
create_temp_dir()
signal.signal(signal.SIGTERM, stop_gracefully)
loop = asyncio.get_event_loop()
loop.add_signal_handler(signal.SIGUSR1, lambda: asyncio.create_task(delayed.handler()))
config = get_config()
cvars.config.set(config)
client = await alerts.get_client()
cvars.matrix_client.set(client)
checker_sets = {
"temp": [interval_checker(checks.temp_check, datetime.timedelta(minutes=5))],
"cpu": [interval_checker(checks.cpu_check, datetime.timedelta(minutes=5))],
"ups": [interval_checker(checks.ups_check, datetime.timedelta(minutes=5))],
"ram": [interval_checker(checks.ram_check, datetime.timedelta(minutes=1))],
"vuln": [interval_checker(checks.vuln_check, datetime.timedelta(days=1))],
"raid": [interval_checker(checks.raid_check, datetime.timedelta(days=1))],
"disk_wearout": [interval_checker(checks.disk_wearout_check, datetime.timedelta(days=1))],
"docker_registry": [
scheduled_checker(
checks.docker_registry_check, period=datetime.timedelta(days=1), when=datetime.time(hour=0, minute=0)
)
],
}
for disabled_key in config.disabled_checks:
if disabled_key in checker_sets:
del checker_sets[disabled_key]
checkers = []
for _, s in checker_sets.items():
for checker in s:
checkers.append(checker)
async with asyncio.TaskGroup() as tg:
checker_tasks: set[asyncio.Task] = set()
for c in checkers:
task = tg.create_task(c)
checker_tasks.add(task)
while True:
if stopping:
await client.close()
shutil.rmtree(str(TMP_DIR))
raise SystemExit
else:
await asyncio.sleep(3)
if __name__ == "__main__":
asyncio.run(main())

View file

@ -0,0 +1,594 @@
{
"json_format_version": [
1,
0
],
"smartctl": {
"version": [
7,
4
],
"pre_release": false,
"svn_revision": "5530",
"platform_info": "x86_64-linux-6.11.3-arch1-1",
"build_info": "(local build)",
"argv": [
"smartctl",
"-ja",
"/dev/sda"
],
"drive_database_version": {
"string": "7.3/5528"
},
"exit_status": 0
},
"local_time": {
"time_t": 1731149584,
"asctime": "Sat Nov 9 13:53:04 2024 MSK"
},
"device": {
"name": "/dev/sda",
"info_name": "/dev/sda [SAT]",
"type": "sat",
"protocol": "ATA"
},
"model_name": "WDC WD20EARZ-00C5XB0",
"serial_number": "WD-WX32D83C15U7",
"wwn": {
"naa": 5,
"oui": 5358,
"id": 8959374949
},
"firmware_version": "01.01A01",
"user_capacity": {
"blocks": 3907029168,
"bytes": 2000398934016
},
"logical_block_size": 512,
"physical_block_size": 4096,
"rotation_rate": 5400,
"form_factor": {
"ata_value": 2,
"name": "3.5 inches"
},
"trim": {
"supported": false
},
"in_smartctl_database": false,
"ata_version": {
"string": "ACS-3 T13/2161-D revision 5",
"major_value": 2046,
"minor_value": 109
},
"sata_version": {
"string": "SATA 3.1",
"value": 126
},
"interface_speed": {
"max": {
"sata_value": 14,
"string": "6.0 Gb/s",
"units_per_second": 60,
"bits_per_unit": 100000000
},
"current": {
"sata_value": 3,
"string": "6.0 Gb/s",
"units_per_second": 60,
"bits_per_unit": 100000000
}
},
"smart_support": {
"available": true,
"enabled": true
},
"smart_status": {
"passed": true
},
"ata_smart_data": {
"offline_data_collection": {
"status": {
"value": 0,
"string": "was never started"
},
"completion_seconds": 19380
},
"self_test": {
"status": {
"value": 0,
"string": "completed without error",
"passed": true
},
"polling_minutes": {
"short": 2,
"extended": 208,
"conveyance": 5
}
},
"capabilities": {
"values": [
123,
3
],
"exec_offline_immediate_supported": true,
"offline_is_aborted_upon_new_cmd": false,
"offline_surface_scan_supported": true,
"self_tests_supported": true,
"conveyance_self_test_supported": true,
"selective_self_test_supported": true,
"attribute_autosave_enabled": true,
"error_logging_supported": true,
"gp_logging_supported": true
}
},
"ata_sct_capabilities": {
"value": 12341,
"error_recovery_control_supported": false,
"feature_control_supported": true,
"data_table_supported": true
},
"ata_smart_attributes": {
"revision": 16,
"table": [
{
"id": 1,
"name": "Raw_Read_Error_Rate",
"value": 200,
"worst": 200,
"thresh": 51,
"when_failed": "",
"flags": {
"value": 47,
"string": "POSR-K ",
"prefailure": true,
"updated_online": true,
"performance": true,
"error_rate": true,
"event_count": false,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 3,
"name": "Spin_Up_Time",
"value": 175,
"worst": 175,
"thresh": 21,
"when_failed": "",
"flags": {
"value": 39,
"string": "POS--K ",
"prefailure": true,
"updated_online": true,
"performance": true,
"error_rate": false,
"event_count": false,
"auto_keep": true
},
"raw": {
"value": 2241,
"string": "2241"
}
},
{
"id": 4,
"name": "Start_Stop_Count",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 11,
"string": "11"
}
},
{
"id": 5,
"name": "Reallocated_Sector_Ct",
"value": 200,
"worst": 200,
"thresh": 140,
"when_failed": "",
"flags": {
"value": 51,
"string": "PO--CK ",
"prefailure": true,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 7,
"name": "Seek_Error_Rate",
"value": 100,
"worst": 253,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 46,
"string": "-OSR-K ",
"prefailure": false,
"updated_online": true,
"performance": true,
"error_rate": true,
"event_count": false,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 9,
"name": "Power_On_Hours",
"value": 96,
"worst": 96,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 3275,
"string": "3275"
}
},
{
"id": 10,
"name": "Spin_Retry_Count",
"value": 100,
"worst": 253,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 11,
"name": "Calibration_Retry_Count",
"value": 100,
"worst": 253,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 12,
"name": "Power_Cycle_Count",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 10,
"string": "10"
}
},
{
"id": 192,
"name": "Power-Off_Retract_Count",
"value": 200,
"worst": 200,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 6,
"string": "6"
}
},
{
"id": 193,
"name": "Load_Cycle_Count",
"value": 200,
"worst": 200,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 28,
"string": "28"
}
},
{
"id": 194,
"name": "Temperature_Celsius",
"value": 112,
"worst": 105,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 34,
"string": "-O---K ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": false,
"auto_keep": true
},
"raw": {
"value": 31,
"string": "31"
}
},
{
"id": 196,
"name": "Reallocated_Event_Count",
"value": 200,
"worst": 200,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 197,
"name": "Current_Pending_Sector",
"value": 200,
"worst": 200,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 198,
"name": "Offline_Uncorrectable",
"value": 100,
"worst": 253,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 48,
"string": "----CK ",
"prefailure": false,
"updated_online": false,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 199,
"name": "UDMA_CRC_Error_Count",
"value": 200,
"worst": 200,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 200,
"name": "Multi_Zone_Error_Rate",
"value": 100,
"worst": 253,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 8,
"string": "---R-- ",
"prefailure": false,
"updated_online": false,
"performance": false,
"error_rate": true,
"event_count": false,
"auto_keep": false
},
"raw": {
"value": 0,
"string": "0"
}
}
]
},
"power_on_time": {
"hours": 3275
},
"power_cycle_count": 10,
"temperature": {
"current": 31
},
"ata_smart_error_log": {
"summary": {
"revision": 1,
"count": 0
}
},
"ata_smart_self_test_log": {
"standard": {
"revision": 1,
"table": [
{
"type": {
"value": 3,
"string": "Conveyance offline"
},
"status": {
"value": 0,
"string": "Completed without error",
"passed": true
},
"lifetime_hours": 0
}
],
"count": 1,
"error_count_total": 0,
"error_count_outdated": 0
}
},
"ata_smart_selective_self_test_log": {
"revision": 1,
"table": [
{
"lba_min": 0,
"lba_max": 0,
"status": {
"value": 0,
"string": "Not_testing"
}
},
{
"lba_min": 0,
"lba_max": 0,
"status": {
"value": 0,
"string": "Not_testing"
}
},
{
"lba_min": 0,
"lba_max": 0,
"status": {
"value": 0,
"string": "Not_testing"
}
},
{
"lba_min": 0,
"lba_max": 0,
"status": {
"value": 0,
"string": "Not_testing"
}
},
{
"lba_min": 0,
"lba_max": 0,
"status": {
"value": 0,
"string": "Not_testing"
}
}
],
"flags": {
"value": 0,
"remainder_scan_enabled": false
},
"power_up_scan_resume_minutes": 0
}
}

View file

@ -0,0 +1,680 @@
{
"json_format_version": [
1,
0
],
"smartctl": {
"version": [
7,
4
],
"pre_release": false,
"svn_revision": "5530",
"platform_info": "x86_64-linux-6.11.6-arch1-1",
"build_info": "(local build)",
"argv": [
"smartctl",
"-ja",
"/dev/sda"
],
"drive_database_version": {
"string": "7.3/5528"
},
"exit_status": 0
},
"local_time": {
"time_t": 1731149676,
"asctime": "Sat Nov 9 13:54:36 2024 MSK"
},
"device": {
"name": "/dev/sda",
"info_name": "/dev/sda [SAT]",
"type": "sat",
"protocol": "ATA"
},
"model_family": "WD Blue / Red / Green SSDs",
"model_name": "WDC WDS100T2G0A-00JH30",
"serial_number": "20299A802244",
"wwn": {
"naa": 5,
"oui": 6980,
"id": 37501727029
},
"firmware_version": "UH510000",
"user_capacity": {
"blocks": 1953529856,
"bytes": 1000207286272
},
"logical_block_size": 512,
"physical_block_size": 512,
"rotation_rate": 0,
"form_factor": {
"ata_value": 3,
"name": "2.5 inches"
},
"trim": {
"supported": true,
"deterministic": true,
"zeroed": false
},
"in_smartctl_database": true,
"ata_version": {
"string": "ACS-2 T13/2015-D revision 3",
"major_value": 1008,
"minor_value": 272
},
"sata_version": {
"string": "SATA 3.2",
"value": 255
},
"interface_speed": {
"max": {
"sata_value": 14,
"string": "6.0 Gb/s",
"units_per_second": 60,
"bits_per_unit": 100000000
},
"current": {
"sata_value": 3,
"string": "6.0 Gb/s",
"units_per_second": 60,
"bits_per_unit": 100000000
}
},
"smart_support": {
"available": true,
"enabled": true
},
"smart_status": {
"passed": true
},
"ata_smart_data": {
"offline_data_collection": {
"status": {
"value": 0,
"string": "was never started"
},
"completion_seconds": 120
},
"self_test": {
"status": {
"value": 0,
"string": "completed without error",
"passed": true
},
"polling_minutes": {
"short": 2,
"extended": 182
}
},
"capabilities": {
"values": [
21,
3
],
"exec_offline_immediate_supported": true,
"offline_is_aborted_upon_new_cmd": true,
"offline_surface_scan_supported": false,
"self_tests_supported": true,
"conveyance_self_test_supported": false,
"selective_self_test_supported": false,
"attribute_autosave_enabled": true,
"error_logging_supported": true,
"gp_logging_supported": true
}
},
"ata_smart_attributes": {
"revision": 1,
"table": [
{
"id": 5,
"name": "Reallocated_Sector_Ct",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 9,
"name": "Power_On_Hours",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 7976,
"string": "7976"
}
},
{
"id": 12,
"name": "Power_Cycle_Count",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 1218,
"string": "1218"
}
},
{
"id": 165,
"name": "Block_Erase_Count",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 2063,
"string": "2063"
}
},
{
"id": 166,
"name": "Minimum_PE_Cycles_TLC",
"value": 100,
"worst": 100,
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 15,
"string": "15"
}
},
{
"id": 167,
"name": "Max_Bad_Blocks_per_Die",
"value": 100,
"worst": 100,
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 168,
"name": "Maximum_PE_Cycles_TLC",
"value": 100,
"worst": 100,
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 36,
"string": "36"
}
},
{
"id": 169,
"name": "Total_Bad_Blocks",
"value": 100,
"worst": 100,
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 1075,
"string": "1075"
}
},
{
"id": 170,
"name": "Grown_Bad_Blocks",
"value": 100,
"worst": 100,
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 171,
"name": "Program_Fail_Count",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 172,
"name": "Erase_Fail_Count",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 173,
"name": "Average_PE_Cycles_TLC",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 15,
"string": "15"
}
},
{
"id": 174,
"name": "Unexpected_Power_Loss",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 144,
"string": "144"
}
},
{
"id": 184,
"name": "End-to-End_Error",
"value": 100,
"worst": 100,
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 187,
"name": "Reported_Uncorrect",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 188,
"name": "Command_Timeout",
"value": 100,
"worst": 100,
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 194,
"name": "Temperature_Celsius",
"value": 70,
"worst": 58,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 34,
"string": "-O---K ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": false,
"auto_keep": true
},
"raw": {
"value": 249108103198,
"string": "30 (Min/Max 0/58)"
}
},
{
"id": 199,
"name": "UDMA_CRC_Error_Count",
"value": 100,
"worst": 100,
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
},
{
"id": 230,
"name": "Media_Wearout_Indicator",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 5879860561241,
"string": "0x055903000559"
}
},
{
"id": 232,
"name": "Available_Reservd_Space",
"value": 100,
"worst": 100,
"thresh": 5,
"when_failed": "",
"flags": {
"value": 51,
"string": "PO--CK ",
"prefailure": true,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 100,
"string": "100"
}
},
{
"id": 233,
"name": "NAND_GB_Written_TLC",
"value": 100,
"worst": 100,
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 15654,
"string": "15654"
}
},
{
"id": 234,
"name": "NAND_GB_Written_SLC",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 32244,
"string": "32244"
}
},
{
"id": 241,
"name": "Host_Writes_GiB",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 48,
"string": "----CK ",
"prefailure": false,
"updated_online": false,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 13847,
"string": "13847"
}
},
{
"id": 242,
"name": "Host_Reads_GiB",
"value": 100,
"worst": 100,
"thresh": 0,
"when_failed": "",
"flags": {
"value": 48,
"string": "----CK ",
"prefailure": false,
"updated_online": false,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 31195,
"string": "31195"
}
},
{
"id": 244,
"name": "Temp_Throttle_Status",
"value": 0,
"worst": 100,
"flags": {
"value": 50,
"string": "-O--CK ",
"prefailure": false,
"updated_online": true,
"performance": false,
"error_rate": false,
"event_count": true,
"auto_keep": true
},
"raw": {
"value": 0,
"string": "0"
}
}
]
},
"power_on_time": {
"hours": 7976
},
"power_cycle_count": 1218,
"temperature": {
"current": 30
},
"ata_smart_error_log": {
"summary": {
"revision": 1,
"count": 0
}
},
"ata_smart_self_test_log": {
"standard": {
"revision": 1,
"count": 0
}
}
}

View file

@ -0,0 +1,145 @@
{
"json_format_version": [
1,
0
],
"smartctl": {
"version": [
7,
4
],
"pre_release": false,
"svn_revision": "5530",
"platform_info": "x86_64-linux-6.11.3-arch1-1",
"build_info": "(local build)",
"argv": [
"smartctl",
"-ja",
"/dev/nvme0"
],
"exit_status": 0
},
"local_time": {
"time_t": 1731149045,
"asctime": "Sat Nov 9 13:44:05 2024 MSK"
},
"device": {
"name": "/dev/nvme0",
"info_name": "/dev/nvme0",
"type": "nvme",
"protocol": "NVMe"
},
"model_name": "Samsung SSD 970 EVO Plus 1TB",
"serial_number": "S4EWNM0W921977B",
"firmware_version": "2B2QEXM7",
"nvme_pci_vendor": {
"id": 5197,
"subsystem_id": 5197
},
"nvme_ieee_oui_identifier": 9528,
"nvme_total_capacity": 1000204886016,
"nvme_unallocated_capacity": 0,
"nvme_controller_id": 4,
"nvme_version": {
"string": "1.3",
"value": 66304
},
"nvme_number_of_namespaces": 1,
"nvme_namespaces": [
{
"id": 1,
"size": {
"blocks": 1953525168,
"bytes": 1000204886016
},
"capacity": {
"blocks": 1953525168,
"bytes": 1000204886016
},
"utilization": {
"blocks": 686279048,
"bytes": 351374872576
},
"formatted_lba_size": 512,
"eui64": {
"oui": 9528,
"ext_id": 383083641036
}
}
],
"user_capacity": {
"blocks": 1953525168,
"bytes": 1000204886016
},
"logical_block_size": 512,
"smart_support": {
"available": true,
"enabled": true
},
"smart_status": {
"passed": true,
"nvme": {
"value": 0
}
},
"nvme_smart_health_information_log": {
"critical_warning": 0,
"temperature": 47,
"available_spare": 100,
"available_spare_threshold": 10,
"percentage_used": 0,
"data_units_read": 111588,
"data_units_written": 1802957,
"host_reads": 2570341,
"host_writes": 36266417,
"controller_busy_time": 133,
"power_cycles": 31,
"power_on_hours": 432,
"unsafe_shutdowns": 18,
"media_errors": 0,
"num_err_log_entries": 63,
"warning_temp_time": 0,
"critical_comp_time": 0,
"temperature_sensors": [
47,
51
]
},
"temperature": {
"current": 47
},
"power_cycle_count": 31,
"power_on_time": {
"hours": 432
},
"nvme_error_information_log": {
"size": 64,
"read": 16,
"unread": 0,
"table": [
{
"error_count": 63,
"submission_queue_id": 0,
"command_id": 8,
"status_field": {
"value": 8194,
"do_not_retry": false,
"status_code_type": 0,
"status_code": 2,
"string": "Invalid Field in Command"
},
"phase_tag": false,
"lba": {
"value": 0
},
"nsid": 0
}
]
},
"nvme_self_test_log": {
"current_self_test_operation": {
"value": 0,
"string": "No self-test in progress"
}
}
}

View file

@ -0,0 +1,57 @@
import json
import unittest
from misc.disks import (
LVAttr,
WearoutIndicator,
WearoutReading,
_get_wearout_reading_from_smartctl_output,
)
class TestDisks(unittest.TestCase):
def test_lv_attr_declaration(self):
self.assertEqual(
LVAttr.from_str("rwi-aor---", "Data/lvol0"),
LVAttr(
vol_type=LVAttr.VolType.RAID,
permissions=LVAttr.Permissions.WRITABLE,
allocation_policy=LVAttr.AllocationPolicy.INHERITED,
fixed_minor=False,
state=LVAttr.State.ACTIVE,
is_open=LVAttr.IsOpen.OPEN,
target_type=LVAttr.TargetType.RAID,
zero_before_use=False,
health=LVAttr.Health.OK,
skip_activation=False,
name="Data/lvol0",
),
)
def test_wearout_reading_nvme_ssd(self):
with open("tests/smartctl_nvme_ssd.json") as f:
smartctl_output = json.load(f)
self.assertEqual(
_get_wearout_reading_from_smartctl_output(smartctl_output),
WearoutReading(indicator=WearoutIndicator.SPARE_BLOCKS, current_reading=100, threshold_reading=10),
)
def test_wearout_reading_ata_hdd(self):
with open("tests/smartctl_ata_hdd.json") as f:
smartctl_output = json.load(f)
self.assertEqual(
_get_wearout_reading_from_smartctl_output(smartctl_output),
WearoutReading(indicator=WearoutIndicator.REALLOCATED_SECTORS, current_reading=200, threshold_reading=140),
)
def test_wearout_reading_ata_ssd(self):
with open("tests/smartctl_ata_ssd.json") as f:
smartctl_output = json.load(f)
self.assertEqual(
_get_wearout_reading_from_smartctl_output(smartctl_output),
WearoutReading(indicator=WearoutIndicator.SPARE_BLOCKS, current_reading=100, threshold_reading=5),
)
if __name__ == "__main__":
unittest.main()

View file

@ -0,0 +1,34 @@
import unittest
from misc import vuln
class TestVuln(unittest.TestCase):
def test_parse_arch_audit_output(self):
self.assertEqual(
vuln._parse_arch_audit_output(
"""[
{"name":"AVG-2765",
"packages":["openssl"],
"status":"Vulnerable",
"type":"arbitrary command execution",
"severity":"Medium",
"fixed":null,
"issues":["CVE-2022-2068"]}
]"""
),
[
vuln.Vulnerability(
id="AVG-2765",
link="https://security.archlinux.org/AVG-2765",
vuln_type="arbitrary command execution",
packages=["openssl"],
severity=vuln.Severity.MEDIUM,
fixed=None,
)
],
)
if __name__ == "__main__":
unittest.main()

View file

@ -0,0 +1,14 @@
#!/bin/bash
mydir=$(dirname "$0")
sudo "$mydir/send_login_alert.sh"
shell=$(getent passwd $LOGNAME | cut -d: -f7)
if [ "$SSH_ORIGINAL_COMMAND" = "internal-sftp" ] # command given, so run it
then
exec /usr/lib/ssh/sftp-server
elif [[ -n $SSH_ORIGINAL_COMMAND ]]; then
exec "$shell" -c "$SSH_ORIGINAL_COMMAND"
else # no command, so interactive login shell
exec "$shell" -il
fi

View file

@ -0,0 +1,4 @@
#!/bin/bash
mydir=$(dirname "$0")
"$mydir/../.venv/bin/python" "$mydir/../send_login_alert.py" "local-only"

View file

@ -0,0 +1,4 @@
#!/bin/bash
mydir=$(dirname "$0")
"$mydir/../.venv/bin/python" "$mydir/../send_login_alert.py"