pax_global_header 0000666 0000000 0000000 00000000064 14167332244 0014520 g ustar 00root root 0000000 0000000 52 comment=83c6d6a4170492cd42f17678708ef621c4c7b4d4
journal-brief-1.1.8/ 0000775 0000000 0000000 00000000000 14167332244 0014266 5 ustar 00root root 0000000 0000000 journal-brief-1.1.8/.gitignore 0000664 0000000 0000000 00000001270 14167332244 0016256 0 ustar 00root root 0000000 0000000 # Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod~]
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/
journal-brief-1.1.8/.travis.yml 0000664 0000000 0000000 00000000511 14167332244 0016374 0 ustar 00root root 0000000 0000000 language: python
python:
- "3.6"
- "3.8"
install:
- pip install PyYAML
- pip install flexmock pytest-mock
- pip install pytest-cov coveralls
- pip install -r tests/requirements.txt
script: py.test -vv -rs tests --cov journal_brief --benchmark-skip
sudo: false
notifications:
email: false
after_success: "coveralls"
journal-brief-1.1.8/LICENSE 0000664 0000000 0000000 00000043177 14167332244 0015307 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
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
this service 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.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
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
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
journal-brief-1.1.8/MANIFEST.in 0000664 0000000 0000000 00000000310 14167332244 0016016 0 ustar 00root root 0000000 0000000 include conftest.py
include setup.py
include setup.cfg
include LICENSE
include README.md
include *.spec
recursive-include conf *.conf
recursive-include journal_brief *.py
recursive-include tests *.py
journal-brief-1.1.8/README.md 0000664 0000000 0000000 00000015656 14167332244 0015562 0 ustar 00root root 0000000 0000000 [](https://landscape.io/github/twaugh/journal-brief/master)
[](https://travis-ci.org/twaugh/journal-brief)
[](https://coveralls.io/github/twaugh/journal-brief?branch=master)
# journal-brief
Show interesting new systemd journal entries since last run.
This can be run from cron to get a briefing of journal entries sent by
email. Example:
```
$ cat /etc/cron.daily/journal-brief
#!/bin/sh
exec journal-brief -p err
```
By maintaining a bookmark of the last journal entry processed,
journal-brief is able to carry on processing journal entries from
where it left off last time, ensuring no duplicates and no missed
journal entries.
## Install
### From git
```
python3 setup.py install
```
### From PyPI
```
pip3 install journal-brief
```
### On Fedora
```
dnf install journal-brief
```
## Quick start
One useful feature of journal-brief is that it can generate its own
configuration of which journal entries to ignore. Most of the messages
you are likely to want to ignore will come from booting or shutting
down. Here is the procedure for ignoring those messages:
#### 1. Run journal-brief for the first time, ignoring its output:
```
journal-brief -b >/dev/null
```
This will cause the journal bookmark to be updated to the end of the
journal.
#### 2. Reboot
#### 3. Run journal-brief in debrief mode, to generate configuration:
```
journal-brief -p err debrief > ~/.config/journal-brief/journal-brief.conf
```
#### 4. Adjust to taste
Look through `~/.config/journal-brief/journal-brief.conf` to check
that the exclusions make sense and remove any that do not.
## Configuration
A YAML configuration in `~/.config/journal-brief/journal-brief.conf`
defines which journal entries should be shown.
### Inclusions
Each inclusion is defined by a list of journal fields and their
possible matches. All fields defined in an inclusion must match at
least one of their possible match values for an entry to be included.
For example, the configuration below matches all entries of priority 3
(err) or lower (like `journalctl -p err`), but also includes entries
of priority 6 or lower from the specified systemd unit (like
`journalctl -p info -u myservice.service`):
```yaml
inclusions:
- PRIORITY: [0, 1, 2, 3]
- PRIORITY: [4, 5, 6]
_SYSTEMD_UNIT: [myservice.service]
```
The `priority` configuration parameter sets the log level to add to
all inclusions, and if the PRIORITY field match is not a list it is
matched as a maximum value so the above could be written as:
```yaml
priority: err
inclusions:
- PRIORITY: info
_SYSTEMD_UNIT: [myservice.service]
```
### Exclusions
Each exclusion is defined by a list of journal fields and their
possible matches. All fields in an exclusion must match at least one
of their possible match values for an entry to be excluded.
For example:
```yaml
exclusions:
- MESSAGE:
- exclude this
- exclude this too
SYSLOG_IDENTIFIER:
- from here
- MESSAGE_ID: [c7a787079b354eaaa9e77b371893cd27]
- MESSAGE: ["/Normal exit (.*run)/"]
```
This would cause `journal-brief` to ignore journal entries that
satisfy both conditions: `SYSLOG_IDENTIFIER` is `from here`, and
`MESSAGE` is either `exclude this` or `exclude this too`.
It will also ignore any entries with the specified `MESSAGE_ID`.
In addition, any entries whose `MESSAGE` matches the (Python) regular
expression `Normal exit (.*run)` will be excluded. Regular expressions
are indicated with `/` at the beginning and end of the match string,
and are used for matching (not searching) against the field in
question at the beginning of the field's string value.
The available journal fields are described in the
systemd.journal-fields(7) manual page.
#### Test exclusion rules
You can run `journal-brief --dry-run -b stats` to see how many times
each exclusion rule has excluded messages, based on all messages from
the current boot. The `--dry-run` parameter skips updating the
bookmark, so you can edit the exclusion rules and try again, comparing
output.
#### Automatically create exclusion rules
To create exclusion rules, rather than showing journal entries, run
`journal-brief --dry-run debrief`.
## Email
The standard behavior of journal-brief is to send the desired journal
entries to the standard output, but if desired it can be configured to
send them via email instead. To do this, add an `email` section to the
configuration file. There are two ways that email can be sent: through
a command which implements the normal `mail` interface, or directly
via SMTP.
### Configuration keys
* `suppress_empty`: if true, no email will be sent unless matching journal
entries are found (defaults to `true`)
* `from`: RFC-5322 format address to be used as the sender address (required)
* `to`: RFC-5322 format address to be used as the recipient address, or a list
of such addresses (required)
* `cc`: RFC-5322 format address to be used as a carbon-copy address,
or a list of such addresses
* `bcc`: RFC-5322 format address to be used as a blind-carbon-copy address,
or a list of such addresses
* `subject`: string to be used as the email message subject
* `headers`: dictionary of string keys and string values to be added as
custom headers; the dictionary cannot include 'From', 'To', 'Cc', or 'Bcc'
Either command-based or SMTP-based delivery must be specified (but not both).
### Email via command
Example:
```yaml
email:
from: "journal sender"
to: "system admin"
command: "sendmail -i -t"
```
This will cause journal-brief to execute the specified command in a
child process and pipe the formatted email message to it. The supplied
command string will be executed via the shell (typically identified in the
`SHELL` environment variable) so it can make use of shell expansions and
other features.
### Email via SMTP
Example:
```yaml
email:
from: "journal sender"
to: "system admin"
smtp: {}
```
This will cause journal-brief to use the Python `smtplib` module to send
the formatted email message.
Note the usage of YAML 'flow' style to specify an empty mapping for the
'smtp' configuration, allowing all of the defaults to be used. This is only
necessary when no SMTP-specific configuration keys are specified.
#### Email SMTP configuration keys
* `host`: hostname or address of the SMTP server to use for sending email
(defaults to `localhost`)
* `port`: port number to connect to on the SMTP server (defaults to `25`)
* `starttls`: boolean value indicating whether STARTTLS should be used to
secure the connection to the SMTP server (defaults to `false`)
* `user`: username to be used to authenticate to the SMTP server
* `password`: password to be used to authenticate to the SMTP server (only
used if `user` is specified)
journal-brief-1.1.8/conf/ 0000775 0000000 0000000 00000000000 14167332244 0015213 5 ustar 00root root 0000000 0000000 journal-brief-1.1.8/conf/journal-brief.conf 0000664 0000000 0000000 00000000513 14167332244 0020620 0 ustar 00root root 0000000 0000000 # cursor-file: cursor
# inclusions:
# # like journalctl -p err
# - PRIORITY: err
# # like journalctl -p info -u myservice.service
# - PRIORITY: info
# _SYSTEMD_UNIT: [myservice.service]
# exclusions:
# - MESSAGE:
# - exclude this
# - and this
# SYSLOG_IDENTIFIER:
# - from here
# - MESSAGE:
# - and this, from anywhere
journal-brief-1.1.8/conftest.py 0000664 0000000 0000000 00000000036 14167332244 0016464 0 ustar 00root root 0000000 0000000 collect_ignore = ['setup.py']
journal-brief-1.1.8/journal_brief/ 0000775 0000000 0000000 00000000000 14167332244 0017107 5 ustar 00root root 0000000 0000000 journal-brief-1.1.8/journal_brief/__init__.py 0000664 0000000 0000000 00000002324 14167332244 0021221 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015, 2020 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from journal_brief.journal_brief import SelectiveReader, LatestJournalEntries
from journal_brief.filter import JournalFilter
from journal_brief.format import list_formatters, get_formatter
from journal_brief.config import Config
__all__ = ['SelectiveReader', 'LatestJournalEntries',
'JournalFilter',
'list_formatters', 'get_formatter',
'Config']
__version__ = '1.1.8' # also update setup.py and python-journal-brief.spec
journal-brief-1.1.8/journal_brief/cli/ 0000775 0000000 0000000 00000000000 14167332244 0017656 5 ustar 00root root 0000000 0000000 journal-brief-1.1.8/journal_brief/cli/__init__.py 0000664 0000000 0000000 00000000000 14167332244 0021755 0 ustar 00root root 0000000 0000000 journal-brief-1.1.8/journal_brief/cli/constants.py 0000664 0000000 0000000 00000001555 14167332244 0022252 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2020 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
EMAIL_SUPPRESS_EMPTY_TEXT = 'No matching entries found in journal.\n'
EMAIL_DRY_RUN_SEPARATOR = '------'
journal-brief-1.1.8/journal_brief/cli/main.py 0000664 0000000 0000000 00000030210 14167332244 0021150 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015, 2020 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
import argparse
from email.mime.text import MIMEText
from email import charset
import io
from locale import setlocale, LC_ALL
import logging
import os
import signal
from smtplib import SMTP
import ssl
import subprocess
import sys
from journal_brief import (SelectiveReader,
LatestJournalEntries,
get_formatter,
list_formatters,
JournalFilter,
__version__ as journal_brief_version)
from journal_brief.cli.constants import (EMAIL_SUPPRESS_EMPTY_TEXT,
EMAIL_DRY_RUN_SEPARATOR)
from journal_brief.config import Config, ConfigError
from journal_brief.constants import PACKAGE, CONFIG_DIR, PRIORITY_MAP
import journal_brief.format.config # registers class; # noqa: F401
import journal_brief.format.short # registers class; # noqa: F401
import journal_brief.format.json # registers class; # noqa: F401
import journal_brief.format.reboot # registers class; # noqa: F401
import journal_brief.format.login # registers class; # noqa: F401
import journal_brief.format.systemd # registers class; # noqa: F401
log = logging.getLogger('cli')
class InstanceConfig(object):
def __init__(self, config, args):
self.config = config
if args.output is not None:
args.output = args.output.split(',')
self.args = args
def get(self, key, default_value=None):
config_key = key.replace('_', '-')
args_key = key.replace('-', '_')
try:
value = getattr(self.args, args_key)
log.debug("%s=%r from args", args_key, value)
except AttributeError:
value = None
finally:
if value is None:
value = self.config.get(config_key, default_value)
if value is not None:
log.debug("%s=%r from config", args_key, value)
return value
class NullStream(object):
def write(self, data):
pass
class CLI(object):
def __init__(self, args=None):
self.args = self.get_args(args or sys.argv[1:])
config = Config(config_file=self.args.conf)
self.config = InstanceConfig(config, self.args)
self.default_output_formats = ['reboot', 'short']
self.cursor_file = None
self.log_level = None
@staticmethod
def get_args(args):
description = 'Show new journal entries since last run'
parser = argparse.ArgumentParser(description=description)
parser.add_argument('-b', action='store_true', default=False,
help='process all entries from the current boot')
parser.add_argument('-p', '--priority', metavar='PRI',
help='show entries at priority PRI and lower',
choices=['emerg', 'alert', 'crit', 'err',
'warning', 'notice', 'info', 'debug'])
parser.add_argument('--conf', metavar='FILE',
help='use FILE as config file')
parser.add_argument('--debug', action='store_true', default=False,
help='enable debugging')
parser.add_argument('--dry-run', action='store_true', default=False,
help='do not update cursor bookmark file')
helptxt = ('output format for journal entries, '
'comma-separated list from {0}'.format(list_formatters()))
parser.add_argument('-o', '--output', metavar='FORMAT', help=helptxt)
parser.add_argument('--help-output', action='store_true',
default=False,
help='display information about output formats')
cmds = parser.add_subparsers(dest='cmd')
cmds.add_parser('debrief', help='create exclusions config')
cmds.add_parser('reset', help='reset cursor bookmark and exit')
cmds.add_parser('stats', help='show statistics')
return parser.parse_args(args)
def show_stats(self, jfilter):
jfilter.format(NullStream())
stats = jfilter.get_statistics()
log.debug("stats: %r", stats)
strf = "{FREQ:>10} {EXCLUSION}"
print(strf.format(FREQ='FREQUENCY', EXCLUSION='EXCLUSION'))
for stat in stats:
print(strf.format(FREQ=stat.hits,
EXCLUSION=repr(dict(stat.exclusion))))
def show_output_help(self):
"""
Respond to --help-output
"""
print("Available output formats:")
for output in list_formatters():
print("\n{0}:".format(output))
formatter = get_formatter(output)
docstring = [line.strip()
for line in formatter.__doc__.splitlines()]
while docstring and not docstring[0]:
del docstring[0]
while docstring and not docstring[-1]:
del docstring[-1]
print('\n'.join([' ' + line for line in docstring]))
print("\nMultiple output formats can be used at the same time.")
print("The default is '{0}'".format(','.join(self.default_output_formats)))
def reset(self):
"""
Remove the cursor file
"""
log.debug('reset: removing %r', self.cursor_file)
try:
os.unlink(self.cursor_file)
except IOError:
pass
def handle_options(self):
"""
Deal with options and sub-commands
:return: bool, whether to exit
"""
if self.args.help_output:
self.show_output_help()
return True
if self.config.get('debug'):
logging.basicConfig(level=logging.DEBUG)
self.cursor_file = self.config.get('cursor-file')
if not self.cursor_file.startswith('/'):
self.cursor_file = os.path.join(CONFIG_DIR, self.cursor_file)
log.debug("cursor-file=%r", self.cursor_file)
if self.args.cmd == 'reset':
self.reset()
return True
priority = self.config.get('priority')
if priority:
self.log_level = int(PRIORITY_MAP[priority])
log.debug("priority=%r from args/config", self.log_level)
return False
def get_formatters(self):
"""
Build the list of formatters we'll use
:return: list, EntryFormatter instances
"""
if self.args.cmd == 'debrief':
formatters = [get_formatter('config')]
else:
outputs = self.config.get('output', self.default_output_formats)
try:
formatters = [get_formatter(output) for output in outputs]
except KeyError as ex:
sys.stderr.write("{0}: invalid output format '{1}'\n"
.format(PACKAGE, ex.args[0]))
sys.exit(1)
return formatters
def send_email(self, output):
email = self.config.get('email')
if not output:
if not email['suppress_empty']:
output = EMAIL_SUPPRESS_EMPTY_TEXT
else:
return
if not self.config.get('mime-email'):
# old-style non-MIME delivery through command
if self.args.dry_run:
print("Email to be delivered via '{0}'".format(email['command']))
print(EMAIL_DRY_RUN_SEPARATOR)
print(output)
else:
subprocess.run(email['command'], shell=True, check=True, text=True, input=output)
return
charset.add_charset('utf-8', charset.QP, charset.QP)
message = MIMEText(output, _charset='utf-8')
message['X-Journal-Brief-Version'] = journal_brief_version
message['From'] = email['from']
message['To'] = ', '.join(email['to'])
if 'subject' in email:
message['Subject'] = email['subject']
if 'cc' in email:
message['Cc'] = ', '.join(email['cc'])
if 'bcc' in email:
message['Bcc'] = ', '.join(email['bcc'])
if 'headers' in email:
for header, value in email['headers'].items():
message[header] = value
if 'command' in email: # delivery through command
if self.args.dry_run:
print("Email to be delivered via '{0}'".format(email['command']))
print(EMAIL_DRY_RUN_SEPARATOR)
print(str(message))
else:
subprocess.run(email['command'], shell=True, check=True, text=True, input=str(message))
else: # delivery via SMTP
smtp = email['smtp']
if self.args.dry_run:
print("Email to be delivered via SMTP to {0} port {1}".format(
smtp.get('host', 'localhost'),
smtp.get('port', '25')))
print(EMAIL_DRY_RUN_SEPARATOR)
print(message)
else:
with SMTP(smtp.get('host'), smtp.get('port', 0)) as sender:
if smtp.get('starttls', False):
sender.starttls(context=ssl.create_default_context())
if 'user' in smtp:
sender.login(smtp.get('user'), smtp.get('password'))
sender.send_message(message)
def run(self):
if self.handle_options():
return
setlocale(LC_ALL, '')
formatters = self.get_formatters()
if any(formatter.FILTER_INCLUSIONS is None
for formatter in formatters):
default_inclusions = self.config.get('inclusions')
else:
# None of our formatters need the inclusions from config
default_inclusions = None
if default_inclusions:
inclusions = default_inclusions[:]
else:
inclusions = []
explicit_inclusions = []
for formatter in formatters:
if formatter.FILTER_INCLUSIONS is not None:
explicit_inclusions.extend(formatter.FILTER_INCLUSIONS)
reader = SelectiveReader(this_boot=self.args.b,
log_level=self.log_level,
inclusions=inclusions,
explicit_inclusions=explicit_inclusions)
with LatestJournalEntries(cursor_file=self.cursor_file,
reader=reader,
dry_run=self.args.dry_run,
seek_cursor=not self.args.b) as entries:
exclusions = self.config.get('exclusions', [])
jfilter = JournalFilter(entries, formatters,
default_inclusions=default_inclusions,
default_exclusions=exclusions)
if self.args.cmd == 'stats':
self.show_stats(jfilter)
elif self.config.get('email') is None:
jfilter.format(sys.stdout)
else:
output_stream = io.StringIO()
jfilter.format(output_stream)
output = output_stream.getvalue()
output_stream.close()
self.send_email(output)
def run():
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
try:
CLI().run()
except KeyboardInterrupt:
pass
except IOError as ex:
sys.stderr.write("{0}: {1}\n".format(PACKAGE, ex))
sys.exit(1)
except ConfigError:
sys.exit(1)
if __name__ == '__main__':
run()
journal-brief-1.1.8/journal_brief/config.py 0000664 0000000 0000000 00000040371 14167332244 0020733 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015, 2020 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
import errno
from journal_brief import list_formatters
from journal_brief.constants import CONFIG_DIR, PACKAGE, PRIORITY_MAP
from logging import getLogger
import os
import re
import sre_constants
import yaml
log = getLogger(__name__)
class ConfigError(Exception):
pass
class SyntaxError(ConfigError):
def __init__(self, config_file, scanner_error):
super(SyntaxError, self).__init__(scanner_error.problem)
self.scanner_error = scanner_error
with open(config_file, 'rt') as cfp:
self.config_lines = cfp.readlines()
def __str__(self):
mark = self.scanner_error.problem_mark
ret = ('{sev}: {problem}\n'
' in "{file}", line {line}, column {column}:\n'.format(
sev='error',
problem=self.scanner_error.problem,
file=mark.name,
line=mark.line,
column=mark.column))
assert mark.line > 0
index = mark.line - 1
assert index < len(self.config_lines)
ret += self.config_lines[index]
assert mark.column > 0
ret += ' ' * (mark.column - 1) + '^'
return ret
class SemanticError(ConfigError):
def __init__(self, message, item, conf, index=None):
super(SemanticError, self).__init__(message)
self.message = message
self.item = item
self.conf = conf
self.index = index
def __str__(self):
conf = yaml.dump(self.conf,
indent=2,
default_flow_style=False)
if self.index is None:
at = ''
else:
at = 'at item {index}, '.format(index=self.index)
if self.index > 0:
conflines = conf.split('\n')
conflines.insert(1, '(...)')
conf = '\n'.join(conflines)
return "{sev}: {item}: {message}\n {at}in:\n{conf}".format(
sev='error',
item=self.item,
message=self.message,
at=at,
conf=conf
)
def load_config(config_file):
try:
with open(config_file) as config_fp:
try:
config = yaml.safe_load(config_fp)
except yaml.scanner.ScannerError as scanner_error:
err = SyntaxError(config_file,
scanner_error)
log.error(err)
raise err from scanner_error
if not config:
config = {}
return config
except IOError as ex:
if ex.errno != errno.ENOENT:
raise
return {}
class Config(dict):
ALLOWED_KEYWORDS = {
'cursor-file',
'debug',
'exclusions',
'inclusions',
'output',
'priority',
'email',
}
def __init__(self, config_file=None):
if not config_file:
conf_filename = '{0}.conf'.format(PACKAGE)
config_file = os.path.join(CONFIG_DIR, conf_filename)
default_config = {'cursor-file': 'cursor'}
config = load_config(config_file)
if not isinstance(config, dict):
error = SemanticError('must be a map', 'top level', config)
log.error(error)
raise error
default_config.update(config)
super(Config, self).__init__(default_config)
exceptions = list(self.validate())
for exception in exceptions:
log.error("%s", exception)
if exceptions:
raise exceptions[0]
def validate(self):
valid_prios = [prio for prio in PRIORITY_MAP.keys()
if isinstance(prio, str)]
valid_prios.sort()
for errors in [self.validate_allowed_keywords(),
self.validate_cursor_file(),
self.validate_debug(),
self.validate_inclusions_or_exclusions(valid_prios,
'exclusions'),
self.validate_inclusions_or_exclusions(valid_prios,
'inclusions'),
self.validate_output(),
self.validate_priority(valid_prios),
self.validate_email()]:
for error in errors:
yield error
def validate_allowed_keywords(self):
for unexpected_key in set(self) - self.ALLOWED_KEYWORDS:
yield SemanticError('unexpected keyword', unexpected_key,
{unexpected_key: self[unexpected_key]})
def validate_cursor_file(self):
if 'cursor-file' not in self:
return
if not (isinstance(self['cursor-file'], str) or
isinstance(self['cursor-file'], int)):
yield SemanticError('expected string', 'cursor-file',
{'cursor-file': self['cursor-file']})
def validate_debug(self):
if 'debug' not in self:
return
if not (isinstance(self['debug'], bool) or
isinstance(self['debug'], int)):
yield SemanticError('expected bool', 'debug',
{'debug': self['debug']})
def validate_email(self):
ALLOWED_EMAIL_KEYWORDS = {
'bcc',
'cc',
'command',
'from',
'headers',
'smtp',
'subject',
'suppress_empty',
'to',
}
ALLOWED_SMTP_KEYWORDS = {
'host',
'password',
'port',
'starttls',
'user',
}
DISALLOWED_HEADERS = {
'From'.casefold(),
'To'.casefold(),
'Cc'.casefold(),
'Bcc'.casefold(),
}
if 'email' not in self:
return
email = self.get('email')
self['mime-email'] = True
if not isinstance(email, dict):
yield SemanticError('must be a map', 'email',
{'email': email})
return
for unexpected_key in set(email) - ALLOWED_EMAIL_KEYWORDS:
yield SemanticError('unexpected \'email\' keyword', unexpected_key,
{unexpected_key: email[unexpected_key]})
if 'suppress_empty' in email:
if not (isinstance(email['suppress_empty'], bool)
or isinstance(email['suppress_empty'], int)):
yield SemanticError('expected bool', 'suppress_empty',
{'email': {'suppress_empty': email['suppress_empty']}})
else:
email['suppress_empty'] = True
if ('smtp' in email and 'command' in email):
yield SemanticError('cannot specify both smtp and command', 'email',
{'email':
{'command': email['command'],
'smtp': email['smtp']}})
if not ('smtp' in email or 'command' in email):
yield SemanticError('either smtp or command must be specified', 'email',
{'email': email})
if 'command' in email:
if not isinstance(email['command'], str):
yield SemanticError('expected string', 'command',
{'email': {'command': email['command']}})
# allow old-style non-MIME configuration for command delivery
if not ('from' in email or 'to' in email):
self['mime-email'] = False
if 'smtp' in email:
smtp = email['smtp']
# convert old-style configuration to new-style
for key in ['from', 'to', 'cc', 'bcc', 'subject', 'headers']:
if key in smtp:
email[key] = smtp.pop(key)
if not isinstance(smtp, dict):
yield SemanticError('must be a map', 'smtp',
{'email': {'smtp': smtp}})
return
for unexpected_key in set(smtp) - ALLOWED_SMTP_KEYWORDS:
yield SemanticError('unexpected \'smtp\' keyword', unexpected_key,
{unexpected_key: smtp[unexpected_key]})
if ('host' in smtp and
not isinstance(smtp['host'], str)):
yield SemanticError('expected string', 'host',
{'smtp': {'host': smtp['host']}})
if ('port' in smtp and
not isinstance(smtp['port'], int)):
yield SemanticError('expected int', 'port',
{'smtp': {'port': smtp['port']}})
if ('starttls' in smtp and
not (isinstance(smtp['starttls'], bool) or
isinstance(smtp['starttls'], int))):
yield SemanticError('expected bool', 'starttls',
{'smtp': {'starttls': smtp['starttls']}})
if ('user' in smtp and
not isinstance(smtp['user'], str)):
yield SemanticError('expected string', 'user',
{'smtp': {'user': smtp['user']}})
if ('password' in smtp and
not isinstance(smtp['password'], str)):
yield SemanticError('expected string', 'password',
{'smtp': {'password': smtp['password']}})
if not self['mime-email']:
return
if 'from' not in email:
yield SemanticError('\'email\' map must include \'from\'', 'email',
{'email': email})
else:
if not isinstance(email['from'], str):
yield SemanticError('expected string', 'from',
{'email': {'from': email['from']}})
if 'to' not in email:
yield SemanticError('\'email\' map must include \'to\'', 'email',
{'email': email})
else:
if isinstance(email['to'], list):
pass
elif isinstance(email['to'], str):
email['to'] = [email['to']]
else:
yield SemanticError('expected list or string', 'to',
{'email': {'to': email['to']}})
if 'cc' in email:
if isinstance(email['cc'], list):
pass
elif isinstance(email['cc'], str):
email['cc'] = [email['cc']]
else:
yield SemanticError('expected list or string', 'cc',
{'email': {'cc': email['cc']}})
if 'bcc' in email:
if isinstance(email['bcc'], list):
pass
elif isinstance(email['bcc'], str):
email['bcc'] = [email['bcc']]
else:
yield SemanticError('expected list or string', 'bcc',
{'email': {'bcc': email['bcc']}})
if ('subject' in email and
not isinstance(email['subject'], str)):
yield SemanticError('expected string', 'subject',
{'email': {'subject': email['subject']}})
if 'headers' in email:
if not isinstance(email['headers'], dict):
yield SemanticError('expected dict', 'headers',
{'email': {'headers': email['headers']}})
else:
for key in email['headers'].keys():
if key.casefold() in DISALLOWED_HEADERS:
yield SemanticError("Header " + key + " cannot not be specified here", 'headers',
{'email': {'headers': email['headers']}})
def validate_output(self):
if 'output' not in self:
return
formatters = list_formatters()
output = self['output']
if isinstance(output, list):
outputs = output
else:
outputs = [output]
self['output'] = outputs
for output in outputs:
if output not in formatters:
yield SemanticError('invalid output format, must be in %s' %
formatters, output,
{'output': self['output']})
def validate_priority(self, valid_prios):
if 'priority' not in self:
return
try:
valid = self['priority'] in PRIORITY_MAP
except TypeError:
valid = False
finally:
if not valid:
yield SemanticError('invalid priority, must be in %s' %
valid_prios, 'priority',
{'priority': self['priority']})
def validate_inclusions_or_exclusions(self, valid_prios, key):
if key not in self:
return
if not isinstance(self[key], list):
yield SemanticError('must be a list', key,
{key: self[key]})
return
for error in self.find_bad_rules(valid_prios, key):
yield error
def priority_rule_is_valid(self, values):
try:
if isinstance(values, list):
valid = all(value in PRIORITY_MAP
for value in values)
else:
valid = values in PRIORITY_MAP
except TypeError:
valid = False
finally:
return valid
def find_bad_rule_values(self, key, index, field, values):
for value in values:
if isinstance(value, list) or isinstance(value, dict):
yield SemanticError('must be a string', value,
{key: [{field: values}]},
index=index)
continue
if (key == 'exclusions' and
isinstance(value, str) and
value.startswith('/') and
value.endswith('/')):
try:
# TODO: use this computed value
re.compile(value[1:-1])
except sre_constants.error as ex:
yield SemanticError(ex.args[0], value,
{key: [{field: values}]},
index=index)
def find_bad_rules(self, valid_prios, key):
log.debug("%s:", key)
for index, rule in enumerate(self[key]):
if not isinstance(rule, dict):
yield SemanticError('must be a map', key, {key: [rule]}, index)
continue
log.debug('-')
for field, values in rule.items():
log.debug("%s: %r", field, values)
if field == 'PRIORITY':
if not self.priority_rule_is_valid(values):
message = ('must be list or priority (%s)' %
valid_prios)
yield SemanticError(message, field,
{key: [{field: values}]},
index=index)
continue
if not isinstance(values, list):
yield SemanticError('must be a list', field,
{key: [{field: values}]},
index=index)
continue
for error in self.find_bad_rule_values(key, index,
field, values):
yield error
journal-brief-1.1.8/journal_brief/constants.py 0000664 0000000 0000000 00000002172 14167332244 0021477 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
import os
from systemd import journal
CONFIG_DIR = '{0}/.config/journal-brief'.format(os.path.expanduser('~'))
PACKAGE = 'journal-brief'
PRIORITY_MAP = {}
for attr in dir(journal):
if attr.startswith('LOG_'):
value = getattr(journal, attr)
svalue = str(value)
for key in [value, svalue, attr[4:].lower()]:
PRIORITY_MAP[key] = value
journal-brief-1.1.8/journal_brief/filter.py 0000664 0000000 0000000 00000025144 14167332244 0020754 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from collections import namedtuple
from journal_brief.constants import PRIORITY_MAP
from logging import getLogger
import re
from systemd import journal
from uuid import UUID
import yaml
log = getLogger(__name__)
# Statistics about an exclusion filter rule
ExclusionStatistics = namedtuple('ExclusionStatistics', ['hits', 'exclusion'])
# A set of inclusion and exclusion filter rules
FilterRules = namedtuple('FilterRules', ['inclusions', 'exclusions'])
def coerce_to_UUID(x):
if isinstance(x, UUID):
return x
return UUID(x)
DEFAULT_CONVERTERS = journal.DEFAULT_CONVERTERS.copy()
DEFAULT_CONVERTERS.update({
'_BOOT_ID': coerce_to_UUID,
'_MACHINE_ID': coerce_to_UUID,
'MESSAGE_ID': coerce_to_UUID,
})
class FilterRule(dict):
"""
A mapping of field names to values that are significant for that field
"""
def __init__(self, mapping):
assert isinstance(mapping, dict)
# Make sure everything is interpreted as the appropriate type
type_mapping = {}
for field, matches in mapping.items():
converter = DEFAULT_CONVERTERS.get(field, str)
if field == 'PRIORITY':
try:
level = int(PRIORITY_MAP[matches])
except (AttributeError, TypeError):
type_mapping[field] = [converter(PRIORITY_MAP[match])
for match in matches]
else:
type_mapping[field] = [converter(prio)
for prio in list(range(level + 1))]
else:
type_mapping[field] = [converter(match) for match in matches]
super(FilterRule, self).__init__(type_mapping)
def __str__(self):
rdict = {}
for field, matches in self.items():
if any(isinstance(match, UUID) for match in matches):
# Convert UUID to str for representation
rdict[field] = [str(match) for match in matches]
else:
rdict[field] = matches
return yaml.dump([rdict],
indent=2,
default_flow_style=False)
def value_matches(self, field, index, match, value):
return match == value
def matches(self, entry):
for field, matches in self.items():
if not any(self.value_matches(field, index, match, entry.get(field))
for index, match in enumerate(matches)):
# No match for this field
return False
return True
class Inclusion(FilterRule):
"""
Filter rule for including entries
Initialise it with a mapping of field names to possible values.
>>> rule = {'FIELD': ['VALUE'], 'FIELD1': ['VALUE1', 'VALUE2']}
>>> incl = Inclusion(rule)
All fields must match one of their possible values.
>>> assert not incl.matches({'FIELD': 'VALUE'})
>>> assert incl.matches({'FIELD': 'VALUE', 'FIELD1': 'VALUE1'})
>>> assert incl.matches({'FIELD': 'VALUE', 'FIELD1': 'VALUE2'})
"""
def __repr__(self):
return "Inclusion(%s)" % super(Inclusion, self).__repr__()
class Exclusion(FilterRule):
"""
Filter rule for excluding entries
Initialise it with a mapping of field names to possible values.
>>> rule = {'FIELD': ['VALUE'], 'FIELD1': ['VALUE1', 'VALUE2']}
>>> excl = Exclusion(rule)
All fields must match one of their possible values.
>>> assert not excl.matches({'FIELD': 'VALUE'})
>>> assert excl.matches({'FIELD': 'VALUE', 'FIELD1': 'VALUE1'})
>>> assert excl.matches({'FIELD': 'VALUE', 'FIELD1': 'VALUE2'})
Regular expressions are allowed.
>>> excl = Exclusion({'MESSAGE': ['/exclude/']})
>>> assert excl.matches({'MESSAGE': 'exclude this'})
Regular expressions are matched at the beginning of the string.
>>> assert not excl.matches({'MESSAGE': "don't exclude this"})
"""
def __init__(self, mapping, comment=None):
super(Exclusion, self).__init__(mapping)
# Make sure everything is interpreted as a string
log.debug("new exclusion rule:")
for field, matches in mapping.items():
log.debug("%s=%r", field, matches)
self.hits = 0
self.regexp = {} # field -> index -> compiled regexp
self.comment = comment
def __repr__(self):
return "Exclusion(%s)" % super(Exclusion, self).__repr__()
def __str__(self):
ret = ''
if self.comment:
ret += '# {0}\n'.format(self.comment)
ret += super(Exclusion, self).__str__()
return ret
def value_matches(self, field, index, match, value):
try:
regexp = self.regexp[field][index]
if regexp is not None:
log.debug('using cached regexp for %s[%d]:%s',
field, index, match)
except KeyError:
try:
if match.startswith('/') and match.endswith('/'):
pattern = match[1:-1]
log.debug('compiling pattern %r', pattern)
regexp = re.compile(pattern)
else:
regexp = None
log.debug('%r is not a regex', match)
except AttributeError:
regexp = None
log.debug('%r is not a regex', match)
self.regexp.setdefault(field, {})
self.regexp[field][index] = regexp
if regexp is not None:
try:
return regexp.match(value)
except TypeError:
# Can't regexp match against a non-string value
return False
return super(Exclusion, self).value_matches(field, index, match, value)
def matches(self, entry):
matched = super(Exclusion, self).matches(entry)
if matched:
log.debug("excluding entry")
self.hits += 1
return matched
class JournalFilter(object):
"""
Apply filter rules to journal entries for a list of formatters
Provide a list of default filter rules for inclusion and
exclusion. Each filter rule is a dict whose keys are fields which
must all match an entry to be excluded.
The dict value for each field is a list of possible match values,
any of which may match.
For exclusions, regular expressions are indicated with '/' at the
beginning and end of the match string. Regular expressions are
matched at the start of the journal field value (i.e. it's a match
not a search).
"""
def __init__(self,
iterator,
formatters,
default_inclusions=None,
default_exclusions=None):
"""
Constructor
:param iterator: iterator, providing journal entries
:param formatters: list, EntryFormatter instances
:param default_inclusions: list, dicts of field -> values for inclusion
:param default_exclusions: list, dicts of field -> values for exclusion
"""
super(JournalFilter, self).__init__()
self.iterator = iterator
self.formatters = formatters
self.filter_rules = {}
default_inclusions = [Inclusion(incl)
for incl in default_inclusions or []]
self.default_exclusions = [Exclusion(excl)
for excl in default_exclusions or []]
# Initialise filters
for formatter in formatters:
name = formatter.FORMAT_NAME
if formatter.FILTER_INCLUSIONS or formatter.FILTER_EXCLUSIONS:
inclusions = [Inclusion(incl)
for incl in formatter.FILTER_INCLUSIONS or []]
exclusions = [Exclusion(excl)
for excl in formatter.FILTER_EXCLUSIONS or []]
else:
inclusions = default_inclusions
exclusions = self.default_exclusions
rules = FilterRules(inclusions=inclusions,
exclusions=exclusions)
self.filter_rules[name] = rules
def format(self, stream):
try:
for entry in self.iterator:
default_excl = None
for formatter in self.formatters:
rules = self.filter_rules[formatter.FORMAT_NAME]
inclusions = rules.inclusions
if inclusions and not any(inclusion.matches(entry)
for inclusion in inclusions):
# Doesn't match an inclusion rule
continue
if default_excl is None:
# Only match against the default exclusions
# once per message, for efficiency and for
# better statistics gathering
default_excl = any(excl.matches(entry)
for excl in self.default_exclusions)
exclusions = rules.exclusions
if exclusions is self.default_exclusions and default_excl:
# No special rules, matches a default exclusion rule
continue
if any(excl.matches(entry) for excl in exclusions):
# Matches one of the formatter's exclusion rules
continue
stream.write(formatter.format(entry) or '')
finally:
for formatter in self.formatters:
stream.write(formatter.flush() or '')
def get_statistics(self):
"""
Get filter statistics
:return: list, ExclusionStatistics instances in reverse order
"""
stats = [ExclusionStatistics(excl.hits, excl)
for excl in self.default_exclusions]
stats.sort(reverse=True, key=lambda stat: stat.hits)
return stats
journal-brief-1.1.8/journal_brief/format/ 0000775 0000000 0000000 00000000000 14167332244 0020377 5 ustar 00root root 0000000 0000000 journal-brief-1.1.8/journal_brief/format/__init__.py 0000664 0000000 0000000 00000005333 14167332244 0022514 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
import logging
log = logging.getLogger(__name__)
FORMATTERS = {}
def list_formatters():
return list(FORMATTERS.keys())
def get_formatter(name, *args, **kwargs):
"""
Get a new formatter instance by name
"""
return FORMATTERS[name](*args, **kwargs)
class RegisteredFormatter(type):
"""
Metaclass for EntryFormatter, registering for use with get_formatter()
"""
def __new__(meta, name, bases, class_dict):
cls = type.__new__(meta, name, bases, class_dict)
FORMATTERS[class_dict['FORMAT_NAME']] = cls
return cls
class EntryFormatter(object, metaclass=RegisteredFormatter):
# Base class for output format implementations
# Class docstring is used for help output to describe the output
# format:
"""
Only display MESSAGE field
"""
# This is the name used to select the output format, collected
# automatically by the metaclass and used by list_formatters(),
# get_formatter(), and the CLI '-o' parameter:
FORMAT_NAME = 'cat'
# The formatter can either use the inclusions and exclusions
# listed in the config file:
FILTER_INCLUSIONS = None
FILTER_EXCLUSIONS = None
# or else it can set its own rules. If FILTER_INCLUSIONS is not
# None, this formatter will only receive those entries it has
# asked for.
# FILTER_INCLUSIONS = [{'field': ['values', ...]}, ...]
# The PRIORITY field is allowed to be a single value rather than a
# list, just like in the config file.
def format(self, entry):
"""
Format a single journal entry.
:param entry: dict, entry to format
:return: str, formatted entry including any newline required
"""
return entry['MESSAGE'] + '\n'
def flush(self):
"""
Return any closing formatting required.
This is called when there are no more
entries to format and can be used to
eg. display analysis of the logs.
"""
return ''
journal-brief-1.1.8/journal_brief/format/config.py 0000664 0000000 0000000 00000016232 14167332244 0022222 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from collections import namedtuple
from journal_brief.filter import Exclusion
from journal_brief.format import EntryFormatter
from logging import getLogger
log = getLogger(__name__)
CountedEntryField = namedtuple('CountedEntryField',
['field',
'entries'])
class Entry(dict):
"""
Journal entry that can be represented as a set of key=pair strings
"""
def as_strings(self, ignore_fields=None):
"""
Convert to strings
:return: list, key=pair strings
"""
if ignore_fields is None:
ignore_fields = []
strings = ["{0}={1}".format(field, value)
for field, value in self.items()
if field not in ignore_fields]
return set(strings)
class EntryCounter(object):
"""
Count occurrences of particular key=value pairs, maintaining context
"""
# Fields to ignore
IGNORE = {
'__CURSOR',
'__REALTIME_TIMESTAMP',
'_SOURCE_REALTIME_TIMESTAMP',
'__MONOTONIC_TIMESTAMP',
'_SOURCE_MONOTONIC_TIMESTAMP',
'_BOOT_ID',
'_PID',
'SYSLOG_PID',
'_MACHINE_ID',
'_TRANSPORT',
'_HOSTNAME',
'_SYSTEMD_OWNER_UID',
'_UID',
'_AUDIT_LOGINUID',
'_GID',
'_CAP_EFFECTIVE',
'PRIORITY',
'SYSLOG_FACILITY',
'_AUDIT_SESSION',
'_SYSTEMD_SESSION',
'_SYSTEMD_CGROUP',
'_SYSTEMD_SLICE',
}
def __init__(self, reader, ignore_fields=None):
"""
Constructor
:param reader: iterator, providing entry dicts
:param ignore_fields: sequence, set of field names to ignore
"""
self.reader = reader
self.counts = {}
self.total_entries = 0
self.ignore_fields = self.IGNORE.copy()
if ignore_fields:
self.ignore_fields.update(ignore_fields)
def read(self):
"""
Read all entries and count occurrences of field values
"""
for entry_dict in self.reader:
entry = Entry(entry_dict)
self.total_entries += 1
strings = entry.as_strings(ignore_fields=self.ignore_fields)
for entry_str in strings:
try:
counted = self.counts[entry_str]
counted.entries.append(entry)
except KeyError:
field = entry_str.split('=', 1)[0]
self.counts[entry_str] = CountedEntryField(field=field,
entries=[entry])
def get_counts(self):
"""
Get the list of counted entries, sorted with most frequent first
:return: list, CountedEntryField instances
"""
if not self.counts:
self.read()
counts = list(self.counts.values())
counts.sort(key=lambda count: len(count.entries), reverse=True)
return counts
class Debriefer(EntryFormatter):
"""
Build exclusions list covering all entries
This is the same as using the 'debrief' subcommand.
"""
FORMAT_NAME = 'config'
# One of these must be included in each rule
DEFINITIVE_FIELDS = {
'MESSAGE_ID',
'MESSAGE',
'CODE_FILE',
'CODE_FUNCTION',
}
def __init__(self):
"""
Constructor
:param reader: iterable, providing entry dicts
:param ignore_fields: sequence, field names to ignore
"""
super(Debriefer, self).__init__()
self.all_entries = []
self.exclusions = []
def get_top(self, entries=None):
"""
Find the most frequently occurring set of key=value pairs
:param entries: iterable, providing entry dicts
:return: list of remaining entries
"""
if entries is None:
entries = self.all_entries
ignore_fields = set([])
counter = EntryCounter(entries, ignore_fields=ignore_fields)
counts = counter.get_counts()
top = next(count for count in counts
if count.field in self.DEFINITIVE_FIELDS)
field = top.field
value = top.entries[0][field]
freq = len(top.entries)
log.debug("Top: %s=%r x %s/%s", field, value, freq,
counter.total_entries)
comment = '{0} occurrences (out of {1})'.format(freq,
counter.total_entries)
excl = {field: [value]}
# Anything else common to all of them?
ignore_fields.add(field)
while True:
counter = EntryCounter([entry for entry in entries
if entry.get(field) == value],
ignore_fields=ignore_fields)
counts = counter.get_counts()
if not counts:
break
top = counts.pop(0)
if len(top.entries) < freq:
break
field = top.field
excl[field] = [top.entries[0][field]]
ignore_fields.add(field)
self.exclusions.append(Exclusion(excl, comment=comment))
remaining = []
for entry in entries:
if all(entry.get(key) in value for key, value in excl.items()):
# Excluded
pass
else:
remaining.append(entry)
log.debug("%s entries remaining", len(remaining))
assert len(remaining) < len(entries)
return remaining
def get_exclusions(self):
"""
Get the exclusions list
:return: list, Exclusion instances
"""
try:
remaining = self.get_top()
except StopIteration:
pass
else:
try:
while True:
remaining = self.get_top(remaining)
except StopIteration:
pass
return self.exclusions
def format(self, entry):
self.all_entries.append(entry)
return ''
def flush(self):
exclusions = self.get_exclusions()
exclusions_yaml = ''
for exclusion in exclusions:
as_yaml = str(exclusion).splitlines()
indented = [' {0}\n'.format(line) for line in as_yaml if line]
exclusions_yaml += ''.join(indented)
if exclusions_yaml:
return "exclusions:\n{0}".format(exclusions_yaml)
return ''
journal-brief-1.1.8/journal_brief/format/json.py 0000664 0000000 0000000 00000004515 14167332244 0021727 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
import datetime
from journal_brief.format import EntryFormatter
import json
import logging
from systemd import journal
import uuid
log = logging.getLogger(__name__)
class JSONEntryFormatter(EntryFormatter):
"""
JSON format
"""
FORMAT_NAME = 'json'
JSON_DUMPS_KWARGS = {}
def format(self, entry):
serializable = {}
for field, value in entry.items():
if isinstance(value, uuid.UUID):
log.debug("Converting %s", field)
value = str(value)
elif isinstance(value, datetime.datetime):
log.debug("Converting %s", field)
value = value.timestamp() * 1000000 # microseconds
elif isinstance(value, journal.Monotonic):
log.debug("Converting %s", field)
value = value.timestamp.microseconds
elif isinstance(value, datetime.timedelta):
log.debug("Converting %s", field)
value = value.total_seconds() * 1000000 # microseconds
elif isinstance(value, bytes):
log.debug("Converting %s", field)
try:
value = value.decode()
except UnicodeDecodeError:
value = [int(byte) for byte in value]
serializable[field] = value
log.debug("%r", serializable)
return json.dumps(serializable, **self.JSON_DUMPS_KWARGS) + '\n'
class JSONPrettyEntryFormatter(JSONEntryFormatter):
"""
Pretty JSON format
"""
FORMAT_NAME = 'json-pretty'
JSON_DUMPS_KWARGS = {'indent': 8}
journal-brief-1.1.8/journal_brief/format/login.py 0000664 0000000 0000000 00000003430 14167332244 0022061 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from collections import defaultdict
from journal_brief.format import EntryFormatter
from locale import strxfrm
class LoginFormatter(EntryFormatter):
"""
Show a summary of login sessions
"""
FORMAT_NAME = "login"
FILTER_INCLUSIONS = [
{
# New session
'MESSAGE_ID': ['8d45620c1a4348dbb17410da57c60c66'],
'_COMM': ['systemd-logind'],
},
]
def __init__(self, *args, **kwargs):
super(LoginFormatter, self).__init__(*args, **kwargs)
self.login = defaultdict(int)
def format(self, entry):
if 'USER_ID' not in entry:
return ''
self.login[entry['USER_ID']] += 1
return ''
def flush(self):
if not self.login:
return ''
ret = '\nUser logins:\n\n'
logins = sorted(self.login.items(),
key=lambda item: strxfrm(item[0]))
for user, count in logins:
ret += '{count:>5} x {user}\n'.format(user=user, count=count)
return ret
journal-brief-1.1.8/journal_brief/format/reboot.py 0000664 0000000 0000000 00000003040 14167332244 0022240 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from journal_brief.format import EntryFormatter
import logging
log = logging.getLogger(__name__)
class RebootFormatter(EntryFormatter):
"""
Display a message on each reboot
Only shows reboots between entries that are to be shown.
"""
FORMAT_NAME = 'reboot'
def __init__(self, *args, **kwargs):
super(RebootFormatter, self).__init__(*args, **kwargs)
self.this_boot_id = None
def format(self, entry):
try:
boot_id = entry['_BOOT_ID']
except KeyError:
return ''
else:
reboot = (self.this_boot_id is not None and
self.this_boot_id != boot_id)
self.this_boot_id = boot_id
if reboot:
return '-- Reboot --\n'
return ''
journal-brief-1.1.8/journal_brief/format/short.py 0000664 0000000 0000000 00000004071 14167332244 0022112 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from journal_brief.format import EntryFormatter
import logging
log = logging.getLogger(__name__)
class ShortEntryFormatter(EntryFormatter):
"""
Output like a log file
"""
FORMAT_NAME = 'short'
FORMAT = '{__REALTIME_TIMESTAMP} {_HOSTNAME} {SYSLOG_IDENTIFIER}: {MESSAGE}\n'
TIMESTAMP_FORMAT = '%b %d %T'
def format_timestamp(self, entry, field):
"""
Convert entry field from datetime.datetime instance to string
Uses strftime() and TIMESTAMP_FORMAT
"""
if field in entry:
dt = entry[field]
entry[field] = dt.strftime(self.TIMESTAMP_FORMAT)
def format(self, entry):
"""
Format a journal entry using FORMAT
:param entry: dict, journal entry
:return: str, formatted string
"""
self.format_timestamp(entry, '__REALTIME_TIMESTAMP')
if '_HOSTNAME' not in entry:
entry['_HOSTNAME'] = 'localhost'
if 'SYSLOG_IDENTIFIER' not in entry:
entry['SYSLOG_IDENTIFIER'] = entry.get('_COMM', '?')
if '_PID' in entry:
entry['SYSLOG_IDENTIFIER'] += '[{0}]'.format(entry['_PID'])
elif 'SYSLOG_PID' in entry:
entry['SYSLOG_IDENTIFIER'] += '[{0}]'.format(entry['SYSLOG_PID'])
return self.FORMAT.format(**entry)
journal-brief-1.1.8/journal_brief/format/systemd.py 0000664 0000000 0000000 00000003572 14167332244 0022450 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from collections import defaultdict
from journal_brief.format import EntryFormatter
from locale import strxfrm
class SystemdFormatter(EntryFormatter):
"""
Show failed systemd units
"""
FORMAT_NAME = "systemd"
FILTER_INCLUSIONS = [
{
# New session
'_COMM': ['systemd'],
'CODE_FUNCTION': ['unit_notify'],
},
]
def __init__(self, *args, **kwargs):
super(SystemdFormatter, self).__init__(*args, **kwargs)
self.failed = defaultdict(int)
def format(self, entry):
try:
message = entry['MESSAGE']
unit = entry['UNIT']
except KeyError:
return ''
if 'entered failed state' in message:
self.failed[unit] += 1
return ''
def flush(self):
if not self.failed:
return ''
ret = '\nFailed systemd units:\n\n'
units = sorted(self.failed.items(),
key=lambda item: strxfrm(item[0]))
for unit, count in units:
ret += '{count:>5} x {unit}\n'.format(count=count, unit=unit)
return ret
journal-brief-1.1.8/journal_brief/journal_brief.py 0000664 0000000 0000000 00000015765 14167332244 0022320 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015, 2020 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from collections import namedtuple
from collections.abc import Iterator
import errno
from journal_brief.constants import PRIORITY_MAP
from logging import getLogger
import os
from systemd import journal
log = getLogger(__name__)
class SelectiveReader(journal.Reader):
"""
A Reader instance with matches applied
"""
def __init__(self, log_level=None, this_boot=None, inclusions=None,
explicit_inclusions=None):
"""Constructor
:param log_level: int, LOG_* priority level
:param this_boot: bool, process messages from this boot
:param inclusions: dict, field -> values, PRIORITY may use value
instead of list
:param explicit_inclusions: dict, field -> values, but
log_level is not applied to any of
these
"""
super(SelectiveReader, self).__init__()
log.debug("setting inclusion filters:")
assert not inclusions or isinstance(inclusions, list)
assert not explicit_inclusions or isinstance(explicit_inclusions, list)
Rule = namedtuple('Rule', ('log_level', 'inclusion'))
# 'inclusions' use 'log_level' for each disjunct
rules = [Rule(log_level=log_level, inclusion=inclusion)
for inclusion in inclusions or []]
# 'explicit_inclusions' don't. This is to allow output
# formatters to specify their own explicit inclusions rules
# without needing to set PRIORITY.
rules += [Rule(log_level=None, inclusion=inclusion)
for inclusion in explicit_inclusions or []]
if rules:
self.set_filter_rules(rules, this_boot=this_boot)
else:
if this_boot:
log.debug("this_boot()")
self.this_boot()
if log_level is not None:
log.debug("log_level(%r)", log_level)
self.log_level(log_level)
log.debug("no more inclusion filters")
def process_rule(self, rule, this_boot): # noqa: C901
assert isinstance(rule.inclusion, dict)
for field, matches in rule.inclusion.items():
if field == 'PRIORITY':
try:
this_log_level = int(PRIORITY_MAP[matches])
except (AttributeError, TypeError):
pass
else:
# These are equivalent:
# - PRIORITY: 3
# - PRIORITY: err
# - PRIORITY: [0, 1, 2, 3]
# - PRIORITY: [emerg, alert, crit, err]
log.debug("log_level(%r)", this_log_level)
self.log_level(this_log_level)
continue
assert isinstance(matches, list)
for match in matches:
if field == 'PRIORITY':
try:
match = PRIORITY_MAP[match]
except (AttributeError, TypeError):
pass
log.debug("%s=%s", field, match)
self.add_match(**{str(field): str(match)})
if this_boot:
log.debug("this_boot()")
self.this_boot()
if rule.log_level is not None:
log.debug("log_level(%r)", rule.log_level)
self.log_level(rule.log_level)
def set_filter_rules(self, rules, this_boot=None):
for index, rule in enumerate(rules):
if index:
log.debug("-or-")
self.add_disjunction()
self.process_rule(rule, this_boot)
class LatestJournalEntries(Iterator):
"""
Iterate over new journal entries since last time
"""
def __init__(self, cursor_file=None, reader=None, dry_run=False,
seek_cursor=True):
"""
Constructor
:param cursor_file: str, filename of cursor bookmark file
:param reader: systemd.journal.Reader instance
:param dry_run: bool, whether to update the cursor file
:param seek_cursor: bool, whether to seek to bookmark first
"""
super(LatestJournalEntries, self).__init__()
self.cursor_file = cursor_file
try:
with open(self.cursor_file, "rt") as fp:
self.cursor = fp.read()
except IOError as ex:
if ex.errno == errno.ENOENT:
self.cursor = None
else:
raise
if reader is None:
reader = journal.Reader()
if self.cursor:
if seek_cursor:
log.debug("Seeking to %s", self.cursor)
reader.seek_cursor(self.cursor)
reader.get_next()
elif not dry_run:
# use an unfiltered Reader to find the current 'tail'
# of the journal and store that as the initial cursor
# when the cursor file could not be found; this avoids
# reading through the entire journal again on the next
# run if the inclusions and exclusions result in zero
# matching entries during this run
temp_reader = journal.Reader()
temp_reader.seek_tail()
fields = temp_reader.get_previous()
if fields:
self.cursor = fields['__CURSOR']
else:
self.cursor = ''
temp_reader.close()
self.reader = reader
self.dry_run = dry_run
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# if an exception was thrown by the code using this
# context manager, don't update the cursor
if exc_type is not None:
return
if self.dry_run:
return
path = os.path.dirname(self.cursor_file)
try:
os.makedirs(path)
except OSError as ex:
if ex.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
with open(self.cursor_file, "wt") as fp:
fp.write(self.cursor)
def __next__(self):
fields = self.reader.get_next()
if not fields:
raise StopIteration
if '__CURSOR' in fields:
self.cursor = fields['__CURSOR']
return fields
journal-brief-1.1.8/python-journal-brief.spec 0000664 0000000 0000000 00000004110 14167332244 0021214 0 ustar 00root root 0000000 0000000 %global srcname journal-brief
%global sum Find new systemd journal entries since last run
Name: python-%{srcname}
Version: 1.1.8
Release: 1%{?dist}
Summary: %{sum}
License: GPLv2+
URL: https://pypi.python.org/pypi/%{srcname}
Source0: https://pypi.python.org/packages/source/j/%{srcname}/%{srcname}-%{version}.tar.gz
BuildArch: noarch
BuildRequires: python3-devel
BuildRequires: python3-pytest python3-flexmock python3-pytest-mock
BuildRequires: python3-PyYAML
BuildRequires: python3-setuptools
%description
Python module for examining, bookmarking, and filtering systemd
journal entries.
%package -n %{srcname}
Summary: Show interesting new systemd journal entries since last run
Requires: python3-%{srcname} = %{version}-%{release}
Requires: python3-setuptools
%description -n %{srcname}
Run this from cron to get a daily or hourly briefing of interesting
new systemd journal entries.
%package -n python3-%{srcname}
Summary: %{sum}
Requires: systemd-python3
Requires: python3-PyYAML
Recommends: %{srcname} = %{version}-%{release}
%{?python_provide:%python_provide python3-%{srcname}}
%description -n python3-%{srcname}
Python module for examining, bookmarking, and filtering systemd
journal entries.
%prep
%autosetup -n %{srcname}-%{version}
%build
%py3_build
%install
%py3_install
%check
PYTEST_ARGS='-v --doctest-modules tests journal_brief'
%{__python3} %{py_setup} test --pytest-args="$PYTEST_ARGS"
%files -n %{srcname}
%{_bindir}/%{srcname}
%files -n python3-%{srcname}
%license LICENSE
%doc README.md
%{python3_sitelib}/*
%changelog
* Tue Jan 11 2022 Tim Waugh - 1.1.8-1
- 1.1.8.
* Mon Jul 13 2020 Tim Waugh - 1.1.7-1
- 1.1.7.
* Tue Jul 7 2020 Tim Waugh - 1.1.6-1
- 1.1.6.
* Mon Oct 31 2016 Tim Waugh - 1.1.5-1
- 1.1.5.
* Sun Jul 24 2016 Tim Waugh - 1.1.4-1
- 1.1.4.
* Mon Nov 9 2015 Tim Waugh - 1.1.3-1
- 1.1.3.
* Fri Oct 30 2015 Tim Waugh - 1.1.2-1
- 1.1.2.
* Thu Oct 15 2015 Tim Waugh - 1.1.1-1
- Initial spec file.
journal-brief-1.1.8/setup.py 0000664 0000000 0000000 00000006143 14167332244 0016004 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
"""
Copyright (c) 2015, 2016, 2020 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', 'Arguments to pass to py.test')]
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = []
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
long_description = """
This can be run from cron to get a daily or hourly
briefing of interesting new systemd journal entries.
Inclusion and exclusion criteria define what an "interesting" journal
entry is, and exclusion rules can be built automatically.
""".strip()
setup(
name='journal-brief',
version='1.1.8', # also update journal_brief/__init__.py
# and python-journal-brief.spec
description='Show interesting new systemd journal entries since last run',
long_description=long_description,
author='Tim Waugh',
author_email='tim@cyberelk.net',
url='https://github.com/twaugh/journal-brief',
license="GPLv2+",
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3 :: Only',
'Topic :: System :: Logging',
'Topic :: System :: Monitoring',
],
keywords='systemd journal journalctl log monitor watch',
entry_points={
'console_scripts': ['journal-brief=journal_brief.cli.main:run'],
},
install_requires=['PyYAML', 'systemd-python'],
tests_require=['pytest', 'flexmock', 'pytest-mock'],
cmdclass={'test': PyTest},
packages=find_packages(exclude=['tests',
'tests.cli',
'tests.format',
'tests.missing',
'tests.missing.systemd',
'tests.missing.systemd.journal']),
package_data={'': ['conf/journal-brief.conf']},
)
journal-brief-1.1.8/tests/ 0000775 0000000 0000000 00000000000 14167332244 0015430 5 ustar 00root root 0000000 0000000 journal-brief-1.1.8/tests/__init__.py 0000664 0000000 0000000 00000000000 14167332244 0017527 0 ustar 00root root 0000000 0000000 journal-brief-1.1.8/tests/cli/ 0000775 0000000 0000000 00000000000 14167332244 0016177 5 ustar 00root root 0000000 0000000 journal-brief-1.1.8/tests/cli/__init__.py 0000664 0000000 0000000 00000000000 14167332244 0020276 0 ustar 00root root 0000000 0000000 journal-brief-1.1.8/tests/cli/test_main.py 0000664 0000000 0000000 00000066145 14167332244 0020550 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015, 2020 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from datetime import datetime
from flexmock import flexmock
from journal_brief.cli.constants import (EMAIL_SUPPRESS_EMPTY_TEXT,
EMAIL_DRY_RUN_SEPARATOR)
from journal_brief.cli.main import CLI
import json
import logging
import os
import pytest
from systemd import journal
from tempfile import NamedTemporaryFile
from tests.test_filter import MySpecialFormatter # registers class; # noqa: F401
from tests.util import Watcher
import uuid
import yaml
logging.basicConfig(level=logging.DEBUG)
@pytest.fixture
def build_config_and_cursor(tmp_path):
with NamedTemporaryFile(mode='wt', dir=tmp_path) as configfile:
with NamedTemporaryFile(mode='w+t', dir=tmp_path) as cursorfile:
def write_config(config=None):
configfile.write('cursor-file: {0}\n'.format(cursorfile.name))
if isinstance(config, dict):
configfile.write(yaml.dump(config))
elif config:
configfile.write(config)
configfile.flush()
return (configfile, cursorfile)
yield write_config
@pytest.fixture
def missing_or_empty_cursor():
(flexmock(journal.Reader)
.should_receive('seek_tail')
.once())
(flexmock(journal.Reader)
.should_receive('get_previous')
.and_return({'__CURSOR': '0'}))
class TestCLI(object):
def test_param_override(self):
with NamedTemporaryFile(mode='wt') as configfile:
configfile.write('priority: err')
configfile.flush()
cli = CLI(args=['--conf', configfile.name])
# Default value
assert cli.config.get('cursor_file') == 'cursor'
# Specified in config
assert cli.config.get('priority') == 'err'
# Specified on command-line
cli = CLI(args=['--conf', configfile.name,
'-p', 'debug'])
assert cli.config.get('priority') == 'debug'
def test_normal_run(self, capsys, build_config_and_cursor, missing_or_empty_cursor):
(flexmock(journal.Reader, add_match=None, add_disjunction=None)
.should_receive('get_next')
.and_return({'__CURSOR': '1',
'__REALTIME_TIMESTAMP': datetime.now(),
'MESSAGE': 'message1'})
.and_return({'__CURSOR': '2',
'__REALTIME_TIMESTAMP': datetime.now(),
'MESSAGE': 'message2'})
.and_return({}))
(configfile, cursorfile) = build_config_and_cursor()
cli = CLI(args=['--conf', configfile.name])
cli.run()
(out, err) = capsys.readouterr()
assert not err
assert len(out.splitlines()) == 2
def test_dry_run(self, build_config_and_cursor):
(flexmock(journal.Reader, add_match=None, add_disjunction=None)
.should_receive('get_next')
.and_return({'__CURSOR': '1',
'__REALTIME_TIMESTAMP': datetime.now(),
'MESSAGE': 'message'})
.and_return({}))
(configfile, cursorfile) = build_config_and_cursor()
cli = CLI(args=['--conf', configfile.name, '--dry-run'])
cli.run()
assert not cursorfile.read()
def test_this_boot(self, build_config_and_cursor):
final_cursor = '1'
flexmock(journal.Reader, add_match=None, add_disjunction=None)
(flexmock(journal.Reader)
.should_receive('this_boot')
.once())
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return({'__CURSOR': final_cursor,
'__REALTIME_TIMESTAMP': datetime.now(),
'MESSAGE': 'message'})
.and_return({}))
(configfile, cursorfile) = build_config_and_cursor()
cursorfile.write(final_cursor)
cursorfile.flush()
cli = CLI(args=['--conf', configfile.name, '-b'])
cli.run()
cursorfile.seek(0)
assert cursorfile.read() == final_cursor
def test_log_level(self, build_config_and_cursor, missing_or_empty_cursor):
flexmock(journal.Reader, add_match=None, add_disjunction=None)
(flexmock(journal.Reader)
.should_receive('log_level')
.with_args(journal.LOG_ERR)
.once())
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return({}))
(configfile, cursorfile) = build_config_and_cursor()
cli = CLI(args=['--conf', configfile.name, '-p', 'err'])
cli.run()
def test_reset(self, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor()
with cursorfile: # force the cursorfile context to be exited at the right time
cli = CLI(args=['--conf', configfile.name, 'reset'])
cli.run()
# Cursor file is deleted
assert not os.access(cursorfile.name, os.F_OK)
open(cursorfile.name, mode='w').close()
# No errors when the cursor file doesn't exist
cli = CLI(args=['--conf', configfile.name, 'reset'])
cli.run()
assert not os.access(cursorfile.name, os.F_OK)
def test_stats(self, capsys, build_config_and_cursor, missing_or_empty_cursor):
(flexmock(journal.Reader, add_match=None, add_disjunction=None)
.should_receive('get_next')
.and_return({'__CURSOR': '1',
'__REALTIME_TIMESTAMP': datetime.now(),
'MESSAGE': 'exclude'})
.and_return({'__CURSOR': '2',
'__REALTIME_TIMESTAMP': datetime.now(),
'MESSAGE': 'include'})
.and_return({}))
(configfile, cursorfile) = build_config_and_cursor("""
exclusions:
- MESSAGE: [exclude]
""")
cli = CLI(args=['--conf', configfile.name, 'stats'])
cli.run()
(out, err) = capsys.readouterr()
assert not err
assert out == "\n".join([" FREQUENCY EXCLUSION",
" 1 {'MESSAGE': ['exclude']}",
""])
def test_debrief(self, capsys, build_config_and_cursor, missing_or_empty_cursor):
entries = [
{'__CURSOR': '1',
'MESSAGE': 'message 1',
'KEY': 'multiple',
'__REALTIME_TIMESTAMP': datetime.now()},
{'__CURSOR': '2',
'MESSAGE': 'message 1',
'KEY': 'multiple',
'__REALTIME_TIMESTAMP': datetime.now()},
{'__CURSOR': '3',
'MESSAGE': 'message 1',
'__REALTIME_TIMESTAMP': datetime.now()},
{'__CURSOR': '4',
'MESSAGE': 'message 1',
'__REALTIME_TIMESTAMP': datetime.now()},
{'__CURSOR': '5',
'MESSAGE': 'message 2',
'KEY': 'multiple',
'__REALTIME_TIMESTAMP': datetime.now()},
{'__CURSOR': '6',
'MESSAGE': 'message 2',
'KEY': 'single',
'__REALTIME_TIMESTAMP': datetime.now()},
]
expectation = (flexmock(journal.Reader).should_receive('get_next'))
for entry in entries:
expectation = expectation.and_return(entry)
expectation.and_return({})
(configfile, cursorfile) = build_config_and_cursor()
cli = CLI(args=['--conf', configfile.name, 'debrief'])
cli.run()
(out, err) = capsys.readouterr()
assert not err
assert out == "\n".join([
"exclusions:",
" # 4 occurrences (out of 6)",
" - MESSAGE:",
" - message 1",
" # 2 occurrences (out of 2)",
" - MESSAGE:",
" - message 2",
''])
def test_debrief_no_input(self, capsys, build_config_and_cursor, missing_or_empty_cursor):
"""
Check it handles there being no input
"""
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return({}))
(configfile, cursorfile) = build_config_and_cursor()
cli = CLI(args=['--conf', configfile.name, 'debrief'])
cli.run()
(out, err) = capsys.readouterr()
assert not err
assert not out
def test_exclusions_yaml(self, capsys, build_config_and_cursor, missing_or_empty_cursor):
(flexmock(journal.Reader, add_match=None, add_disjunction=None)
.should_receive('get_next')
.and_return({'__CURSOR': '1',
'__REALTIME_TIMESTAMP': datetime.now(),
'MESSAGE': 'message'})
.and_return({}))
(configfile, cursorfile) = build_config_and_cursor("""
exclusions:
- MESSAGE: [1]
""")
cli = CLI(args=['--conf', configfile.name])
cli.run()
(out, err) = capsys.readouterr()
assert not err
assert 'message' in out
def test_inclusions_yaml(self, build_config_and_cursor, missing_or_empty_cursor):
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return({}))
watcher = Watcher()
(flexmock(journal.Reader)
.should_receive('add_match')
.replace_with(watcher.watch_call('add_match')))
(flexmock(journal.Reader)
.should_receive('add_conjunction')
.replace_with(watcher.watch_call('add_conjunction')))
(flexmock(journal.Reader)
.should_receive('add_disjunction')
.replace_with(watcher.watch_call('add_disjunction')))
(configfile, cursorfile) = build_config_and_cursor("""
inclusions:
- PRIORITY: [0, 1, 2, 3]
- PRIORITY: [4, 5, 6]
_SYSTEMD_UNIT: [myservice.service]
""")
cli = CLI(args=['--conf', configfile.name])
cli.run()
# Should add matches for all of the first group
assert set(watcher.calls[:4]) == set([
('add_match', (), "{'PRIORITY': '0'}"),
('add_match', (), "{'PRIORITY': '1'}"),
('add_match', (), "{'PRIORITY': '2'}"),
('add_match', (), "{'PRIORITY': '3'}"),
])
# Then a disjunction
assert watcher.calls[4] == ('add_disjunction', (), '{}')
# Then matches for all of the second group
assert set(watcher.calls[5:9]) == set([
('add_match', (), "{'PRIORITY': '4'}"),
('add_match', (), "{'PRIORITY': '5'}"),
('add_match', (), "{'PRIORITY': '6'}"),
('add_match', (), "{'_SYSTEMD_UNIT': 'myservice.service'}"),
])
# And nothing else
assert len(watcher.calls) == 9
def test_multiple_output_formats_cli(self, capsys, build_config_and_cursor, missing_or_empty_cursor):
entry = {
'__CURSOR': '1',
'__REALTIME_TIMESTAMP': datetime.now(),
'MESSAGE': 'message',
}
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return(entry)
.and_return({}))
(configfile, cursorfile) = build_config_and_cursor()
cli = CLI(args=['--conf', configfile.name,
'-o', 'cat,cat,json'])
cli.run()
(out, err) = capsys.readouterr()
assert not err
lines = out.splitlines()
assert len(lines) == 3
assert lines[0] == lines[1] == 'message'
output = json.loads(lines[2])
del entry['__REALTIME_TIMESTAMP']
del output['__REALTIME_TIMESTAMP']
assert output == entry
def test_multiple_output_formats_conf(self, capsys, build_config_and_cursor, missing_or_empty_cursor):
entry = {
'__CURSOR': '1',
'__REALTIME_TIMESTAMP': datetime.now(),
'MESSAGE': 'message',
}
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return(entry)
.and_return({}))
(configfile, cursorfile) = build_config_and_cursor("""
output:
- cat
- cat
- json
""")
cli = CLI(args=['--conf', configfile.name])
cli.run()
(out, err) = capsys.readouterr()
assert not err
lines = out.splitlines()
assert len(lines) == 3
assert lines[0] == lines[1] == 'message'
output = json.loads(lines[2])
del entry['__REALTIME_TIMESTAMP']
del output['__REALTIME_TIMESTAMP']
assert output == entry
def test_formatter_filter(self, capsys, build_config_and_cursor, missing_or_empty_cursor):
"""
Just a coverage test
"""
entry = {
'__CURSOR': '1',
'__REALTIME_TIMESTAMP': datetime.now(),
'PRIORITY': 6,
'MESSAGE': 'login session started',
'MESSAGE_ID': uuid.UUID('8d45620c1a4348dbb17410da57c60c66'),
'_COMM': 'systemd-logind',
'USER_ID': 'abc',
}
(flexmock(journal.Reader, add_match=None, add_disjunction=None)
.should_receive('get_next')
.and_return(entry)
.and_return({}))
(configfile, cursorfile) = build_config_and_cursor()
cli = CLI(args=['--conf', configfile.name,
'-p', 'err', '-o', 'login'])
cli.run()
(out, err) = capsys.readouterr()
assert not err
assert out
def test_help_output(self, capsys):
cli = CLI(args=['--help-output'])
cli.run()
(out, err) = capsys.readouterr()
assert not err
assert out
class TestCLIEmailBase(object):
@pytest.fixture(autouse=True)
def mock_journal(self, mocker):
# mock SelectiveReader to ensure that systemd.journal.Reader is never used
self.reader_class = mocker.patch('journal_brief.cli.main.SelectiveReader', autospec=True)
self.entries_class = mocker.patch('journal_brief.cli.main.LatestJournalEntries', autospec=True)
self.entries_object = self.entries_class.return_value.__enter__.return_value
# don't provide any journal entries unless test function calls mock_entries()
self.entries_object.__iter__.return_value = []
def mock_entries(entries):
self.entries_object.__iter__.return_value = entries
yield mock_entries
class TestCLIEmailMIME(TestCLIEmailBase):
TEST_COMMAND = 'foo'
TEST_SUBJECT = 'subj'
@pytest.fixture(autouse=True)
def mock_mime(self, mocker):
self.mimetext_class = mocker.patch('journal_brief.cli.main.MIMEText', autospec=True)
self.mimetext_object = self.mimetext_class.return_value
@pytest.fixture(autouse=True)
def mock_subprocess(self, mocker):
self.subprocess_module = mocker.patch('journal_brief.cli.main.subprocess', autospec=True)
def test(self, capsys, mocker, build_config_and_cursor, mock_journal):
entries = [
{
'__CURSOR': '1',
'TEST': 'yes',
'OUTPUT': 'message',
}
]
mock_journal(entries)
(configfile, cursorfile) = build_config_and_cursor({
'output': 'test',
'email': {
'command': self.TEST_COMMAND,
'from': 'F',
'to': 'T',
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.mimetext_class.assert_called_once_with(entries[0]['OUTPUT'], _charset=mocker.ANY)
self.mimetext_object.__setitem__.assert_any_call('From', 'F')
self.mimetext_object.__setitem__.assert_any_call('To', 'T')
def test_allow_empty(self, mocker, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor({
'email': {
'suppress_empty': False,
'command': self.TEST_COMMAND,
'from': 'F',
'to': 'T',
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.mimetext_class.assert_called_once_with(EMAIL_SUPPRESS_EMPTY_TEXT, _charset=mocker.ANY)
def test_subject(self, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor({
'email': {
'suppress_empty': False,
'command': self.TEST_COMMAND,
'from': 'F',
'to': 'T',
'subject': self.TEST_SUBJECT,
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.mimetext_object.__setitem__.assert_any_call('Subject', self.TEST_SUBJECT)
def test_to_list(self, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor({
'email': {
'suppress_empty': False,
'command': self.TEST_COMMAND,
'from': 'F',
'to': ['A', 'B'],
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.mimetext_object.__setitem__.assert_any_call('To', 'A, B')
def test_cc_list(self, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor({
'email': {
'suppress_empty': False,
'command': self.TEST_COMMAND,
'from': 'F',
'to': 'T',
'cc': ['A', 'B'],
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.mimetext_object.__setitem__.assert_any_call('Cc', 'A, B')
def test_bcc_list(self, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor({
'email': {
'suppress_empty': False,
'command': self.TEST_COMMAND,
'from': 'F',
'to': 'T',
'bcc': ['A', 'B'],
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.mimetext_object.__setitem__.assert_any_call('Bcc', 'A, B')
def test_headers(self, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor({
'email': {
'suppress_empty': False,
'command': self.TEST_COMMAND,
'from': 'F',
'to': 'T',
'headers': {
'X-Header-1': '1',
'X-Header-4': '4',
},
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.mimetext_object.__setitem__.assert_any_call('X-Header-1', '1')
self.mimetext_object.__setitem__.assert_any_call('X-Header-4', '4')
class TestCLIEmailCommand(TestCLIEmailBase):
TEST_COMMAND = 'foo'
@pytest.fixture(autouse=True)
def mock_subprocess(self, mocker):
self.subprocess_module = mocker.patch('journal_brief.cli.main.subprocess', autospec=True)
def test(self, build_config_and_cursor, mock_journal, mocker):
entries = [
{
'__CURSOR': '1',
'TEST': 'yes',
'OUTPUT': 'message',
}
]
mock_journal(entries)
(configfile, cursorfile) = build_config_and_cursor({
'output': 'test',
'email': {
'command': self.TEST_COMMAND,
'from': 'F',
'to': 'T',
}
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.subprocess_module.run.assert_called_once_with(self.TEST_COMMAND, shell=True, check=True, text=True, input=mocker.ANY)
assert isinstance(self.subprocess_module.run.call_args[1]['input'], str), "subprocess.run 'input' argument must be a string"
def test_non_mime(self, build_config_and_cursor, mock_journal, mocker):
entries = [
{
'__CURSOR': '1',
'TEST': 'yes',
'OUTPUT': 'message',
}
]
mock_journal(entries)
(configfile, cursorfile) = build_config_and_cursor({
'output': 'test',
'email': {
'command': self.TEST_COMMAND,
}
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.subprocess_module.run.assert_called_once_with(self.TEST_COMMAND, shell=True, check=True, text=True, input=entries[0]['OUTPUT'])
def test_dry_run(self, capsys, build_config_and_cursor, mock_journal):
entries = [
{
'__CURSOR': '1',
'TEST': 'yes',
'OUTPUT': 'message',
}
]
mock_journal(entries)
(configfile, cursorfile) = build_config_and_cursor({
'output': 'test',
'email': {
'command': self.TEST_COMMAND,
'from': 'F',
'to': 'T',
},
})
cli = CLI(args=['--dry-run', '--conf', configfile.name])
cli.run()
(out, err) = capsys.readouterr()
assert not err
lines = out.splitlines()
assert len(lines) == 10
assert lines[0] == "Email to be delivered via '{0}'".format(self.TEST_COMMAND)
assert lines[1] == EMAIL_DRY_RUN_SEPARATOR
self.subprocess_module.run.assert_not_called()
def test_suppress_empty(self, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor({
'email': {
'command': self.TEST_COMMAND,
'from': 'F',
'to': 'T',
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.subprocess_module.run.assert_not_called()
class TestCLIEmailSMTP(TestCLIEmailBase):
TEST_USER = 'zork'
TEST_PASSWORD = 'xyzzy'
TEST_HOST = 'example'
TEST_PORT = 1234
TEST_SUBJECT = 'subj'
@pytest.fixture(autouse=True)
def mock_smtp(self, mocker):
self.smtp_class = mocker.patch('journal_brief.cli.main.SMTP', autospec=True)
self.smtp_object = self.smtp_class.return_value
self.smtp_context = self.smtp_object.__enter__.return_value
def test(self, capsys, mocker, build_config_and_cursor, mock_journal):
entries = [
{
'__CURSOR': '1',
'TEST': 'yes',
'OUTPUT': 'message',
}
]
mock_journal(entries)
(configfile, cursorfile) = build_config_and_cursor({
'output': 'test',
'email': {
'from': 'F',
'to': 'T',
'smtp': {},
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.smtp_context.send_message.assert_called_once()
def test_dry_run(self, capsys, build_config_and_cursor, mock_journal):
entries = [
{
'__CURSOR': '1',
'TEST': 'yes',
'OUTPUT': 'message',
}
]
mock_journal(entries)
(configfile, cursorfile) = build_config_and_cursor({
'output': 'test',
'email': {
'from': 'F',
'to': 'T',
'smtp': {},
},
})
cli = CLI(args=['--dry-run', '--conf', configfile.name])
cli.run()
self.smtp_class.assert_not_called()
(out, err) = capsys.readouterr()
assert not err
lines = out.splitlines()
assert len(lines) == 10
assert lines[0] == 'Email to be delivered via SMTP to localhost port 25'
assert lines[1] == EMAIL_DRY_RUN_SEPARATOR
def test_suppress_empty(self, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor({
'email': {
'from': 'F',
'to': 'T',
'smtp': {},
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.smtp_class.assert_not_called()
def test_host(self, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor({
'email': {
'suppress_empty': False,
'from': 'F',
'to': 'T',
'smtp': {
'host': self.TEST_HOST,
},
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.smtp_class.assert_called_once_with(self.TEST_HOST, 0)
def test_port(self, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor({
'email': {
'suppress_empty': False,
'from': 'F',
'to': 'T',
'smtp': {
'host': self.TEST_HOST,
'port': self.TEST_PORT,
},
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
self.smtp_class.assert_called_once_with(self.TEST_HOST, self.TEST_PORT)
def test_starttls(self, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor({
'email': {
'suppress_empty': False,
'from': 'F',
'to': 'T',
'smtp': {
'starttls': True,
},
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
assert 'starttls' == self.smtp_context.method_calls[0][0]
assert 'send_message' == self.smtp_context.method_calls[1][0]
def test_user(self, mocker, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor({
'email': {
'suppress_empty': False,
'from': 'F',
'to': 'T',
'smtp': {
'user': self.TEST_USER,
},
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
assert mocker.call.login(self.TEST_USER, None) == self.smtp_context.method_calls[0]
assert 'send_message' == self.smtp_context.method_calls[1][0]
def test_password(self, mocker, build_config_and_cursor):
(configfile, cursorfile) = build_config_and_cursor({
'email': {
'suppress_empty': False,
'from': 'F',
'to': 'T',
'smtp': {
'user': self.TEST_USER,
'password': self.TEST_PASSWORD,
},
},
})
cli = CLI(args=['--conf', configfile.name])
cli.run()
assert mocker.call.login(self.TEST_USER, self.TEST_PASSWORD) == self.smtp_context.method_calls[0]
assert 'send_message' == self.smtp_context.method_calls[1][0]
journal-brief-1.1.8/tests/format/ 0000775 0000000 0000000 00000000000 14167332244 0016720 5 ustar 00root root 0000000 0000000 journal-brief-1.1.8/tests/format/__init__.py 0000664 0000000 0000000 00000000000 14167332244 0021017 0 ustar 00root root 0000000 0000000 journal-brief-1.1.8/tests/format/test_config.py 0000664 0000000 0000000 00000007317 14167332244 0021606 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from tests.util import maybe_mock_systemd
maybe_mock_systemd()
from journal_brief.format import get_formatter
from journal_brief.format.config import EntryCounter
import logging
from uuid import uuid1
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
class TestEntryCounter(object):
def test_get_counts(self):
reader = [{'MESSAGE': 'message 1',
'KEY': 'multiple'},
{'MESSAGE': 'message 1',
'KEY': 'multiple'},
{'MESSAGE': 'message 1'},
{'MESSAGE': 'message 1'},
{'MESSAGE': 'message 2',
'KEY': 'multiple'},
{'MESSAGE': 'message 2',
'KEY': 'single'}]
counter = EntryCounter(reader)
counts = counter.get_counts()
assert counter.total_entries == len(reader)
expected = [('MESSAGE', 'message 1', 4),
('KEY', 'multiple', 3),
('MESSAGE', 'message 2', 2),
('KEY', 'single', 1)]
for exp_field, exp_value, exp_count in expected:
count = counts.pop(0)
log.debug("%r: expect %s=%r x %s",
count, exp_field, exp_value, exp_count)
assert count.field == exp_field
assert len(count.entries) == exp_count
values = set([entry[exp_field] for entry in count.entries])
assert len(values) == 1
class TestDebriefer(object):
def test_get_exclusions(self):
reader = [{'MESSAGE': 'message 1',
'MESSAGE1': 'x',
'KEY': 'multiple'},
{'MESSAGE': 'message 1',
'MESSAGE1': 'x',
'KEY': 'multiple'},
{'MESSAGE': 'message 1',
'MESSAGE1': 'x'},
{'MESSAGE': 'message 1',
'MESSAGE1': 'x'},
{'MESSAGE': 'message 2',
'KEY': 'multiple'},
{'MESSAGE': 'message 2',
'KEY': 'single'}]
dbr = get_formatter('config')
formatted = ''
for entry in reader:
formatted += dbr.format(entry)
formatted += dbr.flush()
assert formatted == '\n'.join([
"exclusions:",
" # 4 occurrences (out of 6)",
" - MESSAGE:",
" - message 1",
" MESSAGE1:",
" - x",
" # 2 occurrences (out of 2)",
" - MESSAGE:",
" - message 2",
''
])
def test_uuid(self):
dbr = get_formatter('config')
message_id = uuid1()
formatted = dbr.format({'MESSAGE_ID': message_id})
formatted += dbr.flush()
assert formatted == '\n'.join([
"exclusions:",
" # 1 occurrences (out of 1)",
" - MESSAGE_ID:",
" - {0}".format(str(message_id)),
''
])
journal-brief-1.1.8/tests/format/test_json.py 0000664 0000000 0000000 00000006572 14167332244 0021314 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from datetime import datetime, timezone, timedelta
from io import StringIO
from journal_brief.format import get_formatter
import journal_brief.format.json # registers class; # noqa: F401
import json
import pytest
import uuid
from tests.util import maybe_mock_systemd
maybe_mock_systemd()
from systemd import journal
class TestJSONEntryFormatter(object):
def test_uuid(self):
"""
Should be string representation of UUID
"""
entry = {'_BOOT_ID': uuid.uuid1()}
formatter = get_formatter('json')
out = json.loads(formatter.format(entry))
assert out['_BOOT_ID'] == str(entry['_BOOT_ID'])
def test_timestamp(self):
"""
Should output microseconds since the epoch
"""
dt = datetime.fromtimestamp(5, tz=timezone(timedelta(hours=1)))
entry = {'__REALTIME_TIMESTAMP': dt}
formatter = get_formatter('json')
out = json.loads(formatter.format(entry))
assert out['__REALTIME_TIMESTAMP'] == 5000000
def test_monotonic(self):
"""
Should be in microseconds
"""
us = 700
elapsed = timedelta(microseconds=us)
boot_id = uuid.uuid1()
timestamp = journal.Monotonic((elapsed, boot_id))
entry = {'__MONOTONIC_TIMESTAMP': timestamp}
formatter = get_formatter('json')
out = json.loads(formatter.format(entry))
assert out['__MONOTONIC_TIMESTAMP'] == us
def test_timedelta(self):
"""
Should be in microseconds
"""
sec = 1
us = 700
mono_ts = timedelta(0, sec, us)
entry = {'__MONOTONIC_TIMESTAMP': mono_ts}
formatter = get_formatter('json')
out = json.loads(formatter.format(entry))
diff = out['__MONOTONIC_TIMESTAMP'] - (sec * 1000000 + us)
assert diff < 0.001
@pytest.mark.parametrize(('bdata', 'brepr'), [
(b'abc', 'abc'),
(b'\x82\xac', [0x82, 0xac]),
])
def test_bytes(self, bdata, brepr):
"""
Should decode to unicode or a number array
"""
entry = {'BDATA': bdata}
formatter = get_formatter('json')
out = json.loads(formatter.format(entry))
assert out['BDATA'] == brepr
def test_multiline(self):
"""
Check each entry is formatted as a single output line
"""
count = 5
output = StringIO()
formatter = get_formatter('json')
for n in range(count):
output.write(formatter.format({'MESSAGE': 'entry'}))
output.write(formatter.flush())
output.seek(0)
assert len(output.read().splitlines()) == count
journal-brief-1.1.8/tests/format/test_login.py 0000664 0000000 0000000 00000003325 14167332244 0021444 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from journal_brief.format import get_formatter
import journal_brief.format.login # registers class; # noqa: F401
from locale import setlocale, LC_ALL
from uuid import UUID
class TestLoginEntryFormatter(object):
def test_no_logins(self):
formatter = get_formatter('login')
assert formatter.flush() == ''
def test_login(self):
setlocale(LC_ALL, 'en_US.UTF-8') # check locale-aware sorting
formatter = get_formatter('login')
base = formatter.FILTER_INCLUSIONS[0].copy()
base['MESSAGE_ID'] = [UUID(uuid) for uuid in base['MESSAGE_ID']]
for user in ['user1', 'user2', 'user1', 'User3']:
entry = base.copy()
entry['USER_ID'] = user
assert formatter.format(entry) == ''
assert formatter.flush().splitlines() == [
'',
'User logins:',
'',
' 2 x user1',
' 1 x user2',
' 1 x User3',
]
journal-brief-1.1.8/tests/format/test_reboot.py 0000664 0000000 0000000 00000002310 14167332244 0021617 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from journal_brief.format import get_formatter
import journal_brief.format.reboot # registers class; # noqa: F401
class TestRebootEntryFormatter(object):
def test_reboot(self):
formatter = get_formatter('reboot')
assert formatter.format({'_BOOT_ID': '1'}) == ''
assert formatter.format({'_BOOT_ID': '2'}) == '-- Reboot --\n'
assert formatter.format({'_BOOT_ID': '2'}) == ''
assert formatter.flush() == ''
journal-brief-1.1.8/tests/format/test_short.py 0000664 0000000 0000000 00000005050 14167332244 0021470 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from datetime import datetime, timezone, timedelta
from journal_brief.format import get_formatter
import journal_brief.format.short # registers class; # noqa: F401
import pytest
class TestShortEntryFormatter(object):
def test_timestamp(self):
dt = datetime.fromtimestamp(0, tz=timezone(timedelta(hours=1)))
entry = {'__REALTIME_TIMESTAMP': dt,
'MESSAGE': 'epoch'}
formatter = get_formatter('short')
# Should output in local time
expected = 'Jan 01 01:00:00'
assert expected in formatter.format(entry)
@pytest.mark.parametrize(('entry', 'expected'), [
({'MESSAGE': 'message'},
'localhost ?: message\n'),
({'_HOSTNAME': 'host',
'MESSAGE': 'message'},
'host ?: message\n'),
({'_HOSTNAME': 'host',
'_COMM': 'comm',
'MESSAGE': 'message'},
'host comm: message\n'),
({'_HOSTNAME': 'host',
'_COMM': 'comm',
'_PID': '1',
'MESSAGE': 'message'},
'host comm[1]: message\n'),
({'_HOSTNAME': 'host',
'SYSLOG_IDENTIFIER': 'syslogid',
'_COMM': 'comm',
'MESSAGE': 'message'},
'host syslogid: message\n'),
({'_HOSTNAME': 'host',
'SYSLOG_IDENTIFIER': 'syslogid',
'_PID': '1',
'MESSAGE': 'message'},
'host syslogid[1]: message\n'),
])
def test_format(self, entry, expected):
entry['__REALTIME_TIMESTAMP'] = datetime.fromtimestamp(0,
tz=timezone.utc)
formatter = get_formatter('short')
formatted = formatter.format(entry)
date = 'Jan 01 00:00:00 '
assert formatted.startswith(date)
assert formatted[len(date):] == expected
journal-brief-1.1.8/tests/format/test_systemd.py 0000664 0000000 0000000 00000003445 14167332244 0022027 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from journal_brief.format import get_formatter
import journal_brief.format.systemd # registers class; # noqa: F401
from locale import setlocale, LC_ALL
class TestSystemdEntryFormatter(object):
def test_no_failed_units(self):
formatter = get_formatter('systemd')
assert formatter.flush() == ''
def test_systemd(self):
setlocale(LC_ALL, 'en_US.UTF-8') # check locale-aware sorting
formatter = get_formatter('systemd')
base = formatter.FILTER_INCLUSIONS[0].copy()
for unit in ['unit1', 'unit2', 'unit1', 'Unit3']:
entry = base.copy()
entry.update({
'MESSAGE': 'Unit %s.service entered failed state.' % unit,
'UNIT': '%s.service' % unit,
})
assert formatter.format(entry) == ''
assert formatter.flush().splitlines() == [
'',
'Failed systemd units:',
'',
' 2 x unit1.service',
' 1 x unit2.service',
' 1 x Unit3.service',
]
journal-brief-1.1.8/tests/missing/ 0000775 0000000 0000000 00000000000 14167332244 0017101 5 ustar 00root root 0000000 0000000 journal-brief-1.1.8/tests/missing/__init__.py 0000664 0000000 0000000 00000000000 14167332244 0021200 0 ustar 00root root 0000000 0000000 journal-brief-1.1.8/tests/missing/systemd/ 0000775 0000000 0000000 00000000000 14167332244 0020571 5 ustar 00root root 0000000 0000000 journal-brief-1.1.8/tests/missing/systemd/__init__.py 0000664 0000000 0000000 00000000000 14167332244 0022670 0 ustar 00root root 0000000 0000000 journal-brief-1.1.8/tests/missing/systemd/journal/ 0000775 0000000 0000000 00000000000 14167332244 0022243 5 ustar 00root root 0000000 0000000 journal-brief-1.1.8/tests/missing/systemd/journal/__init__.py 0000664 0000000 0000000 00000002067 14167332244 0024361 0 ustar 00root root 0000000 0000000 from collections.abc import Iterator
LOG_EMERG = 0
LOG_ALERT = 1
LOG_CRIT = 2
LOG_ERR = 3
LOG_WARNING = 4
LOG_NOTICE = 5
LOG_INFO = 6
LOG_DEBUG = 7
DEFAULT_CONVERTERS = {}
class Reader(Iterator):
"""
Mock systemd.journal.Reader so we can run tests in its absence
"""
def get_next(self):
raise RuntimeError
def get_previous(self):
raise RuntimeError
def __next__(self):
entry = self.get_next()
if not entry:
raise StopIteration
return entry
def this_boot(self):
raise RuntimeError
def log_level(self, level):
raise RuntimeError
def add_disjunction(self):
raise RuntimeError
def add_conjunction(self):
raise RuntimeError
def add_match(self, *args, **kwargs):
raise RuntimeError
def seek_cursor(self, cursor):
raise RuntimeError
def seek_tail(self):
raise RuntimeError
def close(self):
pass
class Monotonic(object):
def __init__(self, init_tuple):
self.timestamp = init_tuple[0]
journal-brief-1.1.8/tests/requirements.txt 0000664 0000000 0000000 00000000021 14167332244 0020705 0 ustar 00root root 0000000 0000000 pytest-benchmark
journal-brief-1.1.8/tests/test_config.py 0000664 0000000 0000000 00000022304 14167332244 0020307 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015, 2020 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from tests.util import maybe_mock_systemd
maybe_mock_systemd()
from journal_brief.config import Config, ConfigError
import logging
import os
import pytest
from tempfile import NamedTemporaryFile
import yaml
logging.basicConfig(level=logging.DEBUG)
class TestConfig(object):
def test_no_config_file(self, tmpdir):
Config(config_file=os.path.join(str(tmpdir), 'nonexistent'))
@pytest.mark.parametrize('badyaml', [
"""
exclusions
- MESSAGE: [foo]
""",
])
def test_validation_bad_yaml(self, badyaml):
with NamedTemporaryFile(mode='wt') as cfp:
cfp.write(badyaml.strip())
cfp.flush()
with pytest.raises(ConfigError):
try:
Config(config_file=cfp.name)
except ConfigError as ex:
# Test the exception can be represented as a string
str(ex)
raise
@pytest.mark.parametrize('badconfig', [
"- not a map",
"disallowed: 1",
"cursor-file: [1]",
"debug: [1]",
"debug: debug",
"output: none",
"priority: -1",
"priority: [0, 1, 2, error, 2]",
# Test multiple errors
"""
disallowed: 1
cursor-file: [1]
debug: [1]
""",
])
def test_validation_bad(self, badconfig):
with NamedTemporaryFile(mode='wt') as cfp:
cfp.write(badconfig.strip())
cfp.flush()
with pytest.raises(ConfigError):
try:
Config(config_file=cfp.name)
except ConfigError as ex:
# Test the exception can be represented as a string
str(ex)
raise
@pytest.mark.parametrize('badconfig', [
"{key}: 1",
"""
{key}:
map: 1
""",
"""
{key}:
- 1
""",
"""
{key}:
- PRIORITY: [-1]
""",
"""
{key}:
- PRIORITY: -1
""",
"""
{key}:
- PRIORITY:
map: 1
""",
"""
{key}:
- MESSAGE: 1
""",
"""
{key}:
- MESSAGE: [baz]
- MESSAGE:
- foo
- [bar]
""",
])
@pytest.mark.parametrize('key', ['inclusions', 'exclusions'])
def test_validation_bad_inclusion_exclusion(self, key, badconfig):
with NamedTemporaryFile(mode='wt') as cfp:
cfp.write(badconfig.format(key=key).strip())
cfp.flush()
with pytest.raises(ConfigError):
Config(config_file=cfp.name)
# Test the exception can be represented as a string
try:
Config(config_file=cfp.name)
except ConfigError as ex:
str(ex)
@pytest.mark.parametrize('badconfig', [
"""
exclusions:
- MESSAGE: [/(mismatched parenth/]
""",
])
def test_validation_bad_regex(self, badconfig):
with NamedTemporaryFile(mode='wt') as cfp:
cfp.write(badconfig.strip())
cfp.flush()
with pytest.raises(ConfigError):
try:
Config(config_file=cfp.name)
except ConfigError as ex:
# Test the exception can be represented as a string
str(ex)
raise
@pytest.mark.parametrize('goodconfig, num_outputs', [
("output: [json-pretty, config]", 2),
("output: [cat]", 1),
("output: cat", 1),
])
def test_validation_good(self, goodconfig, num_outputs):
with NamedTemporaryFile(mode='wt') as cfp:
cfp.write(goodconfig.strip())
cfp.flush()
c = Config(config_file=cfp.name)
assert len(c['output']) == num_outputs
@pytest.mark.parametrize('badconfig', [
{
'from': 'foo',
'to': 'bar',
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'disallowed': '1',
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'suppress_empty': 'foo',
},
{
'from': 'foo',
'to': 'bar',
'command': [],
},
{
'from': 'foo',
'to': 'bar',
'smtp': [],
},
{
'from': 'foo',
'to': 'bar',
'command': 'foo',
'smtp': 'bar',
},
{
'from': 'foo',
'to': 'bar',
'smtp': {'disallowed': '1'},
},
{
'from': 'foo',
'command': 'baz',
},
{
'to': 'bar',
'command': 'baz',
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'subject': [],
},
{
'from': 'foo',
'to': 'bar',
'smtp': {
'host': [],
},
},
{
'from': 'foo',
'to': 'bar',
'smtp': {
'port': [],
},
},
{
'from': 'foo',
'to': 'bar',
'smtp': {
'starttls': 'baz',
},
},
{
'from': 'foo',
'to': 'bar',
'smtp': {
'user': [],
},
},
{
'from': 'foo',
'to': 'bar',
'smtp': {
'password': [],
},
},
{
'from': 'foo',
'to': {},
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'cc': {},
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'bcc': {},
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'headers': [],
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'headers': 'baz',
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'headers': {
'From': 'foo',
},
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'headers': {
'To': 'foo',
},
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'headers': {
'Cc': 'foo',
},
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'headers': {
'Bcc': 'foo',
},
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'headers': {
'from': 'foo',
},
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'headers': {
'TO': 'foo',
},
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'headers': {
'cC': 'foo',
},
},
{
'from': 'foo',
'to': 'bar',
'command': 'baz',
'headers': {
'BcC': 'foo',
},
},
])
def test_validation_email(self, badconfig):
with NamedTemporaryFile(mode='wt') as cfp:
cfp.write(yaml.dump({'email': badconfig}))
cfp.flush()
with pytest.raises(ConfigError):
try:
Config(config_file=cfp.name)
except ConfigError as ex:
# Test the exception can be represented as a string
str(ex)
raise
@pytest.mark.parametrize('oldconfig', [
{
'command': 'foo',
},
{
'smtp': {
'from': 'foo',
'to': 'bar',
'cc': 'baz',
'bcc': 'bat',
'subject': 'subj',
'headers': {
'blah': 'bluh',
},
},
},
])
def test_oldconfig_email(self, oldconfig):
with NamedTemporaryFile(mode='wt') as cfp:
cfp.write(yaml.dump({'email': oldconfig}))
cfp.flush()
Config(config_file=cfp.name)
journal-brief-1.1.8/tests/test_filter.py 0000664 0000000 0000000 00000027730 14167332244 0020337 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from tests.util import maybe_mock_systemd
maybe_mock_systemd()
from flexmock import flexmock
from io import StringIO
from journal_brief import JournalFilter
from journal_brief.filter import Inclusion, Exclusion
from journal_brief.format import EntryFormatter
import logging
import pytest
from systemd import journal
import yaml
try:
import pytest_benchmark
except ImportError:
HAVE_BENCHMARK = False
else:
HAVE_BENCHMARK = True
del pytest_benchmark
logging.basicConfig(level=logging.DEBUG)
@pytest.mark.skipif(not HAVE_BENCHMARK,
reason="install pytest-benchmark to run this test")
class TestFilterProfile(object):
def test_inclusion(self, benchmark):
matches = ['never matched {0}'.format(n) for n in range(100)]
rule = {'MESSAGE': matches}
for x in range(100):
rule['FIELD{0}'.format(x)] = 'never matched'
inclusion = Inclusion(rule)
entry = {
'MESSAGE': 'message',
'__CURSOR': '1',
}
for x in range(100):
entry['FIELD{0}'.format(x)] = x
assert not benchmark(inclusion.matches, entry)
def test_exclusion(self, benchmark):
matches = ['never matched {0}'.format(n) for n in range(100)]
rule = {'MESSAGE': matches}
for x in range(100):
rule['FIELD{0}'.format(x)] = '/never matched/'
exclusion = Exclusion(rule)
entry = {
'MESSAGE': 'message',
'__CURSOR': '1',
}
for x in range(100):
entry['FIELD{0}'.format(x)] = x
assert not benchmark(exclusion.matches, entry)
class TestInclusion(object):
def test_and(self):
inclusion = Inclusion({'MESSAGE': ['include this'],
'SYSLOG_IDENTIFIER': ['from this']})
assert inclusion.matches({'MESSAGE': 'include this',
'SYSLOG_IDENTIFIER': 'from this',
'IGNORE': 'ignore this'})
assert not inclusion.matches({'MESSAGE': 'include this'})
def test_or(self):
inclusion = Inclusion({'MESSAGE': ['include this', 'or this']})
assert inclusion.matches({'MESSAGE': 'include this',
'IGNORE': 'ignore this'})
assert not inclusion.matches({'MESSAGE': 'not this',
'IGNORE': 'ignore this'})
def test_and_or(self):
inclusion = Inclusion({'MESSAGE': ['include this', 'or this'],
'SYSLOG_IDENTIFIER': ['from this']})
assert inclusion.matches({'MESSAGE': 'include this',
'SYSLOG_IDENTIFIER': 'from this',
'IGNORE': 'ignore this'})
assert not inclusion.matches({'MESSAGE': 'include this',
'SYSLOG_IDENTIFIER': 'at your peril',
'IGNORE': 'ignore this'})
def test_priority(self):
inclusion = Inclusion({'PRIORITY': 'err'})
priority_type = journal.DEFAULT_CONVERTERS.get('PRIORITY', str)
assert inclusion.matches({'PRIORITY': priority_type(3)})
def test_repr(self):
incl = {'MESSAGE': ['include this']}
assert repr(Inclusion(incl))
class TestExclusion(object):
def test_and(self):
exclusion = Exclusion({'MESSAGE': ['exclude this'],
'SYSLOG_IDENTIFIER': ['from this']})
assert exclusion.matches({'MESSAGE': 'exclude this',
'SYSLOG_IDENTIFIER': 'from this',
'IGNORE': 'ignore this'})
assert not exclusion.matches({'MESSAGE': 'exclude this'})
def test_or(self):
exclusion = Exclusion({'MESSAGE': ['exclude this', 'or this']})
assert exclusion.matches({'MESSAGE': 'exclude this',
'IGNORE': 'ignore this'})
assert not exclusion.matches({'MESSAGE': 'not this',
'IGNORE': 'ignore this'})
def test_and_or(self):
exclusion = Exclusion({'MESSAGE': ['exclude this', 'or this'],
'SYSLOG_IDENTIFIER': ['from this']})
assert exclusion.matches({'MESSAGE': 'exclude this',
'SYSLOG_IDENTIFIER': 'from this',
'IGNORE': 'ignore this'})
assert not exclusion.matches({'MESSAGE': 'exclude this',
'SYSLOG_IDENTIFIER': 'at your peril',
'IGNORE': 'ignore this'})
def test_regexp(self):
exclusion = Exclusion({'MESSAGE': ['/exclude/'],
'FIELD': ['/exclude/']})
assert exclusion.matches({'MESSAGE': 'exclude this',
'FIELD': 'exclude this'})
assert not exclusion.matches({'MESSAGE': 'do not exclude',
'FIELD': 'do not exclude'})
assert not exclusion.matches({'MESSAGE': 'exclude',
'FIELD': 1})
def test_priority(self):
exclusion = Exclusion({'PRIORITY': 'err'})
priority_type = journal.DEFAULT_CONVERTERS.get('PRIORITY', str)
assert exclusion.matches({'PRIORITY': priority_type(3)})
def test_str_without_comment(self):
excl = {'MESSAGE': ['exclude this']}
unyaml = StringIO()
excl_str = str(Exclusion(excl))
assert '#' not in excl_str
unyaml.write(excl_str)
unyaml.seek(0)
assert yaml.safe_load(unyaml) == [excl]
def test_str_with_comment(self):
excl = {'MESSAGE': ['exclude this']}
unyaml = StringIO()
excl_str = str(Exclusion(excl, comment='comment'))
assert excl_str.startswith('# comment\n')
unyaml.write(excl_str)
unyaml.seek(0)
assert yaml.safe_load(unyaml) == [excl]
class MySpecialFormatter(EntryFormatter):
"""
Only for testing
"""
FORMAT_NAME = 'test'
FILTER_INCLUSIONS = [{'TEST': ['yes']}]
FILTER_EXCLUSIONS = [{'MESSAGE': ['ignore']}]
def __init__(self, *args, **kwargs):
super(MySpecialFormatter, self).__init__(*args, **kwargs)
self.entries_received = []
def format(self, entry):
self.entries_received.append(entry)
return entry.get('OUTPUT', '')
def flush(self):
# format() should handle None here
return None
class TestJournalFilter(object):
def test_no_exclusions(self):
entries = [{'MESSAGE': 'message 1'},
{'MESSAGE': 'message 2'}]
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return(entries[0])
.and_return(entries[1])
.and_return({}))
formatter = EntryFormatter()
jfilter = JournalFilter(journal.Reader(), [formatter])
output = StringIO()
jfilter.format(output)
output.seek(0)
lines = output.read().splitlines()
assert lines == [entry['MESSAGE'] for entry in entries]
def test_exclusion(self):
priority_type = journal.DEFAULT_CONVERTERS.get('PRIORITY', str)
entries = [{'MESSAGE': 'exclude this',
'SYSLOG_IDENTIFIER': 'from here'},
{'PRIORITY': priority_type(6),
'MESSAGE': 'exclude this too'},
{'MESSAGE': 'message 1',
'SYSLOG_IDENTIFIER': 'foo'},
{'MESSAGE': 'exclude this',
'SYSLOG_IDENTIFIER': 'at your peril'},
{'MESSAGE': 'message 2'}]
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return(entries[0])
.and_return(entries[1])
.and_return(entries[2])
.and_return(entries[3])
.and_return(entries[4])
.and_return({}))
exclusions = [{'MESSAGE': ['exclude this',
'and this'],
'SYSLOG_IDENTIFIER': ['from here']},
{'PRIORITY': ['info']}]
formatter = EntryFormatter()
jfilter = JournalFilter(journal.Reader(), [formatter],
default_exclusions=exclusions)
output = StringIO()
jfilter.format(output)
output.seek(0)
lines = output.read().splitlines()
assert lines == [entry['MESSAGE'] for entry in entries[2:]]
def test_exclusion_regexp(self):
entries = [{'MESSAGE': 'exclude this'},
{'MESSAGE': 'message 1'},
{'MESSAGE': 'exclude that'},
{'MESSAGE': 'message 2'}]
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return(entries[0])
.and_return(entries[1])
.and_return(entries[2])
.and_return(entries[3])
.and_return({}))
exclusions = [{'MESSAGE': ['/1/']}, # shouldn't exclude anything
{'MESSAGE': ['/exclude th/']},
{'MESSAGE': ['/exclude/']}]
formatter = EntryFormatter()
jfilter = JournalFilter(journal.Reader(), [formatter],
default_exclusions=exclusions)
output = StringIO()
jfilter.format(output)
output.seek(0)
lines = output.read().splitlines()
assert lines == [entry['MESSAGE']
for entry in [entries[1]] + [entries[3]]]
stats = jfilter.get_statistics()
for stat in stats:
if stat.exclusion['MESSAGE'] == ['/1/']:
assert stat.hits == 0
break
def test_statistics(self):
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return({'MESSAGE': 'exclude'})
.and_return({'MESSAGE': 'include'})
.and_return({}))
exclusions = [{'MESSAGE': ['exclude']}]
formatter = EntryFormatter()
jfilter = JournalFilter(journal.Reader(), [formatter],
default_exclusions=exclusions)
output = StringIO()
jfilter.format(output)
statistics = jfilter.get_statistics()
assert len(statistics) == 1
assert statistics[0].hits == 1
def test_formatter_filters(self):
incl_entries = [
{
'TEST': 'yes',
'MESSAGE': 'message',
},
{
'TEST': 'yes',
'MESSAGE': 'message',
'OUTPUT': None, # Test returning None from format()
},
]
excl_entries = [
{
'TEST': 'no',
'MESSAGE': 'message',
},
{
'TEST': 'yes',
'MESSAGE': 'ignore',
},
]
(flexmock(journal.Reader, add_match=None, add_disjunction=None)
.should_receive('get_next')
.and_return(incl_entries[0])
.and_return(incl_entries[1])
.and_return(excl_entries[0])
.and_return(excl_entries[1])
.and_return({}))
formatter = MySpecialFormatter()
jfilter = JournalFilter(journal.Reader(), [formatter])
jfilter.format(StringIO())
assert formatter.entries_received == incl_entries
journal-brief-1.1.8/tests/test_journal_brief.py 0000664 0000000 0000000 00000020474 14167332244 0021671 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from flexmock import flexmock
from inspect import getsourcefile
from tests.util import Watcher
import journal_brief
from journal_brief import SelectiveReader, LatestJournalEntries
from systemd import journal
import os
import pytest
import re
class TestSelectiveReader(object):
def watch_reader(self):
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return({}))
watcher = Watcher()
for func in ['add_match',
'add_conjunction',
'add_disjunction',
'log_level',
'this_boot']:
(flexmock(journal.Reader)
.should_receive(func)
.replace_with(watcher.watch_call(func)))
return watcher
def test_inclusions(self):
watcher = self.watch_reader()
inclusions = [{'PRIORITY': ['emerg', 'alert', 'crit', 'err']},
{'PRIORITY': ['4', '5', '6'],
'_SYSTEMD_UNIT': ['myservice.service']}]
SelectiveReader(log_level=0, this_boot=True, inclusions=inclusions)
# Should add matches for all of the first group
assert set(watcher.calls[:4]) == set([
('add_match', (), "{'PRIORITY': '0'}"),
('add_match', (), "{'PRIORITY': '1'}"),
('add_match', (), "{'PRIORITY': '2'}"),
('add_match', (), "{'PRIORITY': '3'}"),
])
# Then a this_boot() match
assert watcher.calls[4][0] == 'this_boot'
# Then a log_level() match
assert watcher.calls[5] == ('log_level', (0,), '{}')
# Then a disjunction
assert watcher.calls[6][0] == 'add_disjunction'
# Then matches for all of the second group
assert set(watcher.calls[7:11]) == set([
('add_match', (), "{'PRIORITY': '4'}"),
('add_match', (), "{'PRIORITY': '5'}"),
('add_match', (), "{'PRIORITY': '6'}"),
('add_match', (), "{'_SYSTEMD_UNIT': 'myservice.service'}"),
])
# Then a this_boot() match
assert watcher.calls[11][0] == 'this_boot'
# Then a log_level() match
assert watcher.calls[12] == ('log_level', (0,), '{}')
# No more
assert len(watcher.calls) == 13
def test_inclusion_log_level(self):
watcher = self.watch_reader()
inclusions = [{'PRIORITY': '0'}, # no effect, log_level==1
{'PRIORITY': '2'}]
SelectiveReader(log_level=1, inclusions=inclusions)
# Matches for {'PRIORITY': '0'}
assert set(watcher.calls[0:2]) == set([
('log_level', (0,), '{}'),
('log_level', (1,), '{}'),
])
# A disjunction
assert watcher.calls[2] == ('add_disjunction', (), '{}')
# Matches for {'PRIORITY': '2'}
assert set(watcher.calls[3:5]) == set([
('log_level', (2,), '{}'),
('log_level', (1,), '{}'),
])
# No more
assert len(watcher.calls) == 5
def test_no_inclusions(self):
watcher = self.watch_reader()
SelectiveReader(log_level=0, this_boot=True)
# Should have two matches
assert len(watcher.calls) == 2
# A this_boot() match
assert watcher.calls[0][0] == 'this_boot'
# And a log_level() match
assert watcher.calls[1] == ('log_level', (0,), '{}')
@pytest.fixture
def cursor_file_path(tmp_path):
return os.path.join(str(tmp_path), 'cursor')
@pytest.fixture
def cursor_file(cursor_file_path):
with open(cursor_file_path, 'w+t') as fp:
yield fp
@pytest.fixture
def missing_or_empty_cursor():
(flexmock(journal.Reader)
.should_receive('seek_tail')
.once())
(flexmock(journal.Reader)
.should_receive('get_previous')
.and_return({'__CURSOR': '0'}))
class TestLatestJournalEntries(object):
def test_without_cursor(self, cursor_file_path, missing_or_empty_cursor):
final_cursor = '2'
(flexmock(journal.Reader)
.should_receive('seek_cursor')
.never())
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return({'__CURSOR': '1'})
.and_return({'__CURSOR': final_cursor})
.and_return({}))
with LatestJournalEntries(cursor_file=cursor_file_path) as entries:
e = list(entries)
assert len(e) == 2
with open(cursor_file_path, 'rt') as fp:
assert fp.read() == final_cursor
def test_empty_cursor(self, cursor_file, missing_or_empty_cursor):
final_cursor = '2'
(flexmock(journal.Reader)
.should_receive('seek_cursor')
.never())
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return({'__CURSOR': '1'})
.and_return({'__CURSOR': final_cursor})
.and_return({}))
with LatestJournalEntries(cursor_file=cursor_file.name) as entries:
e = list(entries)
assert len(e) == 2
cursor_file.seek(0)
assert cursor_file.read() == final_cursor
def test_with_cursor(self, cursor_file):
last_cursor = '2'
final_cursor = '4'
results = [{'__CURSOR': last_cursor},
{'__CURSOR': '3'},
{'__CURSOR': final_cursor}]
(flexmock(journal.Reader)
.should_receive('seek_cursor')
.with_args(last_cursor)
.once())
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return(results[0])
.and_return(results[1])
.and_return(results[2])
.and_return({}))
cursor_file.write(last_cursor)
cursor_file.flush()
with LatestJournalEntries(cursor_file=cursor_file.name) as entries:
e = list(entries)
assert e == results[1:]
cursor_file.seek(0)
assert cursor_file.read() == final_cursor
def test_no_seek_cursor(self, cursor_file):
last_cursor = '2'
final_cursor = '3'
results = [{'__CURSOR': '1'},
{'__CURSOR': last_cursor},
{'__CURSOR': final_cursor}]
(flexmock(journal.Reader)
.should_receive('seek_cursor')
.never())
(flexmock(journal.Reader)
.should_receive('get_next')
.and_return(results[0])
.and_return(results[1])
.and_return(results[2])
.and_return({}))
cursor_file.write(last_cursor)
cursor_file.flush()
with LatestJournalEntries(cursor_file=cursor_file.name,
seek_cursor=False) as entries:
e = list(entries)
assert e == results
cursor_file.seek(0)
assert cursor_file.read() == final_cursor
def test_version():
"""
Check the version numbers agree
"""
this_file = getsourcefile(test_version)
regexp = re.compile(r"\s+version='([0-9.]+)', # also update")
topdir = os.path.dirname(os.path.dirname(this_file))
with open(os.path.join(topdir, 'setup.py')) as fp:
matches = map(regexp.match, fp.readlines())
matches = [match for match in matches if match]
assert len(matches) == 1
assert matches[0].groups()[0] == journal_brief.__version__
regexp = re.compile(r"^Version:\s+([0-9.]+)")
with open(os.path.join(topdir, 'python-journal-brief.spec')) as fp:
matches = map(regexp.match, fp.readlines())
matches = [match for match in matches if match]
assert len(matches) == 1
assert matches[0].groups()[0] == journal_brief.__version__
journal-brief-1.1.8/tests/util.py 0000664 0000000 0000000 00000002540 14167332244 0016760 0 ustar 00root root 0000000 0000000 """
Copyright (c) 2015 Tim Waugh
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
import functools
from inspect import getsourcefile
import os
import sys
def mock_systemd():
import tests.missing
mock_path = getsourcefile(tests.missing)
sys.path.append(os.path.dirname(mock_path))
def maybe_mock_systemd():
try:
from systemd import journal # noqa: F401
except ImportError:
mock_systemd()
class Watcher(object):
def __init__(self):
self.calls = []
def watch_call(self, func):
return functools.partial(self.called, func)
def called(self, func, *args, **kwargs):
self.calls.append((func, args, repr(kwargs)))