pax_global_header00006660000000000000000000000064146362432360014523gustar00rootroot0000000000000052 comment=0a7ac4ea53a8bd536343a29a1f694dd737816dc5
btrfsd-0.2.2/000077500000000000000000000000001463624323600130105ustar00rootroot00000000000000btrfsd-0.2.2/.clang-format000066400000000000000000000037121463624323600153660ustar00rootroot00000000000000---
BasedOnStyle: GNU
Language: Cpp
Standard: Cpp11
IndentWidth: 4
UseTab: Never
# maximum column width
ColumnLimit: 100
# brace breaking style like Linux
BreakBeforeBraces: Linux
# always break after an open bracket, if the parameters don’t fit on a single line
AlignAfterOpenBracket: Align
# align consecutive macros
AlignConsecutiveMacros: true
# horizontally align operands of binary and ternary expressions
AlignOperands: true
# align trailing comments
AlignTrailingComments: true
# don't allow putting all parameters of a function/declaration onto the next line
AllowAllArgumentsOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
# only merge empty blocks.
AllowShortBlocksOnASingleLine: Empty
# always break after the return type of top-level definitions
AlwaysBreakAfterReturnType: TopLevelDefinitions
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: false
# never pack parameters/arguments
BinPackParameters: false
BinPackArguments: false
# regroup include blocks
IncludeBlocks: Regroup
# never sort includes
SortIncludes: false
# space after casts
SpaceAfterCStyleCast: true
# we abuse this to make clang-format not touch g_auto* macros,
# as these should not have a space inserted before their open bracket
WhitespaceSensitiveMacros: ['g_autoptr', 'g_auto', '_', '__attribute__', 'G_DEFINE_QUARK']
# some attribute macros
AttributeMacros: ['G_GNUC_NULL_TERMINATED']
# statement macros
StatementMacros: ['']
# avoid breaking around an assignment operator
PenaltyBreakAssignment: 250
# left-align newline escapes, e.g. in macros
AlignEscapedNewlines: Left
# don't indent case labels
IndentCaseLabels: false
# don't reflow comments, this can cause issues with documentation / GIR annotations
ReflowComments: false
# all enums should be on their own line
AllowShortEnumsOnASingleLine: false
# break after operators
BreakBeforeBinaryOperators: None
# don't try to align structure arrays
AlignArrayOfStructures: None
btrfsd-0.2.2/.editorconfig000066400000000000000000000003461463624323600154700ustar00rootroot00000000000000# See https://editorconfig.org/
root = true
[*]
charset = utf-8
end_of_line = lf
trim_trailing_whitespace = true
max_line_length = 100
[*.{c,h}]
indent_style = space
indent_size = 4
[*.xml]
indent_style = space
indent_size = 2
btrfsd-0.2.2/.github/000077500000000000000000000000001463624323600143505ustar00rootroot00000000000000btrfsd-0.2.2/.github/workflows/000077500000000000000000000000001463624323600164055ustar00rootroot00000000000000btrfsd-0.2.2/.github/workflows/build-test.yml000066400000000000000000000065531463624323600212150ustar00rootroot00000000000000name: Build Test
on: [push, pull_request]
jobs:
build-debian-stable:
name: Debian Stable
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Create Build Environment
run: cd tests/ci/ && podman build -t btrfsd -f ./Dockerfile-debian-stable .
- name: Build
run: podman run -a stdout -a stderr -e COMPILER_VENDOR=$CVENDOR -e CC=gcc -e CXX=g++ -v `pwd`:/build btrfsd
./tests/ci/run-build.sh
- name: Test
run: podman run -a stdout -a stderr -e COMPILER_VENDOR=$CVENDOR -e CC=gcc -e CXX=g++ -v `pwd`:/build btrfsd
./tests/ci/run-tests.sh
build-debian-testing:
name: Debian Testing
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Create Build Environment
run: cd tests/ci/ && podman build -t btrfsd -f ./Dockerfile-debian-testing .
- name: Build
run: podman run -a stdout -a stderr -e COMPILER_VENDOR=$CVENDOR -e CC=gcc -e CXX=g++ -v `pwd`:/build btrfsd
./tests/ci/run-build.sh
- name: Test
run: podman run -a stdout -a stderr -e COMPILER_VENDOR=$CVENDOR -e CC=gcc -e CXX=g++ -v `pwd`:/build btrfsd
./tests/ci/run-tests.sh
build-fedora-latest:
name: Fedora Latest Stable
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Create Build Environment
run: cd tests/ci/ && podman build -t btrfsd -f ./Dockerfile-fedora-latest .
- name: Build
run: podman run -a stdout -a stderr -e COMPILER_VENDOR=$CVENDOR -e CC=gcc -e CXX=g++ -v `pwd`:/build btrfsd
./tests/ci/run-build.sh
- name: Test
run: podman run -a stdout -a stderr -e COMPILER_VENDOR=$CVENDOR -e CC=gcc -e CXX=g++ -v `pwd`:/build btrfsd
./tests/ci/run-tests.sh
build-ubuntu:
name: Ubuntu LTS
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v3
- name: Create Build Environment
run: sudo ./tests/ci/install-deps-deb.sh
- name: Build
run: CC=gcc CXX=g++ ./tests/ci/run-build.sh
- name: Test
run: CC=gcc CXX=g++ ./tests/ci/run-tests.sh
build-sanitized-debian:
name: Sanitizers on Debian
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Create Build Environment
run: cd tests/ci/ && podman build -t btrfsd -f ./Dockerfile-debian-testing .
- name: Build with asan, ubsan
run: podman run -a stdout -a stderr --privileged -e COMPILER_VENDOR=$CVENDOR -e CC=gcc -e CXX=g++ -v `pwd`:/build btrfsd
./tests/ci/run-build.sh sanitize
- name: Test with asan, ubsan
run: podman run -a stdout -a stderr --privileged -e COMPILER_VENDOR=$CVENDOR -e CC=gcc -e CXX=g++ -v `pwd`:/build btrfsd
./tests/ci/run-tests.sh sanitize
build-sanitized-fedora:
name: Sanitizers on Fedora
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Create Build Environment
run: cd tests/ci/ && podman build -t btrfsd -f ./Dockerfile-fedora-latest .
- name: Build with asan, ubsan
run: podman run -a stdout -a stderr --privileged -e COMPILER_VENDOR=$CVENDOR -e CC=gcc -e CXX=g++ -v `pwd`:/build btrfsd
./tests/ci/run-build.sh sanitize
- name: Test with asan, ubsan
run: podman run -a stdout -a stderr --privileged -e COMPILER_VENDOR=$CVENDOR -e CC=gcc -e CXX=g++ -v `pwd`:/build btrfsd
./tests/ci/run-tests.sh sanitize
btrfsd-0.2.2/.gitignore000066400000000000000000000006561463624323600150070ustar00rootroot00000000000000# Prerequisites
*.d
# Object files
*.o
*.ko
*.obj
*.elf
# Linker output
*.ilk
*.map
*.exp
# Precompiled Headers
*.gch
*.pch
# Libraries
*.lib
*.a
*.la
*.lo
# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
# Debug files
*.dSYM/
*.su
*.idb
*.pdb
# Kernel Module Compile Results
*.mod*
*.cmd
.tmp_versions/
modules.order
Module.symvers
Mkfile.old
dkms.conf
btrfsd-0.2.2/LICENSE000066400000000000000000000636361463624323600140330ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 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.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
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 and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, 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 library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete 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 distribute a copy of this License along with the
Library.
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 Library or any portion
of it, thus forming a work based on the Library, 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) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
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 Library, 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 Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you 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.
If distribution of 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 satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be 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.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library 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.
9. 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 Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
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 with
this License.
11. 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 Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library 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 Library.
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.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library 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.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser 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 Library
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 Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
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
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. 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 LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. 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.
Copyright (C)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; 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.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random
Hacker.
, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
btrfsd-0.2.2/NEWS.md000066400000000000000000000017401463624323600141100ustar00rootroot00000000000000Version 0.2.2
-------------
Released: 2024-06-24
Features:
* Only run all tasks once per filesystem
Bugfixes:
* Fix potential use of uninitialized variable
* Handle more error conditions in a noisy way when sending emails
Miscellaneous:
* ci: Install systemd-dev on modern Debian
Version 0.2.1
-------------
Released: 2023-10-14
Bugfixes:
* utils: Don't free result twice when checking if device is on battery
Version 0.2.0
-------------
Released: 2023-08-30
Features:
* Don't run balance periodically by default
* Autodetect btrfs executable location by default
* Don't run in containers, run 5min after boot
Bugfixes:
* scheduler: Take the launch time as reference time, so actions
are performed correctly every hour and will not be ignored.
* Don't make systemd timer persistent (so we are not run immediately
after every boot)
Miscellaneous:
* Add build/install instructions to README
Version 0.1.0
-------------
Released: 2023-08-24
Notes:
* Initial release
btrfsd-0.2.2/README.md000066400000000000000000000033621463624323600142730ustar00rootroot00000000000000# Btrfsd - Tiny Btrfs maintenance daemon
[](https://github.com/ximion/btrfsd/actions/workflows/build-test.yml)
Btrfsd is a lightweight daemon that takes care of all Btrfs filesystems on a Linux system.
It can:
* Check for detected errors and broadcast a warning if any were found,
or optionally send an email
* Perform scrub periodically if the system is not on battery
* Optionally schedule balancing operations as well
The daemon is explicitly designed to be run on any system, from a small notebook to a large
storage server. Depending on the system, it should make the best possible decision for
running maintenance jobs, but may also be tweaked by the user.
If no Btrfs filesystems are found, the daemon will be completely inert.
Btrfsd is called every hour via a systemd timer with the lowest CPU priority, so its impact
on system performance should be extremely low.
You can tweak the daemon's default settings by editing `/etc/btrfsd/settings.conf`,
check `man btrfsd(8)` for more documentation.
# Installation
Btrfsd is packaged in a few Linux distributions for easy installation:
[](https://repology.org/project/btrfsd/versions)
# Building
Btrfsd can be built & installed from source using the Meson build system.
It requires GLib, JSON-GLib, libsystemd, libmount and btrfs-progs.
On Debian-based systems, you can install all dependencies via:
```bash
sudo apt install btrfs-progs docbook-xsl libglib2.0-dev libjson-glib-dev libsystemd-dev meson xsltproc
```
You can the build the daemon:
```bash
mkdir build && cd build
meson setup --buildtype=debugoptimized ..
ninja
ninja install
```
btrfsd-0.2.2/RELEASE000066400000000000000000000015161463624323600140160ustar00rootroot00000000000000Btrfsd Release Notes
1. Set variables
OLD_VERSION="0.2.1"
NEW_VERSION="0.2.2"
2. Write NEWS.md entries for Btrfsd in the same format as usual.
git shortlog v$OLD_VERSION.. | grep -i -v trivial | grep -v Merge > NEWS.new
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Version 0.2.2
-------------
Released: 2023-xx-xx
Notes:
Features:
Bugfixes:
Miscellaneous:
Contributors:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3. Commit changes in Btrfsd git:
git commit -a -m "Release version $NEW_VERSION"
git tag -s -f -m "Release $NEW_VERSION" v$NEW_VERSION
git push --tags
git push
4. Do post release version bump in meson.build, RELEASE
5. Commit trivial changes:
git commit -a -m "trivial: post release version bump"
git push
6. Announce the new release
btrfsd-0.2.2/autoformat.py000077500000000000000000000101021463624323600155400ustar00rootroot00000000000000#!/usr/bin/env python3
#
# Copyright (C) 2015-2022 Matthias Klumpp
#
# SPDX-License-Identifier: LGPL-2.1+
#
# Format all source code in-place.
#
import os
import sys
import shutil
import fnmatch
import subprocess
import tempfile
from glob import glob
INCLUDE_LOCATIONS = [
'autoformat.py',
'src',
'tests',
]
EXCLUDE_MATCH = []
EXTRA_STYLE_RULES_FOR = [
(
[
'AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments',
'AlignConsecutiveAssignments: AcrossComments',
'PenaltyReturnTypeOnItsOwnLine: 1000',
],
[
'*/src/*.h',
],
),
]
def format_cpp_sources(sources, style_fname=None, extra_styles: list[str] = None):
"""Format C/C++ sources with clang-format."""
if not sources:
return
command = ['clang-format', '-i']
if extra_styles:
style_rules = []
if style_fname:
with open(style_fname, 'r') as f:
style_rules = [l.strip() for l in f.readlines()]
with tempfile.NamedTemporaryFile(mode='w') as fp:
style_rules.extend(extra_styles)
fp.write('\n'.join(style_rules))
fp.flush()
command.append('--style=file:{}'.format(fp.name))
command.extend(sources)
subprocess.run(command, check=True)
return
if style_fname:
command.append('--style=file:{}'.format(style_fname))
command.extend(sources)
subprocess.run(command, check=True)
def format_python_sources(sources):
"""Format Python sources with Black."""
command = [
'black',
'-S', # no string normalization
'-l',
'100', # line length
'-t',
'py311', # minimum Python target
]
command.extend(sources)
subprocess.run(command, check=True)
def run(current_dir, args):
# check for tools
if not shutil.which('clang-format'):
print(
'The `clang-format` formatter is not installed. Please install it to continue!',
file=sys.stderr,
)
return 1
if not shutil.which('black'):
print(
'The `black` formatter is not installed. Please install it to continue!',
file=sys.stderr,
)
return 1
# if no include directories are explicitly specified, we read all locations
if not INCLUDE_LOCATIONS:
INCLUDE_LOCATIONS.append('.')
# collect sources
cpp_sources = []
cpp_style_matches = [[]] * len(EXTRA_STYLE_RULES_FOR)
py_sources = []
for il_path_base in INCLUDE_LOCATIONS:
il_path = os.path.join(current_dir, il_path_base)
if os.path.isfile(il_path):
candidates = [il_path]
else:
candidates = glob(il_path + '/**/*', recursive=True)
for filename in candidates:
skip = False
for exclude in EXCLUDE_MATCH:
if fnmatch.fnmatch(filename, exclude):
skip = True
break
if skip:
continue
if filename.endswith(('.c', '.cpp', '.h', '.hpp')):
cpp_sources.append(filename)
for i, er in enumerate(EXTRA_STYLE_RULES_FOR):
for pattern in er[1]:
if fnmatch.fnmatch(filename, pattern):
cpp_style_matches[i].append(filename)
break
elif filename.endswith('.py'):
py_sources.append(filename)
# format
format_python_sources(py_sources)
format_cpp_sources(cpp_sources)
for i, er in enumerate(EXTRA_STYLE_RULES_FOR):
format_cpp_sources(
cpp_style_matches[i],
os.path.join(current_dir, '.clang-format'),
er[0],
)
return 0
if __name__ == '__main__':
thisfile = __file__
if not os.path.isabs(thisfile):
thisfile = os.path.normpath(os.path.join(os.getcwd(), thisfile))
thisdir = os.path.normpath(os.path.join(os.path.dirname(thisfile)))
os.chdir(thisdir)
sys.exit(run(thisdir, sys.argv[1:]))
btrfsd-0.2.2/data/000077500000000000000000000000001463624323600137215ustar00rootroot00000000000000btrfsd-0.2.2/data/btrfsd.service.in000066400000000000000000000003461463624323600171770ustar00rootroot00000000000000[Unit]
Description=Btrfs maintenance daemon
Documentation=man:btrfsd
After=local-fs.target fstrim.service
Wants=local-fs.target
[Service]
Type=simple
ExecStart=@BTRFSD_INSTALL_BIN@
IOSchedulingClass=idle
CPUSchedulingPolicy=idle
btrfsd-0.2.2/data/btrfsd.timer000066400000000000000000000002761463624323600162540ustar00rootroot00000000000000[Unit]
Description=Perform Btrfs maintenance actions
Documentation=man:btrfsd
ConditionVirtualization=!container
[Timer]
OnBootSec=5min
OnUnitActiveSec=1h
[Install]
WantedBy=timers.target
btrfsd-0.2.2/data/error-mail.tmpl000066400000000000000000000011121463624323600166630ustar00rootroot00000000000000From: {{mail_from}}
Subject: Btrfs device issue on {{date_time}} @ {{hostname}}
This is an automatically generated mail message from btrfsd
running on {{hostname}}.
An issue has been detected on the Btrfs device mounted as {{mountpoint}}.
You will be getting this email daily or even sooner if we detect an increasing
rate of errors.
Please fix the issues (replace the failing disk(s) if needed), or clear them
with `btrfs device stats --reset {{mountpoint}}`
Faithfully yours, etc.
P.S. Some helpful information about the filesystem:
{{issue_report}}
Filesystem usage:
{{fs_usage}}
btrfsd-0.2.2/data/meson.build000066400000000000000000000011331463624323600160610ustar00rootroot00000000000000
systemd_unit_dir = systemd_dep.get_variable(pkgconfig: 'systemdsystemunitdir')
bdsd_data = configuration_data()
bdsd_data.set('BTRFSD_INSTALL_BIN', get_option('prefix') / get_option('libexecdir') / 'btrfsd')
bdsd_service = configure_file(
input: 'btrfsd.service.in',
output: 'btrfsd.service',
configuration: bdsd_data
)
install_data(
bdsd_service,
install_dir: systemd_unit_dir
)
install_data(
'btrfsd.timer',
install_dir: systemd_unit_dir
)
# Install example configuration file
install_data(
'settings.conf',
install_dir: get_option('sysconfdir') / 'btrfsd'
)
btrfsd-0.2.2/data/settings.conf000066400000000000000000000006421463624323600164320ustar00rootroot00000000000000#
# Configuration for Btrfsd
#
# Settings can be adjusted per mountpoint,
# if no settings are defined for a mountpoint,
# the ones from the "default" section are used.
# Check man btrfsd(8) for more informtion.
[default]
# Address to send mails about filesystem errors to
mail_address=""
# Approximate intervals at which to execute
# maintenance actions.
stats_interval=1h
scrub_interval=1M
balance_interval=never
btrfsd-0.2.2/docs/000077500000000000000000000000001463624323600137405ustar00rootroot00000000000000btrfsd-0.2.2/docs/btrfsd.8.xml000066400000000000000000000100551463624323600161150ustar00rootroot00000000000000
18 Aug,2023">
]>
btrfsd2022-2023Matthias KlumppBtrfsd
&date;
btrfsd8btrfsdBtrfs maintenance daemon&package;
Description
This manual page documents briefly the &package; daemon.
Btrfsd is a lightweight daemon that takes care of all Btrfs filesystems on a Linux system.
It will:
Check stats for errors and broadcast a warning if any were found, or send an emailPerform scrub periodically if system is not on batteryRun balance occasionally if not on battery power
The daemon is explicitly designed to be run on any system, from a small notebook to a large
storage server. Depending on the system, it should make the best possible decision for
running maintenance jobs, but may also be tweaked by the user.
Configuration
The daemon will run on its own, without any configuration, and monitor all Btrfs filesystems mounted on the system
(or do nothing if none were found).
However, the user may tweak some settings via its configuration file: /etc/btrfsd/settings.conf
The configuration file is an Ini-style text file, with one section per Btrfs mount point. If no section for a mountpoint
with settings was found, the values from the default section are used.
Every *_interval maintenance action interval may contain an integer time value with a unit character behind it:
h for hours, d for days and M for months. The special value never will
prevent the action from being executed. Going below an hour for actions is not recommended, as &package; is only woken up hourly
by the system to check for pending actions.
Example:Command-line OptionsDisplay extra debugging information.Display the version number of &package;.Display the status of the daemon and its various tasks, as well as its configuration.See Alsobtrfs1.
AUTHOR
This manual page was written by Matthias Klumpp matthias@tenstral.net.
btrfsd-0.2.2/docs/meson.build000066400000000000000000000010651463624323600161040ustar00rootroot00000000000000
# make manual pages
xsltproc = find_program('xsltproc')
custom_target('man-btrfsd',
input: 'btrfsd.8.xml',
output: 'btrfsd.8',
install: true,
install_dir: join_paths(get_option('mandir'), 'man8'),
command: [
xsltproc,
'--nonet',
'--stringparam', 'man.output.quietly', '1',
'--stringparam', 'funcsynopsis.style', 'ansi',
'--stringparam', 'man.th.extra1.suppress', '1',
'-o', '@OUTPUT@',
'http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl',
'@INPUT@'
]
)
btrfsd-0.2.2/meson.build000066400000000000000000000111701463624323600151520ustar00rootroot00000000000000project('Btrfsd', 'c',
meson_version: '>=0.60',
default_options: ['c_std=c11', 'cpp_std=gnu++14'],
license: 'LGPL-2.1+',
version: '0.2.2',
)
cc = meson.get_compiler('c')
source_root = meson.project_source_root()
btrfsd_version = meson.project_version()
varr = btrfsd_version.split('.')
btrfsd_major_version = varr[0]
btrfsd_minor_version = varr[1]
btrfsd_micro_version = varr[2]
#
# Configure files
#
btrfs_exe_path = get_option('btrfs-cmd')
if btrfs_exe_path == 'auto'
btrfs_exe = find_program('btrfs', dirs: ['/usr/bin', '/usr/sbin', '/bin', '/sbin'], required : false)
btrfs_exe_path = btrfs_exe.found() ? btrfs_exe.full_path() : '/usr/bin/btrfs'
endif
message('Using `btrfs` executable:', btrfs_exe_path)
conf = configuration_data()
conf.set('BTRFSD_MAJOR_VERSION_CONF', btrfsd_major_version)
conf.set('BTRFSD_MINOR_VERSION_CONF', btrfsd_minor_version)
conf.set('BTRFSD_MICRO_VERSION_CONF', btrfsd_micro_version)
conf.set_quoted('PACKAGE_VERSION', btrfsd_version)
conf.set_quoted('GETTEXT_PACKAGE', 'btrfsd')
conf.set_quoted('LOCALEDIR',
get_option('prefix') / get_option('localedir'))
conf.set_quoted('LOCALSTATEDIR',
get_option('prefix') / get_option('localstatedir'))
conf.set_quoted('LIBEXECDIR',
get_option('prefix') / get_option('libexecdir'))
conf.set_quoted('DATADIR',
get_option('prefix') / get_option('datadir'))
conf.set_quoted('LIBDIR',
get_option('prefix') / get_option('libdir'))
conf.set_quoted('BINDIR',
get_option('prefix') / get_option('bindir'))
conf.set_quoted('SYSCONFDIR',
get_option('prefix') / get_option('sysconfdir'))
conf.set_quoted('BTRFS_CMD', btrfs_exe_path)
conf.set('HAVE_SYSTEMD', true)
conf.set('_DEFAULT_SOURCE', true)
configure_file(output: 'config.h', configuration: conf)
root_inc_dir = include_directories ('.')
if get_option('static-analysis') and host_machine.system() != 'windows'
if cc.get_id() != 'gcc'
error('You need to compile with GCC to run the static analyzer!')
endif
# enable statuc analyzer
add_project_arguments(['-fanalyzer'], language : 'c')
# make false-positive non-fatal with GCC 12 for now
if cc.version().version_compare('>11<13')
add_project_arguments(['-Wno-error=analyzer-use-of-uninitialized-value'], language : 'c')
endif
# g_error has a deliberate infinite loop, so we have to suppress the new warning for now
if cc.version().version_compare('>13<15')
add_project_arguments(['-Wno-error=analyzer-infinite-loop'], language : 'c')
endif
endif
#
# Custom C flags
#
sanitizer_libs = []
if get_option('maintainer')
maintainer_c_args = ['-Werror',
'-Wall',
'-Wextra',
'-Wcast-align',
'-Wno-uninitialized',
'-Wempty-body',
'-Winit-self',
'-Wnull-dereference',
'-Wfloat-equal',
'-Winline',
'-Wno-error=comment',
]
add_project_arguments(maintainer_c_args, language: 'c')
endif
# a few compiler warning flags we always want enabled
add_project_arguments(
cc.get_supported_arguments([
'-Werror=shadow',
'-Werror=empty-body',
'-Werror=strict-prototypes',
'-Werror=missing-prototypes',
'-Werror=implicit-function-declaration',
'-Werror=pointer-arith',
'-Werror=missing-declarations',
'-Werror=return-type',
'-Werror=int-conversion',
'-Werror=incompatible-pointer-types',
'-Werror=misleading-indentation',
'-Werror=missing-include-dirs',
'-Werror=declaration-after-statement',
'-Werror=format-security',
'-Wno-missing-field-initializers',
'-Wno-error=missing-field-initializers',
'-Wno-unused-parameter',
'-Wno-error=unused-parameter',
]),
language: 'c'
)
if cc.get_id() == 'clang'
# Clang doesn't understand autofree helpers on GMutexLocker and thinks
# these variables are irrelevant, so this warning when used with Clang
# gives many false-positives
add_project_arguments(
'-Wno-unused-variable',
language: 'c'
)
endif
#
# Dependencies
#
systemd_dep = dependency('systemd')
glib_dep = dependency('glib-2.0', version: '>= 2.72')
gobject_dep = dependency('gobject-2.0', version: '>= 2.72')
gio_dep = dependency('gio-2.0', version: '>= 2.72')
json_glib_dep = dependency('json-glib-1.0', version: '>= 1.6.2')
mount_dep = dependency('mount')
libsystemd_dep = dependency('libsystemd')
#
# Modules
#
fs = import('fs')
glib = import('gnome')
#
# Directories
#
subdir('src/')
subdir('data/')
subdir('tests/')
subdir('docs/')
btrfsd-0.2.2/meson_options.txt000066400000000000000000000007051463624323600164470ustar00rootroot00000000000000
option('btrfs-cmd',
type: 'string',
value: 'auto',
description: 'Path to the "btrfs" command, set to "auto" to autodetect.'
)
#
# For development
#
option('maintainer',
type : 'boolean',
value : false,
description : 'Enable maintainer mode (use strict compiler flags, e.g. -Werror)'
)
option('static-analysis',
type : 'boolean',
value : false,
description : 'Enable GCC static analysis support'
)
btrfsd-0.2.2/src/000077500000000000000000000000001463624323600135775ustar00rootroot00000000000000btrfsd-0.2.2/src/btd-filesystem.c000066400000000000000000000437331463624323600167100ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
/**
* SECTION:btd-filesystem
* @short_description: An active Btrfs mountpoint on the system.
*
* Defines an active Btrfs mountpoint on the current system, and can perform
* various actions on it.
*/
#include "config.h"
#include "btd-filesystem.h"
#include
#include
#include "btd-utils.h"
#include "btd-logging.h"
typedef struct {
gchar *device_name;
gchar *mountpoint;
dev_t devno;
} BtdFilesystemPrivate;
enum {
PROP_0,
PROP_DEVICE_NAME,
PROP_DEVNO,
PROP_MOUNTPOINT,
N_PROPERTIES
};
static GParamSpec *obj_properties[N_PROPERTIES] = {
NULL,
};
G_DEFINE_TYPE_WITH_PRIVATE (BtdFilesystem, btd_filesystem, G_TYPE_OBJECT)
#define GET_PRIVATE(o) (btd_filesystem_get_instance_private (o))
/**
* btd_btrfs_error_quark:
*
* Return value: An error quark.
*/
G_DEFINE_QUARK (btd-btrfs-error-quark, btd_btrfs_error)
/**
* btd_find_mounted_btrfs_filesystems:
*
* Find all mounted Btrfs filesystems on the current system.
*
* Returns: (transfer container) (element-type BtdFilesystem): mounted Btrfs filesystems
*/
GPtrArray *
btd_find_mounted_btrfs_filesystems (GError **error)
{
struct libmnt_table *table;
struct libmnt_iter *iter;
struct libmnt_fs *fs;
g_autoptr(GPtrArray) result = NULL;
table = mnt_new_table ();
iter = mnt_new_iter (MNT_ITER_FORWARD);
/* load the current mount table */
if (mnt_table_parse_mtab (table, NULL) != 0) {
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, "Failed to parse mount table");
goto out;
}
/* enlist all btrfs filesystems */
result = g_ptr_array_new_with_free_func (g_object_unref);
while (mnt_table_next_fs (table, iter, &fs) == 0) {
if (g_strcmp0 (mnt_fs_get_fstype (fs), "btrfs") == 0) {
BtdFilesystem *bmount = btd_filesystem_new (mnt_fs_get_source (fs),
mnt_fs_get_devno (fs),
mnt_fs_get_target (fs));
g_ptr_array_add (result, bmount);
}
}
out:
mnt_free_iter (iter);
mnt_free_table (table);
return g_steal_pointer (&result);
}
static void
btd_filesystem_init (BtdFilesystem *self)
{
BtdFilesystemPrivate *priv = GET_PRIVATE (self);
priv->device_name = NULL;
}
static void
btd_filesystem_finalize (GObject *object)
{
BtdFilesystem *bmount = BTD_FILESYSTEM (object);
BtdFilesystemPrivate *priv = GET_PRIVATE (bmount);
g_free (priv->device_name);
g_free (priv->mountpoint);
G_OBJECT_CLASS (btd_filesystem_parent_class)->finalize (object);
}
static void
btd_filesystem_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
BtdFilesystem *self = BTD_FILESYSTEM (object);
BtdFilesystemPrivate *priv = GET_PRIVATE (self);
switch (property_id) {
case PROP_DEVICE_NAME:
g_free (priv->device_name);
priv->device_name = g_value_dup_string (value);
break;
case PROP_DEVNO:
priv->devno = g_value_get_uint64 (value);
break;
case PROP_MOUNTPOINT:
g_free (priv->mountpoint);
priv->mountpoint = g_value_dup_string (value);
if (btd_is_empty (priv->mountpoint))
g_critical ("Mountpoint for %s is empty!", priv->device_name);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void
btd_filesystem_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec)
{
BtdFilesystem *self = BTD_FILESYSTEM (object);
BtdFilesystemPrivate *priv = GET_PRIVATE (self);
switch (property_id) {
case PROP_DEVICE_NAME:
g_value_set_string (value, priv->device_name);
break;
case PROP_DEVNO:
g_value_set_uint64 (value, priv->devno);
break;
case PROP_MOUNTPOINT:
g_value_set_string (value, priv->mountpoint);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void
btd_filesystem_class_init (BtdFilesystemClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->finalize = btd_filesystem_finalize;
object_class->set_property = btd_filesystem_set_property;
object_class->get_property = btd_filesystem_get_property;
obj_properties[PROP_DEVICE_NAME] = g_param_spec_string ("device_name",
"DeviceName",
"Device property",
NULL,
G_PARAM_READWRITE |
G_PARAM_CONSTRUCT_ONLY);
obj_properties[PROP_DEVNO] = g_param_spec_uint64 ("devno",
"Devno",
"Physical device number",
0,
G_MAXUINT64,
0,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY);
obj_properties[PROP_MOUNTPOINT] = g_param_spec_string ("mountpoint",
"Mountpoint",
"Mountpoint property",
NULL,
G_PARAM_READWRITE |
G_PARAM_CONSTRUCT_ONLY);
g_object_class_install_properties (object_class, N_PROPERTIES, obj_properties);
}
/**
* btd_filesystem_new:
*
* Creates a new #BtdFilesystem.
*
* Returns: (transfer full): a #BtdFilesystem
*/
BtdFilesystem *
btd_filesystem_new (const gchar *device, dev_t devno, const gchar *mountpoint)
{
BtdFilesystem *self;
self = g_object_new (BTD_TYPE_FILESYSTEM,
"device_name",
device,
"devno",
(guint64) devno,
"mountpoint",
mountpoint,
NULL);
return BTD_FILESYSTEM (self);
}
/**
* btd_filesystem_get_device_name:
* @self: An instance of #BtdFilesystem.
*
* Returns: The device name backing this mountpoint.
*/
const gchar *
btd_filesystem_get_device_name (BtdFilesystem *self)
{
BtdFilesystemPrivate *priv = GET_PRIVATE (self);
return priv->device_name;
}
/**
* btd_filesystem_get_mountpoint:
* @self: An instance of #BtdFilesystem.
*
* Returns: The mountpoint path.
*/
const gchar *
btd_filesystem_get_mountpoint (BtdFilesystem *self)
{
BtdFilesystemPrivate *priv = GET_PRIVATE (self);
return priv->mountpoint;
}
/**
* btd_filesystem_get_devno:
* @self: An instance of #BtdFilesystem.
*
* Returns: The device number.
*/
dev_t
btd_filesystem_get_devno (BtdFilesystem *self)
{
BtdFilesystemPrivate *priv = GET_PRIVATE (self);
return priv->devno;
}
/**
* btd_filesystem_read_usage:
* @self: An instance of #BtdFilesystem.
* @error: A #GError
*
* Read filesystem usage information (btrfs fi df).
*
* Returns: The Btrfs usage report.
*/
gchar *
btd_filesystem_read_usage (BtdFilesystem *self, GError **error)
{
BtdFilesystemPrivate *priv = GET_PRIVATE (self);
GError *tmp_error = NULL;
gint btrfs_exit_code;
g_autofree gchar *df_output = NULL;
g_autofree gchar *stderr_output = NULL;
gchar *command[] = { BTRFS_CMD, "fi", "df", priv->mountpoint, NULL };
if (!g_spawn_sync (NULL, /* working directory */
command,
NULL, /* envp */
G_SPAWN_DEFAULT,
NULL,
NULL,
&df_output,
&stderr_output,
&btrfs_exit_code,
&tmp_error)) {
g_propagate_prefixed_error (error, tmp_error, "Failed to execute btrfs fi df command:");
return FALSE;
}
if (btrfs_exit_code != 0) {
g_set_error (error,
BTD_BTRFS_ERROR,
BTD_BTRFS_ERROR_FAILED,
"Running btrfs fi df has failed: %s",
btd_strstripnl (stderr_output));
return FALSE;
}
return btd_strstripnl (g_steal_pointer (&df_output));
}
static gchar *
btd_parse_btrfs_device_stats (JsonArray *array, guint64 *errors_count)
{
g_autoptr(GString) intro_text = NULL;
g_autoptr(GString) issues_text = NULL;
guint64 total_errors = 0;
intro_text = g_string_new ("Registered Devices:\n");
issues_text = g_string_new ("Issue Report:\n");
for (guint i = 0; i < json_array_get_length (array); i++) {
JsonObject *obj = json_array_get_object_element (array, i);
const gchar *device = json_object_get_string_member (obj, "device");
const gchar *devid = json_object_get_string_member (obj, "devid");
gint64 write_io_errs = json_object_get_int_member (obj, "write_io_errs");
gint64 read_io_errs = json_object_get_int_member (obj, "read_io_errs");
gint64 flush_io_errs = json_object_get_int_member (obj, "flush_io_errs");
gint64 corruption_errs = json_object_get_int_member (obj, "corruption_errs");
gint64 generation_errs = json_object_get_int_member (obj, "generation_errs");
total_errors = write_io_errs + read_io_errs + flush_io_errs + corruption_errs +
generation_errs;
if (errors_count != NULL)
*errors_count = total_errors;
/* add device to the known devices list */
g_string_append_printf (intro_text, " • %s\n", device);
/* if there are no errors, we don't add that information to the report */
if (total_errors == 0)
continue;
/* we have issues, make a full report */
g_string_append_printf (issues_text, "Device: %s\n", device);
g_string_append_printf (issues_text, "Devid: %s\n", devid);
g_string_append_printf (issues_text,
"Write IO Errors: %" G_GINT64_FORMAT "\n",
write_io_errs);
g_string_append_printf (issues_text,
"Read IO Errors: %" G_GINT64_FORMAT "\n",
read_io_errs);
g_string_append_printf (issues_text,
"Flush IO Errors: %" G_GINT64_FORMAT "\n",
flush_io_errs);
g_string_append_printf (issues_text,
"Corruption Errors: %" G_GINT64_FORMAT "\n",
corruption_errs);
g_string_append_printf (issues_text,
"Generation Errors: %" G_GINT64_FORMAT "\n\n",
generation_errs);
}
/* finalize report */
if (total_errors == 0)
g_string_append (issues_text, " • No errors found\n");
g_string_append (intro_text, "\n");
g_string_prepend (issues_text, intro_text->str);
/* drop trailing newlines */
g_string_truncate (issues_text, issues_text->len - 2);
return g_string_free (g_steal_pointer (&issues_text), FALSE);
}
/**
* btd_filesystem_read_error_stats:
* @self: An instance of #BtdFilesystem.
* @report: (out) (optional) (not nullable): Destination of a string report text.
* @errors_count: (out) (optional): Number of detected erros
* @error: A #GError, set if we failed to read statistics.
*
* Returns: %TRUE if stats were read successfully.
*/
gboolean
btd_filesystem_read_error_stats (BtdFilesystem *self,
gchar **report,
guint64 *errors_count,
GError **error)
{
BtdFilesystemPrivate *priv = GET_PRIVATE (self);
GError *tmp_error = NULL;
gint btrfs_exit_code;
g_autofree gchar *stats_output = NULL;
g_autofree gchar *stderr_output = NULL;
g_autoptr(JsonParser) parser = NULL;
g_autofree gchar *tmp_report = NULL;
JsonObject *root = NULL;
JsonArray *device_stats = NULL;
gchar *command[] = { BTRFS_CMD, "--format=json", "device", "stats", priv->mountpoint, NULL };
btd_debug ("Running btrfs device stats on %s", priv->mountpoint);
if (!g_spawn_sync (NULL, /* working directory */
command,
NULL, /* envp */
G_SPAWN_DEFAULT,
NULL,
NULL,
&stats_output,
&stderr_output,
&btrfs_exit_code,
&tmp_error)) {
g_propagate_prefixed_error (error, tmp_error, "Failed to execute btrfs stats command:");
return FALSE;
}
if (btrfs_exit_code != 0) {
g_set_error (error,
BTD_BTRFS_ERROR,
BTD_BTRFS_ERROR_FAILED,
"Running btrfs stats has failed: %s",
btd_strstripnl (stderr_output));
return FALSE;
}
parser = json_parser_new ();
if (!json_parser_load_from_data (parser, stats_output, -1, &tmp_error)) {
g_propagate_prefixed_error (error, tmp_error, "Failed to parse btrfs stats JSON:");
return FALSE;
}
root = json_node_get_object (json_parser_get_root (parser));
device_stats = json_object_get_array_member (root, "device-stats");
if (device_stats == NULL) {
g_set_error_literal (error,
BTD_BTRFS_ERROR,
BTD_BTRFS_ERROR_PARSE,
"Failed to parse stats output: No 'device-stats' section.");
return FALSE;
}
/* parse stats & generate report */
tmp_report = btd_parse_btrfs_device_stats (device_stats, errors_count);
if (report != NULL)
*report = g_steal_pointer (&tmp_report);
return TRUE;
}
/**
* btd_filesystem_scrub:
* @self: An instance of #BtdFilesystem.
* @error: A #GError, set if scrub failed.
*
* Returns: %TRUE if scrub operation completed without errors.
*/
gboolean
btd_filesystem_scrub (BtdFilesystem *self, GError **error)
{
BtdFilesystemPrivate *priv = GET_PRIVATE (self);
GError *tmp_error = NULL;
gint btrfs_exit_code;
g_autofree gchar *btrfs_stdout = NULL;
g_autofree gchar *btrfs_stderr = NULL;
gchar *command[] = { BTRFS_CMD, "-q", "scrub", "start", "-B", priv->mountpoint, NULL };
btd_info ("Running btrfs scrub on %s", priv->mountpoint);
if (!g_spawn_sync (NULL, /* working directory */
command,
NULL, /* envp */
G_SPAWN_DEFAULT,
NULL,
NULL,
&btrfs_stdout,
&btrfs_stderr,
&btrfs_exit_code,
&tmp_error)) {
g_propagate_prefixed_error (error, tmp_error, "Failed to execute btrfs scrub command:");
return FALSE;
}
if (btrfs_exit_code != 0) {
g_autofree gchar *output_msg = NULL;
btrfs_stdout = btd_strstripnl (btrfs_stdout);
btrfs_stderr = btd_strstripnl (btrfs_stderr);
if (btd_is_empty (btrfs_stdout))
output_msg = g_steal_pointer (&btrfs_stderr);
else if (btd_is_empty (btrfs_stderr))
output_msg = g_steal_pointer (&btrfs_stdout);
else
output_msg = g_strconcat (btrfs_stderr, "\n", btrfs_stdout, NULL);
g_set_error (error,
BTD_BTRFS_ERROR,
BTD_BTRFS_ERROR_SCRUB_FAILED,
"Scrub action failed: %s",
output_msg);
return FALSE;
}
/* scrub ran successfully */
return TRUE;
}
/**
* btd_filesystem_balance:
* @self: An instance of #BtdFilesystem.
* @error: A #GError, set if scrub failed.
*
* Run balance operation with some sensible defaults.
*
* Returns: %TRUE if balance operation completed without errors.
*/
gboolean
btd_filesystem_balance (BtdFilesystem *self, GError **error)
{
BtdFilesystemPrivate *priv = GET_PRIVATE (self);
GError *tmp_error = NULL;
gint btrfs_exit_code;
g_autofree gchar *btrfs_stdout = NULL;
g_autofree gchar *btrfs_stderr = NULL;
gchar *command[] = { BTRFS_CMD, "balance", "start", "--enqueue",
"-dusage=15", "-musage=10", priv->mountpoint, NULL };
btd_info ("Running btrfs balance on %s", priv->mountpoint);
if (!g_spawn_sync (NULL, /* working directory */
command,
NULL, /* envp */
G_SPAWN_DEFAULT,
NULL,
NULL,
&btrfs_stdout,
&btrfs_stderr,
&btrfs_exit_code,
&tmp_error)) {
g_propagate_prefixed_error (error, tmp_error, "Failed to execute btrfs balance command:");
return FALSE;
}
if (btrfs_exit_code != 0) {
g_autofree gchar *output_msg = NULL;
btrfs_stdout = btd_strstripnl (btrfs_stdout);
btrfs_stderr = btd_strstripnl (btrfs_stderr);
if (btd_is_empty (btrfs_stdout))
output_msg = g_steal_pointer (&btrfs_stderr);
else if (btd_is_empty (btrfs_stderr))
output_msg = g_steal_pointer (&btrfs_stdout);
else
output_msg = g_strconcat (btrfs_stderr, "\n", btrfs_stdout, NULL);
g_set_error (error,
BTD_BTRFS_ERROR,
BTD_BTRFS_ERROR_SCRUB_FAILED,
"Balance action failed: %s",
output_msg);
return FALSE;
}
/* balance ran successfully */
return TRUE;
}
btrfsd-0.2.2/src/btd-filesystem.h000066400000000000000000000036501463624323600167070ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
#pragma once
#include
G_BEGIN_DECLS
/**
* BtdBtrfsError:
* @BTD_BTRFS_ERROR_FAILED: Generic failure
* @BTD_BTRFS_ERROR_PARSE: Data parsing failed
* @BTD_BTRFS_ERROR_SCRUB_FAILED: Scrub operation failed.
*
* The error type.
**/
typedef enum {
BTD_BTRFS_ERROR_FAILED,
BTD_BTRFS_ERROR_PARSE,
BTD_BTRFS_ERROR_SCRUB_FAILED,
/*< private >*/
BTD_BTRFS_ERROR_LAST
} BtdBtrfsError;
#define BTD_BTRFS_ERROR btd_btrfs_error_quark ()
GQuark btd_btrfs_error_quark (void);
#define BTD_TYPE_FILESYSTEM (btd_filesystem_get_type ())
G_DECLARE_DERIVABLE_TYPE (BtdFilesystem, btd_filesystem, BTD, FILESYSTEM, GObject)
struct _BtdFilesystemClass {
GObjectClass parent_class;
/*< private >*/
void (*_as_reserved1) (void);
void (*_as_reserved2) (void);
void (*_as_reserved3) (void);
void (*_as_reserved4) (void);
void (*_as_reserved5) (void);
void (*_as_reserved6) (void);
};
GPtrArray *btd_find_mounted_btrfs_filesystems (GError **error);
BtdFilesystem *btd_filesystem_new (const gchar *device, dev_t devno, const gchar *mountpoint);
const gchar *btd_filesystem_get_device_name (BtdFilesystem *self);
const gchar *btd_filesystem_get_mountpoint (BtdFilesystem *self);
dev_t btd_filesystem_get_devno (BtdFilesystem *self);
gchar *btd_filesystem_read_usage (BtdFilesystem *self, GError **error);
gboolean btd_filesystem_read_error_stats (BtdFilesystem *self,
gchar **report,
guint64 *errors_count,
GError **error);
gboolean btd_filesystem_scrub (BtdFilesystem *self, GError **error);
gboolean btd_filesystem_balance (BtdFilesystem *self, GError **error);
G_END_DECLS
btrfsd-0.2.2/src/btd-fs-record.c000066400000000000000000000236621463624323600164070ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
/**
* SECTION:btd-fs-record
* @short_description: Helper class to store state about a mounted Btrfs filesystem.
*
* Store state about a Btrfs mountpoint for later use.
*/
#include "config.h"
#include "btd-fs-record.h"
#include "btd-utils.h"
typedef struct {
gchar *mountpoint;
GKeyFile *state;
gboolean is_new;
} BtdFsRecordPrivate;
enum {
PROP_0,
PROP_MOUNTPOINT,
N_PROPERTIES
};
static GParamSpec *obj_properties[N_PROPERTIES] = {
NULL,
};
G_DEFINE_TYPE_WITH_PRIVATE (BtdFsRecord, btd_fs_record, G_TYPE_OBJECT)
#define GET_PRIVATE(o) (btd_fs_record_get_instance_private (o))
/**
* btd_btrfs_action_to_string:
* @kind: the %BtdBtrfsAction.
*
* Converts the enumerated value to a text representation.
*
* Returns: string version of @kind
**/
const gchar *
btd_btrfs_action_to_string (BtdBtrfsAction kind)
{
if (kind == BTD_BTRFS_ACTION_STATS)
return "stats";
if (kind == BTD_BTRFS_ACTION_SCRUB)
return "scrub";
if (kind == BTD_BTRFS_ACTION_BALANCE)
return "balance";
return "unknown";
}
/**
* btd_btrfs_action_from_string:
* @str: the string.
*
* Converts the text representation to an enumerated value.
*
* Returns: a #BtdBtrfsAction or %BTD_BTRFS_ACTION_UNKNOWN for unknown.
**/
BtdBtrfsAction
btd_btrfs_action_from_string (const gchar *str)
{
if (btd_str_equal0 (str, "stats"))
return BTD_BTRFS_ACTION_STATS;
if (btd_str_equal0 (str, "scrub"))
return BTD_BTRFS_ACTION_SCRUB;
if (btd_str_equal0 (str, "balance"))
return BTD_BTRFS_ACTION_BALANCE;
return BTD_BTRFS_ACTION_UNKNOWN;
}
/**
* btd_btrfs_action_to_human_string:
* @kind: the %BtdBtrfsAction.
*
* Converts the enumerated value to a human-readable text representation.
*
* Returns: string version of @kind
**/
const gchar *
btd_btrfs_action_to_human_string (BtdBtrfsAction kind)
{
if (kind == BTD_BTRFS_ACTION_STATS)
return "Check for Issues";
if (kind == BTD_BTRFS_ACTION_SCRUB)
return "Scrub Filesystem";
if (kind == BTD_BTRFS_ACTION_BALANCE)
return "Balance Filesystem";
return "Unknown Action";
}
static void
btd_fs_record_init (BtdFsRecord *self)
{
BtdFsRecordPrivate *priv = GET_PRIVATE (self);
priv->state = g_key_file_new ();
}
static void
btd_fs_record_finalize (GObject *object)
{
BtdFsRecord *bmount = BTD_FS_RECORD (object);
BtdFsRecordPrivate *priv = GET_PRIVATE (bmount);
g_free (priv->mountpoint);
g_key_file_unref (priv->state);
G_OBJECT_CLASS (btd_fs_record_parent_class)->finalize (object);
}
static void
btd_fs_record_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
BtdFsRecord *self = BTD_FS_RECORD (object);
BtdFsRecordPrivate *priv = GET_PRIVATE (self);
switch (property_id) {
case PROP_MOUNTPOINT:
g_free (priv->mountpoint);
priv->mountpoint = g_value_dup_string (value);
if (btd_is_empty (priv->mountpoint))
g_critical ("Mountpoint for record file is empty!");
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void
btd_fs_record_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec)
{
BtdFsRecord *self = BTD_FS_RECORD (object);
BtdFsRecordPrivate *priv = GET_PRIVATE (self);
switch (property_id) {
case PROP_MOUNTPOINT:
g_value_set_string (value, priv->mountpoint);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void
btd_fs_record_class_init (BtdFsRecordClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->finalize = btd_fs_record_finalize;
object_class->set_property = btd_fs_record_set_property;
object_class->get_property = btd_fs_record_get_property;
obj_properties[PROP_MOUNTPOINT] = g_param_spec_string ("mountpoint",
"Mountpoint",
"Mountpoint property",
NULL,
G_PARAM_READWRITE |
G_PARAM_CONSTRUCT_ONLY);
g_object_class_install_properties (object_class, N_PROPERTIES, obj_properties);
}
/**
* btd_fs_record_new:
*
* Creates a new #BtdFsRecord.
*
* Returns: (transfer full): a #BtdFsRecord
*/
BtdFsRecord *
btd_fs_record_new (const gchar *mountpoint)
{
BtdFsRecord *self;
self = g_object_new (BTD_TYPE_FS_RECORD, "mountpoint", mountpoint, NULL);
return BTD_FS_RECORD (self);
}
static gchar *
btd_fs_record_get_state_filename (BtdFsRecord *self)
{
BtdFsRecordPrivate *priv = GET_PRIVATE (self);
g_autofree gchar *state_path = NULL;
g_autofree gchar *state_filename = NULL;
g_autofree gchar *btrfsd_state_dir = NULL;
state_filename = btd_path_to_filename (priv->mountpoint);
btrfsd_state_dir = btd_get_state_dir ();
state_path = g_strconcat (btrfsd_state_dir, "/", state_filename, ".state", NULL);
return g_steal_pointer (&state_path);
}
/**
* btd_fs_record_load:
* @self: An instance of #BtdFsRecord.
* @error: A #GError
*
* Load mount record.
*
* Returns: %TRUE on success.
*/
gboolean
btd_fs_record_load (BtdFsRecord *self, GError **error)
{
BtdFsRecordPrivate *priv = GET_PRIVATE (self);
g_autofree gchar *state_path = NULL;
state_path = btd_fs_record_get_state_filename (self);
if (g_file_test (state_path, G_FILE_TEST_EXISTS)) {
if (!g_key_file_load_from_file (priv->state, state_path, G_KEY_FILE_NONE, error))
return FALSE;
} else {
priv->is_new = TRUE;
/* the file did not exist yet, so we cheat and assume all jobs recently ran, so we don't run every job immediately */
for (guint j = BTD_BTRFS_ACTION_UNKNOWN + 1; j < BTD_BTRFS_ACTION_LAST; j++) {
/* running "stats" immediately is fine, the more expensive actions should wait */
if (j != BTD_BTRFS_ACTION_STATS)
btd_fs_record_set_last_action_time_now (self, j);
}
}
return TRUE;
}
/**
* btd_fs_record_save:
* @self: An instance of #BtdFsRecord.
* @error: A #GError
*
* Save mount record.
*
* Returns: %TRUE on success.
*/
gboolean
btd_fs_record_save (BtdFsRecord *self, GError **error)
{
BtdFsRecordPrivate *priv = GET_PRIVATE (self);
g_autofree gchar *state_path = NULL;
state_path = btd_fs_record_get_state_filename (self);
return g_key_file_save_to_file (priv->state, state_path, error);
}
/**
* btd_fs_record_is_new:
* @self: An instance of #BtdFsRecord.
*
* Check if the record file was just created.
*
* returns: %TRUE if the state record is new.
*/
gboolean
btd_fs_record_is_new (BtdFsRecord *self)
{
BtdFsRecordPrivate *priv = GET_PRIVATE (self);
return priv->is_new;
}
/**
* btd_fs_record_get_mountpoint:
* @self: An instance of #BtdFsRecord.
*
* Returns: The mountpoint path.
*/
const gchar *
btd_fs_record_get_mountpoint (BtdFsRecord *self)
{
BtdFsRecordPrivate *priv = GET_PRIVATE (self);
return priv->mountpoint;
}
/**
* btd_fs_record_set_mountpoint:
* @self: An instance of #BtdFsRecord.
* @mount_path: The new mountpoint path.
*
* Set a new mountpoint path.
*/
void
btd_fs_record_set_mountpoint (BtdFsRecord *self, const gchar *mount_path)
{
BtdFsRecordPrivate *priv = GET_PRIVATE (self);
g_free (priv->mountpoint);
priv->mountpoint = g_strdup (mount_path);
}
/**
* btd_fs_record_get_last_action_time:
* @self: An instance of #BtdFsRecord.
* @action_kind: The %BtdBtrfsAction to check for.
*
* Returns: Last UNIX timestamp when the action was run, or 0 if never.
*/
gint64
btd_fs_record_get_last_action_time (BtdFsRecord *self, BtdBtrfsAction action_kind)
{
BtdFsRecordPrivate *priv = GET_PRIVATE (self);
return g_key_file_get_int64 (priv->state,
"times",
btd_btrfs_action_to_string (action_kind),
NULL);
}
/**
* btd_fs_record_set_last_action_time_now:
* @self: An instance of #BtdFsRecord.
* @action_kind: The %BtdBtrfsAction.
*
* Set the last time the action was performed to now.
*/
void
btd_fs_record_set_last_action_time_now (BtdFsRecord *self, BtdBtrfsAction action_kind)
{
BtdFsRecordPrivate *priv = GET_PRIVATE (self);
g_key_file_set_uint64 (priv->state,
"times",
btd_btrfs_action_to_string (action_kind),
(gint64) time (NULL));
}
/**
* btd_fs_record_get_value_int:
* @self: An instance of #BtdFsRecord.
* @group_name: The group.
* @key: The key to look at.
* @default_value: A default value.
*
* Returns: The selected value.
*/
gint64
btd_fs_record_get_value_int (BtdFsRecord *self,
const gchar *group_name,
const gchar *key,
gint64 default_value)
{
BtdFsRecordPrivate *priv = GET_PRIVATE (self);
gint64 value;
g_autoptr(GError) error = NULL;
value = g_key_file_get_int64 (priv->state, group_name, key, &error);
if (error != NULL)
return default_value;
return value;
}
/**
* btd_fs_record_get_value_int:
* @self: An instance of #BtdFsRecord.
* @group_name: The group.
* @key: The key to look at.
* @default_value: A default value.
*
* Set en integer value in the state record.
*/
void
btd_fs_record_set_value_int (BtdFsRecord *self,
const gchar *group_name,
const gchar *key,
gint64 value)
{
BtdFsRecordPrivate *priv = GET_PRIVATE (self);
g_key_file_set_uint64 (priv->state, group_name, key, value);
}
btrfsd-0.2.2/src/btd-fs-record.h000066400000000000000000000044041463624323600164050ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
#pragma once
#include
G_BEGIN_DECLS
#define BTD_TYPE_FS_RECORD (btd_fs_record_get_type ())
G_DECLARE_DERIVABLE_TYPE (BtdFsRecord, btd_fs_record, BTD, FS_RECORD, GObject)
struct _BtdFsRecordClass {
GObjectClass parent_class;
/*< private >*/
void (*_as_reserved1) (void);
void (*_as_reserved2) (void);
void (*_as_reserved3) (void);
void (*_as_reserved4) (void);
void (*_as_reserved5) (void);
void (*_as_reserved6) (void);
};
/**
* BtdBtrfsAction:
* @BTD_BTRFS_ACTION_UNKNOWN: Unknown action
* @BTD_BTRFS_ACTION_STATS: Stats action
* @BTD_BTRFS_ACTION_SCRUB: Scrub action
* @BTD_BTRFS_ACTION_BALANCE: Balance action
*
* A Btrfs action that we perform.
**/
typedef enum {
BTD_BTRFS_ACTION_UNKNOWN,
BTD_BTRFS_ACTION_STATS,
BTD_BTRFS_ACTION_SCRUB,
BTD_BTRFS_ACTION_BALANCE,
/*< private >*/
BTD_BTRFS_ACTION_LAST
} BtdBtrfsAction;
const gchar *btd_btrfs_action_to_string (BtdBtrfsAction kind);
BtdBtrfsAction btd_btrfs_action_from_string (const gchar *str);
const gchar *btd_btrfs_action_to_human_string (BtdBtrfsAction kind);
BtdFsRecord *btd_fs_record_new (const gchar *mountpoint);
gboolean btd_fs_record_load (BtdFsRecord *self, GError **error);
gboolean btd_fs_record_save (BtdFsRecord *self, GError **error);
gboolean btd_fs_record_is_new (BtdFsRecord *self);
const gchar *btd_fs_record_get_mountpoint (BtdFsRecord *self);
void btd_fs_record_set_mountpoint (BtdFsRecord *self, const gchar *mount_path);
gint64 btd_fs_record_get_last_action_time (BtdFsRecord *self, BtdBtrfsAction action_kind);
void btd_fs_record_set_last_action_time_now (BtdFsRecord *self, BtdBtrfsAction action_kind);
gint64 btd_fs_record_get_value_int (BtdFsRecord *self,
const gchar *group_name,
const gchar *key,
gint64 default_value);
void btd_fs_record_set_value_int (BtdFsRecord *self,
const gchar *group_name,
const gchar *key,
gint64 value);
G_END_DECLS
btrfsd-0.2.2/src/btd-logging.c000066400000000000000000000100311463624323600161330ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
/**
* SECTION:btd-logging
* @short_description: Logging / syslog helpers
*
* Logging utility functions for Btrfsd.
*/
#include "config.h"
#include "btd-logging.h"
#include
#include
#include
#include
#include
#ifdef HAVE_SYSTEMD
#include
#include
#endif
typedef enum {
LB_SYSLOG,
LB_JOURNAL,
LB_CONSOLE
} LogBackend;
static LogBackend _log_backend = LB_CONSOLE;
/**
* btd_is_tty:
*
* returns: %TRUE if stdout is a tty.
*/
gboolean
btd_is_tty (void)
{
return isatty (fileno (stdout));
}
/**
* btd_logging_setup:
* @verbose: %TRUE if verbose logging should be enabled.
*
* Setup logging facilities.
*/
void
btd_logging_setup (gboolean verbose)
{
if (verbose)
g_setenv ("G_MESSAGES_DEBUG", "all", TRUE);
if (btd_is_tty ()) {
/* only log to console if we have a tty */
_log_backend = LB_CONSOLE;
g_debug ("Logging to console.");
return;
}
#ifdef HAVE_SYSTEMD
_log_backend = LB_JOURNAL;
if (sd_booted () <= 0) {
g_info ("Not booted with systemd, using syslog instead of journal.");
_log_backend = LB_SYSLOG;
} else {
g_debug ("Logging to journal.");
}
#endif
if (_log_backend == LB_SYSLOG) {
openlog ("btrfsd", LOG_PID | LOG_CONS, LOG_DAEMON);
g_debug ("Logging to syslog.");
}
}
/**
* btd_logging_finalize:
*
* Finish logging.
*/
void
btd_logging_finalize (void)
{
if (_log_backend == LB_SYSLOG)
closelog ();
}
static void
btd_log_va (BtdLogLevel level, const gchar *format, va_list args)
{
int log_priority;
g_autofree gchar *formatted_message = NULL;
formatted_message = g_strdup_vprintf (format, args);
if (_log_backend == LB_CONSOLE) {
switch (level) {
case BTD_LOG_LEVEL_INFO:
g_print ("I: %s\n", formatted_message);
break;
case BTD_LOG_LEVEL_WARNING:
g_print ("W: %s\n", formatted_message);
break;
case BTD_LOG_LEVEL_ERROR:
g_critical ("%s", formatted_message);
break;
default:
g_debug ("%s", formatted_message);
break;
}
return;
}
switch (level) {
case BTD_LOG_LEVEL_INFO:
log_priority = LOG_INFO;
break;
case BTD_LOG_LEVEL_WARNING:
log_priority = LOG_WARNING;
break;
case BTD_LOG_LEVEL_ERROR:
log_priority = LOG_ERR;
break;
default:
log_priority = LOG_DEBUG;
break;
}
#ifdef HAVE_SYSTEMD
if (_log_backend == LB_JOURNAL) {
sd_journal_print (log_priority, "%s", formatted_message);
return;
}
#endif
/* log with syslog if we haven't written the log message elsewhere */
syslog (log_priority, "%s", formatted_message);
}
/**
* btd_log:
* @level: The log level.
* @format: The string to log.
*
* Log a message.
*/
void
btd_log (BtdLogLevel level, const gchar *format, ...)
{
va_list args;
va_start (args, format);
btd_log_va (level, format, args);
va_end (args);
}
/**
* btd_debug:
*
* Log a debug message.
*/
void
btd_debug (const gchar *format, ...)
{
va_list args;
va_start (args, format);
btd_log_va (BTD_LOG_LEVEL_DEBUG, format, args);
va_end (args);
}
/**
* btd_info:
*
* Log an info message.
*/
void
btd_info (const gchar *format, ...)
{
va_list args;
va_start (args, format);
btd_log_va (BTD_LOG_LEVEL_INFO, format, args);
va_end (args);
}
/**
* btd_warning:
*
* Log a warning message.
*/
void
btd_warning (const gchar *format, ...)
{
va_list args;
va_start (args, format);
btd_log_va (BTD_LOG_LEVEL_WARNING, format, args);
va_end (args);
}
/**
* btd_error:
*
* Log an error message.
*/
void
btd_error (const gchar *format, ...)
{
va_list args;
va_start (args, format);
btd_log_va (BTD_LOG_LEVEL_ERROR, format, args);
va_end (args);
}
btrfsd-0.2.2/src/btd-logging.h000066400000000000000000000020151463624323600161430ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
#pragma once
#include
G_BEGIN_DECLS
/**
* BtdLogLevel:
* @BTD_LOG_LEVEL_DEBUG: Debug level
* @BTD_LOG_LEVEL_INFO: Info level
* @BTD_LOG_LEVEL_WARNING: Warning level
* @BTD_LOG_LEVEL_ERROR: Error level
*
* The log message priority.
**/
typedef enum {
BTD_LOG_LEVEL_DEBUG,
BTD_LOG_LEVEL_INFO,
BTD_LOG_LEVEL_WARNING,
BTD_LOG_LEVEL_ERROR,
/*< private >*/
BTD_LOG_LEVEL_LAST
} BtdLogLevel;
gboolean btd_is_tty (void);
void btd_logging_setup (gboolean verbose);
void btd_logging_finalize (void);
void btd_log (BtdLogLevel level, const gchar *format, ...) G_GNUC_PRINTF (2, 3);
void btd_debug (const gchar *format, ...) G_GNUC_PRINTF (1, 2);
void btd_info (const gchar *format, ...) G_GNUC_PRINTF (1, 2);
void btd_warning (const gchar *format, ...) G_GNUC_PRINTF (1, 2);
void btd_error (const gchar *format, ...) G_GNUC_PRINTF (1, 2);
G_END_DECLS
btrfsd-0.2.2/src/btd-mailer.c000066400000000000000000000106771463624323600157760ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
/**
* SECTION:btd-mailer
* @short_description: Send E-Mail messages.
*
* Helper functions to send E-Mail messages.
*/
#include "config.h"
#include "btd-mailer.h"
#include
#include
#include
#include
#include
/**
* btd_mail_error_quark:
*
* Return value: An error quark.
*/
G_DEFINE_QUARK (btd-mail-error-quark, btd_mail_error)
/**
* btd_have_sendmail:
*
* Returns: %TRUE if the sendmail program is available.
*/
gboolean
btd_have_sendmail (void)
{
g_autofree gchar *sendmail_exe = NULL;
sendmail_exe = g_find_program_in_path ("sendmail");
return sendmail_exe != NULL;
}
/**
* btd_send_email:
* @to_address: Address to send the mail to.
* @body: The message body, including the subject line
* @error: A #GError.
*
* Send any E-Mail via sendmail.
*
* Return: %TRUE on success.
*/
gboolean
btd_send_email (const gchar *to_address, const gchar *body, GError **error)
{
g_autofree gchar *sendmail_exe = NULL;
g_autofree gchar *email_content = NULL;
size_t email_content_len;
ssize_t write_result;
g_autoptr(GError) tmp_error = NULL;
const gchar *sm_argv[3];
GPid child_pid;
gint stdin_fd;
gint exit_status;
sendmail_exe = g_find_program_in_path ("sendmail");
if (sendmail_exe == NULL) {
g_set_error_literal (error,
BTD_MAIL_ERROR,
BTD_MAIL_ERROR_FAILED,
"Unable to find the `sendmail` command, can not send emails.");
return FALSE;
}
email_content = g_strdup_printf ("To: %s\n%s", to_address, body);
sm_argv[0] = sendmail_exe;
sm_argv[1] = "-t";
sm_argv[2] = NULL;
if (!g_spawn_async_with_pipes (NULL,
(gchar **) sm_argv,
NULL,
G_SPAWN_DO_NOT_REAP_CHILD,
NULL,
NULL,
&child_pid,
&stdin_fd,
NULL,
NULL,
&tmp_error)) {
g_propagate_prefixed_error (error, tmp_error, "Failed to send mail with sendmail:");
return FALSE;
}
/* write email content to stdin of sendmail */
email_content_len = strlen (email_content);
write_result = write (stdin_fd, email_content, email_content_len);
close (stdin_fd);
g_spawn_close_pid (child_pid);
if (write_result == -1) {
g_set_error_literal (error,
BTD_MAIL_ERROR,
BTD_MAIL_ERROR_FAILED,
"Failed to write email content to sendmail process.");
return FALSE;
} else if ((size_t) write_result < email_content_len) {
g_set_error (error,
BTD_MAIL_ERROR,
BTD_MAIL_ERROR_FAILED,
"Could not write all data to sendmail: only %zd of %zu bytes written.",
write_result,
email_content_len);
return FALSE;
}
waitpid (child_pid, &exit_status, 0);
if (exit_status != 0) {
g_set_error (error,
BTD_MAIL_ERROR,
BTD_MAIL_ERROR_FAILED,
"Sendmail failed with exist status %d",
exit_status);
return FALSE;
}
return TRUE;
}
/**
* btd_broadcast_message:
* @message: The message to send.
*
* Broadcast a message to all users, like `wall` does.
*/
void
btd_broadcast_message (const gchar *message)
{
struct utmp *utmp_entry;
gint fd;
/* open the utmp file */
setutent ();
/* read each entry from the utmp file */
while ((utmp_entry = getutent ()) != NULL) {
/* check if the entry is a user process */
if (utmp_entry->ut_type == USER_PROCESS) {
/* open the terminal device */
g_autofree gchar *term_path = g_strconcat ("/dev/", utmp_entry->ut_line, NULL);
fd = open (term_path, O_WRONLY);
if (fd != -1) {
/* write the message to the terminal */
(void) !write (fd, message, strlen (message));
close (fd);
}
}
}
/* close the utmp file */
endutent ();
}
btrfsd-0.2.2/src/btd-mailer.h000066400000000000000000000011761463624323600157750ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
#pragma once
#include
G_BEGIN_DECLS
/**
* BtdMailError:
* @BTD_MAIL_ERROR_FAILED: Generic failure
*
* The error type.
**/
typedef enum {
BTD_MAIL_ERROR_FAILED,
/*< private >*/
BTD_MAIL_ERROR_LAST
} BtdMailError;
#define BTD_MAIL_ERROR btd_mail_error_quark ()
GQuark btd_mail_error_quark (void);
gboolean btd_have_sendmail (void);
gboolean btd_send_email (const gchar *to_address, const gchar *body, GError **error);
void btd_broadcast_message (const gchar *message);
G_END_DECLS
btrfsd-0.2.2/src/btd-scheduler.c000066400000000000000000000573441463624323600165050ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
/**
* SECTION:btd-scheduler
* @short_description: Scheduler for Btrfs maintenance actions.
*
* Schedules various maintenance actions according to the user's preferences.
*/
#include "config.h"
#include "btd-scheduler.h"
#include "btd-utils.h"
#include "btd-logging.h"
#include "btd-mailer.h"
#include "btd-filesystem.h"
#include "btd-fs-record.h"
typedef struct {
gboolean loaded;
GPtrArray *mountpoints;
GKeyFile *config;
gchar *state_dir;
time_t reference_time;
gulong default_intervals[BTD_BTRFS_ACTION_LAST];
} BtdSchedulerPrivate;
G_DEFINE_TYPE_WITH_PRIVATE (BtdScheduler, btd_scheduler, G_TYPE_OBJECT)
#define GET_PRIVATE(o) (btd_scheduler_get_instance_private (o))
typedef gboolean (*BtdActionFunction) (BtdScheduler *, BtdFilesystem *, BtdFsRecord *);
static void
btd_scheduler_init (BtdScheduler *self)
{
BtdSchedulerPrivate *priv = GET_PRIVATE (self);
gulong seconds_in_month;
priv->config = g_key_file_new ();
priv->state_dir = btd_get_state_dir ();
seconds_in_month = btd_parse_duration_string ("1M");
for (guint i = 0; i < BTD_BTRFS_ACTION_LAST; i++)
priv->default_intervals[i] = seconds_in_month;
}
static void
btd_scheduler_finalize (GObject *object)
{
BtdScheduler *self = BTD_SCHEDULER (object);
BtdSchedulerPrivate *priv = GET_PRIVATE (self);
g_free (priv->state_dir);
g_key_file_unref (priv->config);
if (priv->mountpoints != NULL)
g_ptr_array_unref (priv->mountpoints);
G_OBJECT_CLASS (btd_scheduler_parent_class)->finalize (object);
}
static void
btd_scheduler_class_init (BtdSchedulerClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->finalize = btd_scheduler_finalize;
}
/**
* btd_scheduler_new:
*
* Creates a new #BtdScheduler.
*
* Returns: (transfer full): a #BtdScheduler
*/
BtdScheduler *
btd_scheduler_new ()
{
BtdScheduler *self;
self = g_object_new (BTD_TYPE_SCHEDULER, NULL);
return BTD_SCHEDULER (self);
}
static gchar *
btd_get_interval_key (BtdBtrfsAction action_kind)
{
return g_strconcat (btd_btrfs_action_to_string (action_kind), "_interval", NULL);
}
static gulong
btd_scheduler_get_config_duration_str (BtdScheduler *self,
const gchar *group,
const gchar *key,
const gchar *default_value)
{
BtdSchedulerPrivate *priv = GET_PRIVATE (self);
g_autofree gchar *value = NULL;
value = g_key_file_get_string (priv->config, group, key, NULL);
if (value == NULL)
return btd_parse_duration_string (default_value);
return btd_parse_duration_string (value);
}
static gulong
btd_scheduler_get_config_duration (BtdScheduler *self,
const gchar *group,
const gchar *key,
gulong default_value)
{
BtdSchedulerPrivate *priv = GET_PRIVATE (self);
g_autofree gchar *value = NULL;
value = g_key_file_get_string (priv->config, group, key, NULL);
if (value == NULL)
return default_value;
return btd_parse_duration_string (value);
}
static gulong
btd_scheduler_get_config_duration_for_action (BtdScheduler *self,
BtdFilesystem *bfs,
BtdBtrfsAction action_kind)
{
BtdSchedulerPrivate *priv = GET_PRIVATE (self);
g_autofree gchar *key_name = NULL;
key_name = btd_get_interval_key (action_kind);
return btd_scheduler_get_config_duration (self,
btd_filesystem_get_mountpoint (bfs),
key_name,
priv->default_intervals[action_kind]);
}
static gchar *
btd_scheduler_get_config_value (BtdScheduler *self,
BtdFilesystem *bfs,
const gchar *key,
const gchar *default_value)
{
BtdSchedulerPrivate *priv = GET_PRIVATE (self);
g_autofree gchar *value = NULL;
if (bfs == NULL) {
value = g_key_file_get_string (priv->config, "default", key, NULL);
if (value == NULL)
return g_strdup (default_value);
return g_steal_pointer (&value);
}
value = g_key_file_get_string (priv->config, btd_filesystem_get_mountpoint (bfs), key, NULL);
if (value == NULL) {
/* check generic section */
value = g_key_file_get_string (priv->config, "default", key, NULL);
if (value == NULL)
return g_strdup (default_value);
}
return g_steal_pointer (&value);
}
/**
* btd_scheduler_load:
* @self: An instance of #BtdScheduler
* @error: A #GError
*
* Load scheduler data and set up data structures.
*
* Returns: %TRUE on success.
*/
gboolean
btd_scheduler_load (BtdScheduler *self, GError **error)
{
BtdSchedulerPrivate *priv = GET_PRIVATE (self);
const gchar *config_fname = SYSCONFDIR "/btrfsd/settings.conf";
GError *tmp_error = NULL;
if (priv->loaded) {
g_set_error_literal (error,
BTD_BTRFS_ERROR,
BTD_BTRFS_ERROR_FAILED,
"Tried to initialize already initialized scheduler.");
return FALSE;
}
/* The origin reference time when the scheduler was loaded, "current time".
* We reduce the current time by a minute, just in case there were any delays after cron
* called us, so we for sure run all remaining tasks if we are called again in an hour. */
priv->reference_time = time (NULL) - 60;
if (priv->mountpoints != NULL)
g_ptr_array_unref (priv->mountpoints);
priv->mountpoints = btd_find_mounted_btrfs_filesystems (error);
if (priv->mountpoints == NULL)
return FALSE;
if (g_file_test (config_fname, G_FILE_TEST_EXISTS)) {
if (!g_key_file_load_from_file (priv->config, config_fname, G_KEY_FILE_NONE, &tmp_error)) {
g_propagate_prefixed_error (error, tmp_error, "Failed to load configuration:");
return FALSE;
}
btd_debug ("Loaded configuration: %s", config_fname);
}
priv->default_intervals[BTD_BTRFS_ACTION_SCRUB] = btd_scheduler_get_config_duration_str (
self,
"default",
btd_get_interval_key (BTD_BTRFS_ACTION_SCRUB),
"1M");
priv->default_intervals[BTD_BTRFS_ACTION_STATS] = btd_scheduler_get_config_duration_str (
self,
"default",
btd_get_interval_key (BTD_BTRFS_ACTION_STATS),
"1h");
priv->default_intervals[BTD_BTRFS_ACTION_BALANCE] = btd_scheduler_get_config_duration_str (
self,
"default",
btd_get_interval_key (BTD_BTRFS_ACTION_BALANCE),
"never");
priv->loaded = TRUE;
return TRUE;
}
static gboolean
btd_scheduler_send_error_mail (BtdScheduler *self,
BtdFilesystem *bfs,
BtdFsRecord *record,
gboolean new_errors_found,
const gchar *mail_address,
const gchar *issue_report)
{
BtdSchedulerPrivate *priv = GET_PRIVATE (self);
g_autoptr(GBytes) template_bytes = NULL;
g_autofree gchar *mail_from = NULL;
g_autofree gchar *formatted_time = NULL;
g_autofree gchar *mail_body = NULL;
g_autofree gchar *fs_usage = NULL;
g_autoptr(GError) error = NULL;
g_autoptr(GDateTime) dt_now = g_date_time_new_now_local ();
time_t time_last_mail;
time_last_mail = btd_fs_record_get_value_int (record, "messages", "issue_mail_sent", 0);
if (!new_errors_found && (priv->reference_time - time_last_mail) < SECONDS_IN_AN_HOUR * 20) {
g_autofree gchar *time_waiting_str = btd_humanize_time (
(SECONDS_IN_AN_HOUR * 20) - (priv->reference_time - time_last_mail));
btd_debug ("Issue email for '%s' already sent and no new issues found, will send "
"a reminder in %s if the issues persist.",
btd_filesystem_get_mountpoint (bfs),
time_waiting_str);
return TRUE;
}
btd_debug ("Sending issue mail to %s", mail_address);
formatted_time = g_date_time_format (dt_now, "%Y-%m-%d %H:%M:%S");
mail_from = btd_scheduler_get_config_value (self, bfs, "mail_from", NULL);
if (mail_from == NULL)
mail_from = g_strdup ("btrfsd");
template_bytes = btd_get_resource_data ("/btrfsd/error-mail.tmpl");
if (template_bytes == NULL) {
btd_error ("Failed to find error-mail template data. This is a bug.");
return FALSE;
}
fs_usage = btd_filesystem_read_usage (bfs, NULL);
if (fs_usage == NULL)
fs_usage = g_strdup ("⚠ Failed to read usage data.");
mail_body = btd_render_template (g_bytes_get_data (template_bytes, NULL),
"mail_from",
mail_from,
"date_time",
formatted_time,
"hostname",
g_get_host_name (),
"mountpoint",
btd_filesystem_get_mountpoint (bfs),
"issue_report",
issue_report,
"fs_usage",
fs_usage,
NULL);
if (!btd_send_email (mail_address, mail_body, &error)) {
btd_warning ("Failed to send issue mail: %s", error->message);
return FALSE;
}
/* we have sent the mail, record that fact so we don't spam messages too frequently */
btd_fs_record_set_value_int (record, "messages", "issue_mail_sent", priv->reference_time);
return TRUE;
}
static gboolean
btd_scheduler_run_stats (BtdScheduler *self, BtdFilesystem *bfs, BtdFsRecord *record)
{
BtdSchedulerPrivate *priv = GET_PRIVATE (self);
g_autofree gchar *mail_address = NULL;
g_autofree gchar *issue_report = NULL;
guint64 error_count = 0;
guint64 prev_error_count = 0;
g_autoptr(GError) error = NULL;
btd_debug ("Reading stats for %s", btd_filesystem_get_mountpoint (bfs));
mail_address = btd_scheduler_get_config_value (self, bfs, "mail_address", NULL);
if (mail_address != NULL)
mail_address = g_strstrip (mail_address);
if (!btd_filesystem_read_error_stats (bfs, &issue_report, &error_count, &error)) {
/* only log the error for now */
g_printerr ("Failed to query btrfs issue statistics for '%s': %s\n",
btd_filesystem_get_mountpoint (bfs),
error->message);
return FALSE;
}
/* we have nothing more to do if no errors were found */
if (error_count == 0) {
btd_fs_record_set_value_int (record, "errors", "total", 0);
return TRUE;
}
prev_error_count = btd_fs_record_get_value_int (record, "errors", "total", 0);
btd_fs_record_set_value_int (record, "errors", "total", (gint64) error_count);
btd_debug ("Found %" G_GUINT64_FORMAT " errors for %s",
error_count,
btd_filesystem_get_mountpoint (bfs));
if (error_count > prev_error_count ||
(priv->reference_time -
btd_fs_record_get_value_int (record, "messages", "broadcast_sent", 0) >
SECONDS_IN_AN_HOUR * 6)) {
g_autofree gchar *bc_message = NULL;
/* broadcast message that there are errors to be fixed, do that roughly every 6h */
bc_message = g_strdup_printf ("⚠ Errors detected on filesystem at %s!\n"
"Please back up your files immediately. You can run "
"`btrfs device stats %s` for details.\n",
btd_filesystem_get_mountpoint (bfs),
btd_filesystem_get_mountpoint (bfs));
btd_broadcast_message (bc_message);
btd_fs_record_set_value_int (record, "messages", "broadcast_sent", priv->reference_time);
}
if (btd_is_empty (mail_address)) {
btd_warning ("Errors detected on filesystem '%s'", btd_filesystem_get_mountpoint (bfs));
return TRUE;
}
return btd_scheduler_send_error_mail (
self,
bfs, /* filesystem to act on */
record, /* state record for the FS */
error_count > prev_error_count, /* True if error amount is increasing */
mail_address, /* destination email address */
issue_report);
}
static gboolean
btd_scheduler_run_scrub (BtdScheduler *self, BtdFilesystem *bfs, BtdFsRecord *record)
{
g_autoptr(GError) error = NULL;
btd_debug ("Running scrub on filesystem %s", btd_filesystem_get_mountpoint (bfs));
if (!btd_filesystem_scrub (bfs, &error)) {
btd_warning ("Scrub on %s failed: %s", btd_filesystem_get_mountpoint (bfs), error->message);
return FALSE;
}
return TRUE;
}
static gboolean
btd_scheduler_run_balance (BtdScheduler *self, BtdFilesystem *bfs, BtdFsRecord *record)
{
g_autoptr(GError) error = NULL;
btd_debug ("Running balance on filesystem %s", btd_filesystem_get_mountpoint (bfs));
if (!btd_filesystem_balance (bfs, &error)) {
btd_warning ("Balance on %s failed: %s",
btd_filesystem_get_mountpoint (bfs),
error->message);
return FALSE;
}
return TRUE;
}
static gboolean
btd_scheduler_run_for_mount (BtdScheduler *self, BtdFilesystem *bfs)
{
BtdSchedulerPrivate *priv = GET_PRIVATE (self);
g_autoptr(BtdFsRecord) record = NULL;
g_autoptr(GError) error = NULL;
gint64 last_time;
time_t interval_time;
struct {
BtdBtrfsAction action;
BtdActionFunction func;
gboolean allow_on_battery;
} action_fn[] = {
{ BTD_BTRFS_ACTION_STATS, btd_scheduler_run_stats, TRUE },
{ BTD_BTRFS_ACTION_SCRUB, btd_scheduler_run_scrub, FALSE },
{ BTD_BTRFS_ACTION_BALANCE, btd_scheduler_run_balance, FALSE },
{ BTD_BTRFS_ACTION_UNKNOWN, NULL },
};
record = btd_fs_record_new (btd_filesystem_get_mountpoint (bfs));
if (!btd_fs_record_load (record, &error)) {
btd_warning ("Unable to load record for mount '%s': %s",
btd_filesystem_get_mountpoint (bfs),
error->message);
g_clear_error (&error);
}
/* run all actions */
for (guint i = 0; action_fn[i].func != NULL; i++) {
interval_time = (time_t) btd_scheduler_get_config_duration_for_action (self,
bfs,
action_fn[i].action);
if (interval_time == 0) {
btd_debug ("Skipping %s on %s, action is disabled.",
btd_btrfs_action_to_string (action_fn[i].action),
btd_filesystem_get_mountpoint (bfs));
continue;
}
last_time = btd_fs_record_get_last_action_time (record, action_fn[i].action);
if (priv->reference_time - last_time > interval_time) {
/* first check if this action is even allowed to be run if we are on batter power */
if (!action_fn[i].allow_on_battery && btd_machine_is_on_battery ()) {
btd_debug ("Skipping %s on %s, we are running on battery power.",
btd_btrfs_action_to_string (action_fn[i].action),
btd_filesystem_get_mountpoint (bfs));
continue;
}
/* run the action and record that we ran it, if it didn't fail to be launched */
if (action_fn[i].func (self, bfs, record))
btd_fs_record_set_last_action_time_now (record, action_fn[i].action);
}
}
/* save record & finish */
if (!btd_fs_record_save (record, &error)) {
btd_warning ("Unable to save state record for mount '%s': %s",
btd_filesystem_get_mountpoint (bfs),
error->message);
g_clear_error (&error);
}
return TRUE;
}
static gint
btd_filesystem_compare (gconstpointer fs_a, gconstpointer fs_b)
{
const gchar *mount_a = btd_filesystem_get_mountpoint (
BTD_FILESYSTEM (*(BtdFilesystem **) fs_a));
const gchar *mount_b = btd_filesystem_get_mountpoint (
BTD_FILESYSTEM (*(BtdFilesystem **) fs_b));
return g_strcmp0 (mount_a, mount_b);
}
/**
* btd_scheduler_run:
* @self: An instance of #BtdScheduler
* @error: A #GError
*
* Run any actions that are pending.
*
* Returns: %TRUE on success.
*/
gboolean
btd_scheduler_run (BtdScheduler *self, GError **error)
{
BtdSchedulerPrivate *priv = GET_PRIVATE (self);
g_autoptr(GHashTable) known_devices = g_hash_table_new (g_direct_hash, g_direct_equal);
/* load configuration in case we haven't loaded it yet */
if (!priv->loaded) {
if (!btd_scheduler_load (self, error))
return FALSE;
}
/* we need to be root for the next steps */
if (!btd_user_is_root ()) {
g_set_error_literal (error,
BTD_BTRFS_ERROR,
BTD_BTRFS_ERROR_FAILED,
"Need to be root to run this daemon.");
return FALSE;
}
/* check if there is anything for us to do */
if (priv->mountpoints->len == 0) {
g_debug ("No mounted Btrfs filesystems found.");
return TRUE;
}
/* sort mountpoints to get a predictable order */
g_ptr_array_sort (priv->mountpoints, btd_filesystem_compare);
/* run tasks */
for (guint i = 0; i < priv->mountpoints->len; i++) {
BtdFilesystem *bfs = g_ptr_array_index (priv->mountpoints, i);
dev_t devno = btd_filesystem_get_devno (bfs);
if (g_hash_table_contains (known_devices, GUINT_TO_POINTER (devno))) {
btd_debug ("Skipping %s, filesystem was already handled via a previous mount.",
btd_filesystem_get_mountpoint (bfs));
continue;
}
g_hash_table_add (known_devices, GUINT_TO_POINTER (devno));
btd_scheduler_run_for_mount (self, bfs);
}
return TRUE;
}
/**
* btd_scheduler_print_fs_status_entry:
* @self: An instance of #BtdScheduler
* @mountpoints: A #GPtrArray of #BtdFilesystem mountpoints which belong to the same filesystem
*
* Print filesystem scheduler status to stadout.
* Helper function for btd_scheduler_print_status
*
* Returns: %TRUE if no issues were found.
*/
static gboolean
btd_scheduler_print_fs_status_entry (BtdScheduler *self, GPtrArray *mountpoints)
{
BtdFilesystem *bfs;
gboolean errors_found = FALSE;
g_autoptr(GError) error = NULL;
if (mountpoints->len == 0)
return TRUE;
bfs = g_ptr_array_index (mountpoints, 0);
if (mountpoints->len > 1) {
g_autoptr(GString) mp_list = g_string_new (NULL);
for (guint i = 1; i < mountpoints->len; i++) {
BtdFilesystem *secondary = BTD_FILESYSTEM (g_ptr_array_index (mountpoints, i));
g_string_append (mp_list, btd_filesystem_get_mountpoint (secondary));
/* append comma if not the last element */
if (i < mountpoints->len - 1)
g_string_append_c (mp_list, ',');
}
g_print ("%c[%dm%s (%s) → %s%c[%dm\n",
0x1B,
1,
btd_filesystem_get_mountpoint (bfs),
mp_list->str,
btd_filesystem_get_device_name (bfs),
0x1B,
0);
} else {
g_print ("%c[%dm%s → %s%c[%dm\n",
0x1B,
1,
btd_filesystem_get_mountpoint (bfs),
btd_filesystem_get_device_name (bfs),
0x1B,
0);
}
for (guint j = BTD_BTRFS_ACTION_UNKNOWN + 1; j < BTD_BTRFS_ACTION_LAST; j++) {
g_autoptr(BtdFsRecord) record = NULL;
g_autofree gchar *last_action_time_str = NULL;
gint64 last_action_timestamp;
g_autofree gchar *interval_time = btd_humanize_time (
(gint64) btd_scheduler_get_config_duration_for_action (self, bfs, j));
g_print (" • %s\n"
" Runs every %s\n",
btd_btrfs_action_to_human_string (j),
interval_time);
record = btd_fs_record_new (btd_filesystem_get_mountpoint (bfs));
if (!btd_fs_record_load (record, &error)) {
btd_warning ("Unable to load record for mount '%s': %s",
btd_filesystem_get_mountpoint (bfs),
error->message);
g_clear_error (&error);
errors_found = TRUE;
continue;
}
last_action_timestamp = btd_fs_record_get_last_action_time (record, j);
if (last_action_timestamp == 0 || btd_fs_record_is_new (record)) {
last_action_time_str = g_strdup ("Never");
} else {
g_autoptr(GDateTime) last_action_dt = NULL;
last_action_dt = g_date_time_new_from_unix_local (last_action_timestamp);
last_action_time_str = g_date_time_format (last_action_dt, "%Y-%m-%d %H:%M:%S");
}
g_print (" Last run: %s\n", last_action_time_str);
if (j == BTD_BTRFS_ACTION_STATS) {
g_autofree gchar *mail_address = btd_scheduler_get_config_value (self,
bfs,
"mail_address",
NULL);
if (mail_address != NULL)
g_print (" Error mails to: %s\n", mail_address);
}
}
g_print ("\n");
return !errors_found;
}
/**
* btd_scheduler_print_status:
* @self: An instance of #BtdScheduler
*
* Print scheduler status data to stdout.
*
* Returns: %TRUE if all data was gathered and no issues were found.
*/
gboolean
btd_scheduler_print_status (BtdScheduler *self)
{
BtdSchedulerPrivate *priv = GET_PRIVATE (self);
gboolean errors_found = FALSE;
g_autoptr(GHashTable) devno_map = NULL;
GHashTableIter ht_iter;
gpointer ht_value;
if (priv->mountpoints->len == 0) {
g_print ("No mounted Btrfs filesystems found.\n");
return TRUE;
}
/* create a map of devno -> mountpoints */
devno_map = g_hash_table_new_full (g_direct_hash,
g_direct_equal,
NULL,
(GDestroyNotify) g_ptr_array_unref);
for (guint i = 0; i < priv->mountpoints->len; i++) {
BtdFilesystem *bfs = BTD_FILESYSTEM (g_ptr_array_index (priv->mountpoints, i));
GPtrArray *array = NULL;
dev_t devno = btd_filesystem_get_devno (bfs);
array = g_hash_table_lookup (devno_map, GUINT_TO_POINTER (devno));
if (!array) {
array = g_ptr_array_new_with_free_func (g_object_unref);
g_hash_table_insert (devno_map, GUINT_TO_POINTER (devno), array);
}
g_ptr_array_add (array, g_object_ref (bfs));
}
g_print ("Running on battery: %s\n", btd_machine_is_on_battery () ? "yes" : "no");
g_print ("Status:\n");
g_hash_table_iter_init (&ht_iter, devno_map);
while (g_hash_table_iter_next (&ht_iter, NULL, &ht_value)) {
GPtrArray *mps = (GPtrArray *) ht_value;
/* sort mountpoints to get a predictable order */
g_ptr_array_sort (mps, btd_filesystem_compare);
if (!btd_scheduler_print_fs_status_entry (self, mps))
errors_found = TRUE;
}
return !errors_found;
}
btrfsd-0.2.2/src/btd-scheduler.h000066400000000000000000000015131463624323600164750ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
#pragma once
#include
G_BEGIN_DECLS
#define BTD_TYPE_SCHEDULER (btd_scheduler_get_type ())
G_DECLARE_DERIVABLE_TYPE (BtdScheduler, btd_scheduler, BTD, SCHEDULER, GObject)
struct _BtdSchedulerClass {
GObjectClass parent_class;
/*< private >*/
void (*_as_reserved1) (void);
void (*_as_reserved2) (void);
void (*_as_reserved3) (void);
void (*_as_reserved4) (void);
void (*_as_reserved5) (void);
void (*_as_reserved6) (void);
};
BtdScheduler *btd_scheduler_new (void);
gboolean btd_scheduler_load (BtdScheduler *self, GError **error);
gboolean btd_scheduler_run (BtdScheduler *self, GError **error);
gboolean btd_scheduler_print_status (BtdScheduler *self);
G_END_DECLS
btrfsd-0.2.2/src/btd-utils.c000066400000000000000000000277451463624323600156710ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
/**
* SECTION:btd-utils
* @short_description: Various utility functions.
*
* Utility functions for Btrfsd.
*/
#include "config.h"
#include "btd-utils.h"
#include "btd-resources.h"
/**
* btd_is_empty:
* @str: The string to test.
*
* Test if a C string is %NULL or empty (contains only terminating null character).
*
* Returns: %TRUE if string was empty.
*/
gboolean
btd_is_empty (const gchar *str)
{
if ((str == NULL) || (str[0] == '\0'))
return TRUE;
return FALSE;
}
/**
* btd_strstripnl:
* @string: a string to remove surrounding whitespaces and newlines
*
* Removes newlines and whitespaces surrounding a string.
*
* This function doesn't allocate or reallocate any memory;
* it modifies @string in place.
*
* As opposed to g_strstrip() this function also removes newlines
* from the start and end of strings.
*
* Returns: @string
*/
gchar *
btd_strstripnl (gchar *string)
{
gsize len;
guchar *start;
if (string == NULL)
return NULL;
/* remove trailing whitespaces/newlines */
len = strlen (string);
while (len--) {
const guchar c = string[len];
if (g_ascii_isspace (c) || (c == '\n'))
string[len] = '\0';
else
break;
}
/* remove leading whitespaces/newlines */
for (start = (guchar *) string; *start && (g_ascii_isspace (*start) || ((*start) == '\n'));
start++)
;
memmove (string, start, strlen ((gchar *) start) + 1);
return string;
}
/**
* btd_get_state_dir:
*
* Returns: (transfer full): the state dir for Btrfsd.
*/
gchar *
btd_get_state_dir (void)
{
gchar *path = g_build_filename (LOCALSTATEDIR, "lib", "btrfsd", NULL);
g_mkdir_with_parents (path, 0755);
return path;
}
/**
* btd_get_resource_data:
* @resource_path: Path to the resource.
*
* Load data from an internal resource.
*
* returns: The resource bytes, or %NULL on error.
**/
GBytes *
btd_get_resource_data (const gchar *resource_path)
{
return g_resource_lookup_data (btd_get_resource (),
resource_path,
G_RESOURCE_LOOKUP_FLAGS_NONE,
NULL);
}
/**
* btd_user_is_root:
*
* Check if the current user has superuser permissions.
*/
gboolean
btd_user_is_root (void)
{
uid_t vuid;
vuid = getuid ();
return (vuid == ((uid_t) 0));
}
/**
* btd_parse_duration_string:
* @str: The string to parse.
*
* Returns: The duration in seconds, or 0 on error or if "never".
*/
gulong
btd_parse_duration_string (const gchar *str)
{
gchar suffix;
gint64 value;
guint str_len;
gulong multiplier = 1;
if (btd_is_empty (str))
return 0;
str_len = strlen (str);
if (str_len < 1)
return 0;
if (btd_str_equal0 (str, "never"))
return 0;
suffix = str[str_len - 1];
value = g_ascii_strtoll (str, NULL, 10);
if (value <= 0)
return 0;
switch (suffix) {
case 'h':
multiplier = SECONDS_IN_AN_HOUR;
break;
case 'd':
multiplier = SECONDS_IN_A_DAY;
break;
case 'w':
multiplier = SECONDS_IN_A_WEEK;
break;
case 'M':
multiplier = SECONDS_IN_A_MONTH;
break;
default:
/* the last character not being a digit is an error */
if (!g_ascii_isdigit (suffix))
return 0;
/* if no suffix, default to hours */
multiplier = SECONDS_IN_AN_HOUR;
break;
}
return value * multiplier;
}
/**
* btd_render_template:
* @template: the template to render
*
* Formats a template string to replace all placeholder key with the
* given values.
*
* Returns: (transfer full): Template text with variables replaced.
**/
gchar *
btd_render_template (const gchar *template, const gchar *key1, ...)
{
va_list args;
const gchar *cur_key;
const gchar *cur_val;
g_auto(GStrv) parts = NULL;
g_autoptr(GPtrArray) vars = g_ptr_array_new ();
if (template == NULL)
return NULL;
if (key1 == NULL)
return g_strdup (template);
/* prepare variable list */
va_start (args, key1);
cur_key = key1;
while (cur_key != NULL) {
cur_val = va_arg (args, gchar *);
if (cur_val == NULL)
cur_val = "";
g_ptr_array_add (vars, (gchar *) cur_key);
g_ptr_array_add (vars, (gchar *) cur_val);
cur_key = va_arg (args, gchar *);
}
va_end (args);
/* sanity check */
g_return_val_if_fail (vars->len % 2 == 0, NULL);
/* replace variables */
parts = g_strsplit (template, "{{", -1);
for (guint i = 0; parts[i] != NULL; i++) {
gboolean replaced = FALSE;
for (guint j = 0; j < vars->len; j += 2) {
g_autofree gchar *tmp2 = NULL;
g_autofree gchar *tmp = g_strconcat (g_ptr_array_index (vars, j), "}}", NULL);
if (!g_str_has_prefix (parts[i], tmp))
continue;
/* replace string */
tmp2 = parts[i];
parts[i] = parts[i] + strlen (tmp);
parts[i] = g_strconcat (g_ptr_array_index (vars, j + 1), parts[i], NULL);
replaced = TRUE;
break;
}
if (!replaced && (i != 0)) {
g_autofree gchar *tmp = NULL;
/* keep the placeholder in place */
tmp = parts[i];
parts[i] = g_strconcat ("{{", parts[i], NULL);
}
}
return g_strjoinv ("", parts);
}
/**
* btd_path_to_filename:
* @path: The path to convert.
*
* Returns: (transfer full): A filename representing the path.
*/
gchar *
btd_path_to_filename (const gchar *path)
{
GString *str;
guint short_hash;
g_autofree gchar *canonical_path = NULL;
canonical_path = g_canonicalize_filename (path, "/");
str = g_string_new (canonical_path);
short_hash = g_str_hash (canonical_path);
if (g_str_has_prefix (str->str, "/"))
g_string_erase (str, 0, 1);
if (str->len == 0) {
/* we hit the root path / */
g_string_free (str, TRUE);
return g_strdup ("-");
}
if (g_str_has_prefix (str->str, "."))
g_string_prepend_c (str, '_');
g_string_replace (str, "/", "-", 0);
g_string_replace (str, "\\", "-", 0);
/* append the hash value to the filename, for some extra uniqueness for corner cases */
g_string_append_printf (str, "_%u", short_hash);
return g_string_free (str, FALSE);
}
/**
* btd_humanize_time:
* @seconds: The time in seconds.
*
* Convert a time in seconds into a human-readable string.
*
* Returns: (transfer full): The human-readable string containing the time.
*/
gchar *
btd_humanize_time (gint64 seconds)
{
if (seconds == 0)
return g_strdup ("Never");
if (seconds < 60)
return g_strdup_printf ("%" G_GINT64_FORMAT " %s",
seconds,
seconds == 1 ? "second" : "seconds");
if (seconds < SECONDS_IN_AN_HOUR) {
if (seconds % 60 == 0)
return g_strdup_printf ("%" G_GINT64_FORMAT " %s",
seconds / 60,
(seconds / 60) == 1 ? "minute" : "minutes");
else
return g_strdup_printf ("%" G_GINT64_FORMAT " %s %" G_GINT64_FORMAT " %s",
seconds / 60,
(seconds / 60) == 1 ? "minute" : "minutes",
seconds % 60,
(seconds % 60) == 1 ? "second" : "seconds");
}
if (seconds < SECONDS_IN_A_DAY) {
if ((seconds % SECONDS_IN_AN_HOUR) / 60 == 0)
return g_strdup_printf ("%" G_GINT64_FORMAT " %s",
seconds / SECONDS_IN_AN_HOUR,
(seconds / SECONDS_IN_AN_HOUR) == 1 ? "hour" : "hours");
else
return g_strdup_printf ("%" G_GINT64_FORMAT " %s %" G_GINT64_FORMAT " %s",
seconds / SECONDS_IN_AN_HOUR,
(seconds / SECONDS_IN_AN_HOUR) == 1 ? "hour" : "hours",
(seconds % SECONDS_IN_AN_HOUR) / 60,
((seconds % SECONDS_IN_AN_HOUR) / 60) == 1 ? "minute"
: "minutes");
}
if (seconds < SECONDS_IN_A_MONTH) {
if ((seconds % SECONDS_IN_A_DAY) / SECONDS_IN_AN_HOUR == 0)
return g_strdup_printf ("%" G_GINT64_FORMAT " %s",
seconds / SECONDS_IN_A_DAY,
(seconds / SECONDS_IN_A_DAY) == 1 ? "day" : "days");
else
return g_strdup_printf (
"%" G_GINT64_FORMAT " %s %" G_GINT64_FORMAT " %s",
seconds / SECONDS_IN_A_DAY,
(seconds / SECONDS_IN_A_DAY) == 1 ? "day" : "days",
(seconds % SECONDS_IN_A_DAY) / SECONDS_IN_AN_HOUR,
((seconds % SECONDS_IN_A_DAY) / SECONDS_IN_AN_HOUR) == 1 ? "hour" : "hours");
}
if ((seconds % SECONDS_IN_A_MONTH) / SECONDS_IN_A_DAY == 0)
return g_strdup_printf ("%" G_GINT64_FORMAT " %s",
seconds / SECONDS_IN_A_MONTH,
(seconds / SECONDS_IN_A_MONTH) == 1 ? "month" : "months");
else
return g_strdup_printf ("%" G_GINT64_FORMAT " %s %" G_GINT64_FORMAT " %s",
seconds / SECONDS_IN_A_MONTH,
(seconds / SECONDS_IN_A_MONTH) == 1 ? "month" : "months",
(seconds % SECONDS_IN_A_MONTH) / SECONDS_IN_A_DAY,
((seconds % SECONDS_IN_A_MONTH) / SECONDS_IN_A_DAY) == 1 ? "day"
: "days");
}
/**
* btd_machine_is_on_battery:
*
* Check if the system is currently running on battery power.
* We will ask UPower first, and fall back to reading data from /sys
* if that fails.
*
* Returns: %TRUE if system is on battery.
*/
gboolean
btd_machine_is_on_battery ()
{
g_autoptr(GDBusConnection) connection = NULL;
g_autoptr(GVariant) result = NULL;
g_autoptr(GError) dbus_error = NULL;
guint32 state;
connection = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &dbus_error);
if (connection != NULL) {
result = g_dbus_connection_call_sync (
connection,
"org.freedesktop.UPower",
"/org/freedesktop/UPower/devices/battery_BAT0",
"org.freedesktop.DBus.Properties",
"Get",
g_variant_new ("(ss)", "org.freedesktop.UPower.Device", "State"),
G_VARIANT_TYPE ("(v)"),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&dbus_error);
}
if (result == NULL) {
g_autofree gchar *contents = NULL;
g_autoptr(GError) file_error = NULL;
/* we failed to red battery information from UPower - let's try using /sys directly */
if (!g_file_get_contents ("/sys/class/power_supply/BAT0/status",
&contents,
NULL,
&file_error)) {
g_debug ("Unable to read battery status (UPower failed: %s, Reading BAT0 failed: %s). "
"The system may not have a battery.",
dbus_error->message,
file_error->message);
/* this is not an error, the machine may not have a battery */
return FALSE;
}
if (contents != NULL)
contents = g_strstrip (contents);
/* we're on battery if we're discharging */
return g_str_has_prefix (contents, "Discharging");
}
/* extract battery state from D-Bus result */
g_variant_get (result, "(v)", &result);
state = g_variant_get_uint32 (result);
/* 2 is the value for "discharging" in upower */
return state == 2;
}
btrfsd-0.2.2/src/btd-utils.h000066400000000000000000000022361463624323600156620ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
#pragma once
#include
G_BEGIN_DECLS
#define SECONDS_IN_AN_HOUR (60 * 60)
#define SECONDS_IN_A_DAY (24 * SECONDS_IN_AN_HOUR)
#define SECONDS_IN_A_WEEK (7 * SECONDS_IN_A_DAY)
/* we assume an average month has approximately 30.44 days here */
#define SECONDS_IN_A_MONTH ((int) (30.44 * SECONDS_IN_A_DAY))
/**
* btd_str_equal0:
* Returns TRUE if strings are equal, ignoring NULL strings.
* This is a convenience wrapper around g_strcmp0
*/
#define btd_str_equal0(str1, str2) (g_strcmp0 ((gchar *) str1, (gchar *) str2) == 0)
gboolean btd_is_empty (const gchar *str);
gchar *btd_strstripnl (gchar *string);
gchar *btd_get_state_dir (void);
GBytes *btd_get_resource_data (const gchar *resource_path);
gboolean btd_user_is_root (void);
gulong btd_parse_duration_string (const gchar *str);
gchar *btd_render_template (const gchar *template, const gchar *key1, ...) G_GNUC_NULL_TERMINATED;
gchar *btd_path_to_filename (const gchar *path);
gchar *btd_humanize_time (gint64 seconds);
gboolean btd_machine_is_on_battery (void);
G_END_DECLS
btrfsd-0.2.2/src/btrfsd.c000066400000000000000000000047051463624323600152350ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
#include "config.h"
#include
#include
#include
#include "btd-scheduler.h"
#include "btd-logging.h"
int
main (int argc, char **argv)
{
g_autoptr(GOptionContext) option_context = NULL;
g_autoptr(GError) error = NULL;
g_autoptr(BtdScheduler) scheduler = NULL;
gboolean ret;
gboolean verbose = FALSE;
gboolean show_version = FALSE;
gboolean show_status = FALSE;
const GOptionEntry options[] = {
{ "verbose",
'v',
0,
G_OPTION_ARG_NONE,
&verbose,
"Show extra debugging information",
NULL },
{ "version", '\0', 0, G_OPTION_ARG_NONE, &show_version, "Show the program version.", NULL },
{ "status",
'\0',
0,
G_OPTION_ARG_NONE,
&show_status,
"Display some short status information.",
NULL },
{ NULL }
};
setlocale (LC_ALL, "");
bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
textdomain (GETTEXT_PACKAGE);
option_context = g_option_context_new ("Btrfs maintenance helper.");
g_option_context_add_main_entries (option_context, options, NULL);
ret = g_option_context_parse (option_context, &argc, &argv, &error);
if (!ret) {
g_print ("%s: %s\n", "Failed to parse arguments", error->message);
return EXIT_FAILURE;
}
/* set up logging (to console or syslog) */
btd_logging_setup (verbose);
if (show_version) {
g_print ("Btrfsd version: %s\n", PACKAGE_VERSION);
return EXIT_SUCCESS;
}
scheduler = btd_scheduler_new ();
if (!btd_scheduler_load (scheduler, &error)) {
g_printerr ("Failed to initialize: %s\n", error->message);
return EXIT_FAILURE;
}
if (show_status) {
/* display status information */
if (btd_scheduler_print_status (scheduler))
return EXIT_SUCCESS;
return EXIT_FAILURE;
}
/* run all scheduled actions */
if (!btd_scheduler_run (scheduler, &error)) {
if (btd_is_tty ())
g_printerr ("Failed to run: %s\n", error->message);
else
btd_error ("Btrfsd failed to run: %s", error->message);
btd_logging_finalize ();
return EXIT_FAILURE;
}
btd_logging_finalize ();
return EXIT_SUCCESS;
}
btrfsd-0.2.2/src/btrfsd.gresource.xml000066400000000000000000000002151463624323600176000ustar00rootroot00000000000000
error-mail.tmpl
btrfsd-0.2.2/src/meson.build000066400000000000000000000016121463624323600157410ustar00rootroot00000000000000
btrfsd_src = [
'btd-filesystem.h',
'btd-filesystem.c',
'btd-fs-record.h',
'btd-fs-record.c',
'btd-mailer.h',
'btd-mailer.c',
'btd-scheduler.h',
'btd-scheduler.c',
'btd-logging.h',
'btd-logging.c',
'btd-utils.h',
'btd-utils.c',
]
btrfsd_res = glib.compile_resources (
'btd-resources', 'btrfsd.gresource.xml',
c_name: 'btd',
source_dir: ['../data']
)
btrfsd_deps = [
glib_dep,
gobject_dep,
gio_dep,
json_glib_dep,
mount_dep,
libsystemd_dep,
]
btrfsd_lib = static_library(
'btrfsd',
sources: [btrfsd_src, btrfsd_res],
dependencies: btrfsd_deps,
include_directories: [root_inc_dir],
)
btrfsd_exe = executable(
'btrfsd',
['btrfsd.c'],
dependencies: btrfsd_deps,
link_with: btrfsd_lib,
include_directories: [root_inc_dir],
install_dir: get_option('libexecdir'),
install: true,
)
btrfsd-0.2.2/tests/000077500000000000000000000000001463624323600141525ustar00rootroot00000000000000btrfsd-0.2.2/tests/ci/000077500000000000000000000000001463624323600145455ustar00rootroot00000000000000btrfsd-0.2.2/tests/ci/Dockerfile-debian-stable000066400000000000000000000004241463624323600212270ustar00rootroot00000000000000#
# Docker file for Btrfsd CI tests on Debian Stable
#
FROM debian:stable
# prepare
RUN mkdir -p /build/ci/
# install build dependencies
COPY install-deps-deb.sh /build/ci/
RUN chmod +x /build/ci/install-deps-deb.sh && /build/ci/install-deps-deb.sh
# finish
WORKDIR /build
btrfsd-0.2.2/tests/ci/Dockerfile-debian-testing000066400000000000000000000004261463624323600214340ustar00rootroot00000000000000#
# Docker file for Btrfsd CI tests on Debian Testing
#
FROM debian:testing
# prepare
RUN mkdir -p /build/ci/
# install build dependencies
COPY install-deps-deb.sh /build/ci/
RUN chmod +x /build/ci/install-deps-deb.sh && /build/ci/install-deps-deb.sh
# finish
WORKDIR /build
btrfsd-0.2.2/tests/ci/Dockerfile-fedora-latest000066400000000000000000000005001463624323600212620ustar00rootroot00000000000000#
# Docker file for Btrfsd CI tests on Fedora targeting latest stable
#
FROM registry.fedoraproject.org/fedora:latest
# prepare
RUN mkdir -p /build/ci/
# install build dependencies
COPY install-deps-rpm.sh /build/ci/
RUN chmod +x /build/ci/install-deps-rpm.sh && /build/ci/install-deps-rpm.sh
# finish
WORKDIR /build
btrfsd-0.2.2/tests/ci/install-deps-deb.sh000077500000000000000000000011661463624323600202370ustar00rootroot00000000000000#!/bin/bash
#
# Install Btrfsd build dependencies
#
set -e
set -x
export DEBIAN_FRONTEND=noninteractive
# update caches
apt-get update -qq
# install build essentials
apt-get install -yq \
eatmydata \
build-essential \
gdb \
gcc \
g++
# install build dependencies
eatmydata apt-get install -yq --no-install-recommends \
meson \
ninja-build \
git \
gettext \
itstool \
systemd \
libglib2.0-dev \
libsystemd-dev \
gtk-doc-tools \
libmount-dev \
libjson-glib-dev
if apt-cache show systemd-dev > /dev/null 2>&1; then
eatmydata apt-get install -yq systemd-dev
fi
btrfsd-0.2.2/tests/ci/install-deps-rpm.sh000077500000000000000000000006621463624323600203030ustar00rootroot00000000000000#!/bin/sh
#
# Install Btrfsd build dependencies
#
set -e
set -x
# update caches
dnf makecache
# install build dependencies
dnf --assumeyes --quiet --setopt=install_weak_deps=False install \
gcc \
gcc-c++ \
gdb \
git \
meson \
gettext \
gtk-doc \
libasan \
libubsan \
systemd \
'pkgconfig(gio-2.0)' \
'pkgconfig(libsystemd)' \
'pkgconfig(mount)' \
'pkgconfig(json-glib-1.0)' \
btrfsd-0.2.2/tests/ci/run-build.sh000077500000000000000000000023301463624323600170030ustar00rootroot00000000000000#!/bin/sh
set -e
# This script is supposed to run inside the Btrfsd Docker container
# on the CI system.
#
# Read options for the current test build
#
. /etc/os-release
maintainer_mode=true
static_analysis=false
build_type=debugoptimized
build_dir="cibuild"
sanitize_flag=""
if [ "$ID" = "ubuntu" ] && [ "$VERSION_CODENAME" = "jammy" ]; then
# we don't make warnings fatal on Ubuntu 22.04
maintainer_mode=false
fi;
if [ "$1" = "sanitize" ]; then
build_dir="cibuild-san"
sanitize_flags="-Db_sanitize=address,undefined"
build_type=debug
echo "Running build with sanitizers 'address,undefined' enabled."
# Slow unwind, but we get better backtraces
export ASAN_OPTIONS=fast_unwind_on_malloc=0
echo "Running static analysis during build."
static_analysis=true
fi;
if [ "$1" = "codeql" ]; then
build_type=debug
fi;
echo "C compiler: $CC"
echo "C++ compiler: $CXX"
set -x
$CC --version
#
# Configure Btrfsd build
#
mkdir $build_dir && cd $build_dir
meson --buildtype=$build_type \
$sanitize_flags \
-Dmaintainer=$maintainer_mode \
-Dstatic-analysis=$static_analysis \
..
#
# Build & Install
#
ninja
DESTDIR=/tmp/install_root/ ninja install
rm -r /tmp/install_root/
btrfsd-0.2.2/tests/ci/run-tests.sh000077500000000000000000000013011463624323600170430ustar00rootroot00000000000000#!/bin/sh
set -e
# This script is supposed to run inside the Btrfsd Docker container
# on the CI system.
#
# Read options for the current test run
#
build_dir="cibuild"
if [ "$1" = "sanitize" ]; then
build_dir="cibuild-san"
echo "Testing sanitized build."
# Slow unwind, but we get better backtraces
export ASAN_OPTIONS=fast_unwind_on_malloc=0
# no GLib memory pools
export G_SLICE=always-malloc
# pedantic malloc
export MALLOC_CHECK_=3
fi;
if [ ! -d "$build_dir" ]; then
# Take action if $DIR exists. #
echo "Build directory '$build_dir' did not exist. Can not continue."
exit 1
fi
set -x
#
# Run tests
#
cd $build_dir
meson test --print-errorlogs --verbose
btrfsd-0.2.2/tests/meson.build000066400000000000000000000004161463624323600163150ustar00rootroot00000000000000# Meson definition for Btrfsd Tests
test_btd_exe = executable ('as-test_misc',
['test-btd.c'],
dependencies: btrfsd_deps,
link_with: btrfsd_lib,
include_directories: [root_inc_dir, include_directories ('../src')]
)
test ('test_btd',
test_btd_exe,
)
btrfsd-0.2.2/tests/test-btd.c000066400000000000000000000117411463624323600160500ustar00rootroot00000000000000/*
* Copyright (C) Matthias Klumpp
*
* SPDX-License-Identifier: LGPL-2.1+
*/
#include
#include "btd-utils.h"
/**
* test_duration_parser:
*/
static void
test_duration_parser (void)
{
g_assert_cmpint (btd_parse_duration_string ("1h"), ==, 3600);
g_assert_cmpint (btd_parse_duration_string ("2h"), ==, 3600 * 2);
g_assert_cmpint (btd_parse_duration_string ("3"), ==, 3600 * 3);
g_assert_cmpint (btd_parse_duration_string ("1d"), ==, 86400);
g_assert_cmpint (btd_parse_duration_string ("4d"), ==, 86400 * 4);
g_assert_cmpint (btd_parse_duration_string ("1w"), ==, 604800);
g_assert_cmpint (btd_parse_duration_string ("4w"), ==, 604800 * 4);
g_assert_cmpint (btd_parse_duration_string ("1M"), ==, 2630016);
g_assert_cmpint (btd_parse_duration_string ("3M"), ==, 2630016 * 3);
g_assert_cmpint (btd_parse_duration_string ("notvalid"), ==, 0);
g_assert_cmpint (btd_parse_duration_string ("2u"), ==, 0);
}
/**
* test_render_template:
*/
static void
test_render_template (void)
{
const gchar
*template1 = "This is a {{key1}} template\n"
"All strings need to be {{action}} correctly for the {{test_name}} to pass.";
const gchar *
result1 = "This is a good template\n"
"All strings need to be rendered correctly for the render_template test to pass.";
g_autofree gchar *tmp = NULL;
tmp = btd_render_template (template1,
"key1",
"good",
"action",
"rendered",
"test_name",
"render_template test",
NULL);
g_assert_cmpstr (tmp, ==, result1);
}
/**
* test_path_escape:
*/
static void
test_path_escape (void)
{
gchar *tmp;
tmp = btd_path_to_filename ("/");
g_assert_cmpstr (tmp, ==, "-");
g_free (tmp);
tmp = btd_path_to_filename ("");
g_assert_cmpstr (tmp, ==, "-");
g_free (tmp);
tmp = btd_path_to_filename ("/this/is/a path with/spaces/.txt");
g_assert_cmpstr (tmp, ==, "this-is-a path with-spaces-.txt_4128569403");
g_free (tmp);
tmp = btd_path_to_filename ("..");
g_assert_cmpstr (tmp, ==, "-");
g_free (tmp);
tmp = btd_path_to_filename ("/../../.");
g_assert_cmpstr (tmp, ==, "-");
g_free (tmp);
tmp = btd_path_to_filename ("/a/cräzü/path----/x/../txt");
g_assert_cmpstr (tmp, ==, "a-cräzü-path-----txt_3474729208");
g_free (tmp);
tmp = btd_path_to_filename ("/a-b/c");
g_assert_cmpstr (tmp, ==, "a-b-c_2088179606");
g_free (tmp);
tmp = btd_path_to_filename ("/a/b/c");
g_assert_cmpstr (tmp, ==, "a-b-c_2088251480");
g_free (tmp);
}
/**
* test_humanize_time:
*/
static void
test_humanize_time (void)
{
g_autofree gchar *result = NULL;
result = btd_humanize_time (0);
g_assert_cmpstr (result, ==, "Never");
g_clear_pointer (&result, g_free);
result = btd_humanize_time (5);
g_assert_cmpstr (result, ==, "5 seconds");
g_clear_pointer (&result, g_free);
result = btd_humanize_time (1);
g_assert_cmpstr (result, ==, "1 second");
g_clear_pointer (&result, g_free);
result = btd_humanize_time (70);
g_assert_cmpstr (result, ==, "1 minute 10 seconds");
g_clear_pointer (&result, g_free);
result = btd_humanize_time (120);
g_assert_cmpstr (result, ==, "2 minutes");
g_clear_pointer (&result, g_free);
result = btd_humanize_time (3600);
g_assert_cmpstr (result, ==, "1 hour");
g_clear_pointer (&result, g_free);
result = btd_humanize_time (3660);
g_assert_cmpstr (result, ==, "1 hour 1 minute");
g_clear_pointer (&result, g_free);
result = btd_humanize_time (SECONDS_IN_A_DAY);
g_assert_cmpstr (result, ==, "1 day");
g_clear_pointer (&result, g_free);
result = btd_humanize_time (SECONDS_IN_A_DAY + SECONDS_IN_AN_HOUR);
g_assert_cmpstr (result, ==, "1 day 1 hour");
g_clear_pointer (&result, g_free);
result = btd_humanize_time (SECONDS_IN_A_MONTH);
g_assert_cmpstr (result, ==, "1 month");
g_clear_pointer (&result, g_free);
result = btd_humanize_time (SECONDS_IN_A_MONTH + SECONDS_IN_A_DAY);
g_assert_cmpstr (result, ==, "1 month 1 day");
g_clear_pointer (&result, g_free);
}
int
main (int argc, char **argv)
{
int ret;
if (argc == 0) {
g_error ("No test directory specified!");
return 1;
}
g_setenv ("G_MESSAGES_DEBUG", "all", TRUE);
g_test_init (&argc, &argv, NULL);
/* only critical and error are fatal */
g_log_set_fatal_mask (NULL, G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL);
g_test_add_func ("/Btrfsd/Misc/DurationParser", test_duration_parser);
g_test_add_func ("/Btrfsd/Misc/RenderTemplate", test_render_template);
g_test_add_func ("/Btrfsd/Misc/PathEscape", test_path_escape);
g_test_add_func ("/Btrfsd/Misc/HumanizeTime", test_humanize_time);
ret = g_test_run ();
return ret;
}