Repository: egara/buttermanager
Branch: master
Commit: 5d83cce810a4
Files: 42
Total size: 325.7 KB
Directory structure:
gitextract_bque78re/
├── .gitignore
├── LICENSE
├── README.md
├── aur/
│ ├── PKGBUILD
│ └── README.txt
├── buttermanager/
│ ├── bm_main.py
│ ├── buttermanager/
│ │ ├── __init__.py
│ │ ├── buttermanager.py
│ │ ├── exception/
│ │ │ ├── __init__.py
│ │ │ └── exception.py
│ │ ├── filesystem/
│ │ │ ├── __init__.py
│ │ │ ├── filesystem.py
│ │ │ └── snapshot.py
│ │ ├── manager/
│ │ │ ├── __init__.py
│ │ │ └── upgrader.py
│ │ ├── ui/
│ │ │ ├── ConsolidateSnapshotWindow.ui
│ │ │ ├── GeneralInfoWindow.ui
│ │ │ ├── InfoWindow.ui
│ │ │ ├── LogViewWindow.ui
│ │ │ ├── MainWindow.ui
│ │ │ ├── PasswordWindow.ui
│ │ │ ├── ProblemsFoundWindow.ui
│ │ │ ├── SnapshotWindow.ui
│ │ │ ├── SubvolumeWindow.ui
│ │ │ └── UpdatesWindow.ui
│ │ ├── util/
│ │ │ ├── __init__.py
│ │ │ ├── settings.py
│ │ │ └── utils.py
│ │ └── window/
│ │ ├── __init__.py
│ │ └── windows.py
│ └── main.py
├── doc/
│ └── README.md
├── install/
│ ├── native_install.sh
│ ├── uninstall.sh
│ └── venv_install.sh
├── packaging/
│ ├── buttermanager.desktop
│ └── buttermanager_venv.desktop
├── requirements.txt
├── rpm/
│ ├── README.txt
│ └── buttermanager.spec
├── setup.py
└── version.txt
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
#PyCharm configuration
.idea/
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: README.md
================================================
# ButterManager
## Summary
ButterManager is a BTRFS tool for managing snapshots, balancing filesystems and upgrading the system safetly.
## Version
2.5.2
## Wiki
You can find documentation and more info in the [wiki of the project](https://github.com/egara/buttermanager/wiki)
## Caveats
- For using ButterManager, it is important to have a **good BTRFS structure in your filesystem**. If you want some tips and more information, you can [read
this](https://github.com/egara/arch-btrfs-installation).
- ButterManager works with **Debian**, **Ubuntu / derivatives (Linux Mint, KDE Neon, ElementaryOS, Zorin, Deepin...)**, **OpenSUSE / SUSE**, **RHEL / Fedora** and **Arch Linux** so far.
## Main Functionalities
### Managing snapshots
You will be able to define all the subvolumes you want to create snapshots and the path for their storage. Then, using ButterManager you will create and delete snapshots of those subvolumes at your will.
### Integration with GRUB
ButterManager is integrated with [grub-btrfs](https://github.com/Antynea/grub-btrfs) and you will be able to boot your system from any snapshot directly from the GRUB menu.
### Balancing BTRFS filesystems
As new snapshots are created in the system, the free space of the filesystem decreases and it is necessary to perform a system balancing regularly. With ButterManager you can perform these balances at any time and visualize the real space that is occupied.
### Upgrading the system
You will be able to upgrade your system and create new snapshots automatically when this operation is performed. Doing so, if something goes wrong, you will have a snapshot before the upgrade you can use to go back. You will be able to set the maximum number of snapshots in your system and ButterManager will maintain this number with every upgrade.
### Saving the logs
Everytime your system is upgraded using ButterManager, you could save the log indepently. This way, you would be able to see the packages that have been updated in every snapshot if you wish.
## Installation
You can install ButterManager in different ways.
### From the source code
In order to install ButterManager manually, you have to install these packages (all the packages described below are for **Arch Linux**. Please, take into account that maybe the name is different in your distribution and you have to install them for python3 version):
- Python 3
- **python-setuptool** (f.i. the name of the package in Ubuntu is **python3-setuptools**).
- **python-virtualenv** (f.i. the name of the package in Ubuntu is **python3-venv**). This package will only be needed if you use **venv_install.sh** script (see below).
- **grub-btrfs**. Please, go to its GitHub repository [https://github.com/Antynea/grub-btrfs](https://github.com/Antynea/grub-btrfs) and follow the instructions to install it if the package is not in the official repository of your distribution.
- **libxinerama**: This depency has been reported by some users (thanks Adam!) who install ButterManager on Ubuntu 20.04 (proper) (the name of the package in Ubuntu is **libxcb-xinerama0**)
- **tk** (f.i. the name of the package in Ubuntu is **python3-tk**)
Once you meet all the requirements, follow these steps:
1. Clone the repository (install **git** if it is needed first)
```
git clone https://github.com/egara/buttermanager.git
```
1. Install ButterManager using one of the following installation scripts:
1. **Native Installation**: This is the preferred method. It is slimmer because no virtual environment is created in order to execute ButterManager. This installation method will install the dependencies needed in your system natively and create an executable script for running the application. You will be able to execute ButterManager from the terminal typing **buttermanager** or directly via a shortcut created. In order to install ButterManager just open a terminal and execute:
```
cd buttermanager
cd install
./native_install.sh
```
1. **Venv Installation**: If the first method doesn't run ButterManager properly, please try this second one. The installation process will create a virtual environment with all the dependencies needed and a desktop launcher to run ButterManager directly. In order to install ButterManager just open a terminal and type:
```
cd buttermanager
cd install
./venv_install.sh
```
1. If you want to uninstall ButterManager:
```
cd buttermanager
cd install
./uninstall.sh
```
### From AUR
If you are an Arch Linux user or your distribution is a derivative (Manjaro, EndevourOS...), ButterManager is in AUR. Depending on your package manager for AUR, type:
yaourt -S buttermanager
Or
trizen -S buttermanager
Or
yay -S buttermanager
Those are only examples. Use the package manager you have installed for AUR. Once ButterManager is installed, you will be able to run it using the icon created in the main menu.
### From Nix
ButterManager is packaged in Nix [and included in the official repo](https://search.nixos.org/packages?channel=24.05&from=0&size=50&sort=relevance&type=packages&query=buttermanager)
### From RPM
ButterManager is packaged in Fedora but it is outdated. [This is the official package](https://packages.fedoraproject.org/pkgs/buttermanager/buttermanager/)
## Changelog
### Version 2.5.2
- Issue #56. Cancel button has been re-implemented within the consolidation window and now it closes this window when it is clicked.
- All ButterManager windows have been renamed to ButterManager. New labels in some windows have been added.
### Version 2.5.1
- Issue #52. A bug that prevented ButterManager to start normally (reported by Fedora users) has been fixed.
- ButterManager main window title is now displayed.
- Some missing buttons and different elements from tabs have been included within enable and disable buttons methods.
### Version 2.5.0
- Flatpak support implemented.
- Windows layout reimplemented. All windows are resizeable now.
- Font size customization implemented.
- Issue #29 fixed. Now, mobile users should be able to rescale the application to fit their displays.
### Version 2.4.3
- Issue #31 fixed. Preventing errors when calculating diffs against root directly.
- Issue #33 fixed. Refreshing filesystem statistics when user changes filesystem within combobox.
- Issue #45 fixed. Changing yaml.load method to yaml.safe_load because pyyaml library requires it since version 5.4.
### Version 2.4.2
- Minor changes in order to improve the package and preparing all to publish ButterManager in Fedora. Thanks Michel Alexandre Salim!
### Version 2.4.1
- Issue #32 fixed. ButterManager crashed when it was installed for the first time.
### Version 2.4
- Delete log icon button fixed.
- Issue #28 fixed. There is an error for Plasma Desktop (and PyQT5) when the file explorer is opened and the user tries to select a directory when setting subvolumes up. Only for this case, TK will be used as workaround.
- 'Don't remove snapshots' and 'Snapshots to keep' parameters are not global anymore. The user will be able to configure them per subvolume.
- Now, when user deletes a specific snapshot, the log related to it will be removed too if it exists.
### Version 2.3
- Thanks to Fedora guys (Neal Gompa @Conan-Kudo and Michel Alexandre Salim @michel-slm) ButterManager has been restructured in order to be packaged for Fedora. Because of that, now the application won't need to be installed within a virtual environment so the package installation footprint will be very much smaller.
- Two new installation methods have been created for users who wants to install ButterManager from source code: [native and venv](https://github.com/egara/buttermanager/tree/master/install). The first one is the recommended but the second one is still supported just in case native installation doesn't work properly.
- Issue #26 fixed: Now, the **Upgrade with snapshots** button creates snapshots and removes the old ones if needed.
- All the fast action buttons are disabled when a critical operation is executing.
### Version 2.2
- More stability. Some bugs have been fixed and ButterManager should not crashed after upgrading the system.
- Other operations are now Fast actions.
- New fast actions implemented: Upgrade system with/without snapshots and Take snapshots.
### Version 2.1
- Delete icon has been redesigned.
- New button to open a file explorer within a specific snapshot has been implemented.
- New feature to calculate differences between current snapshot and a specified one has been implemented.
- User will be able to calculate full differences (it will take some time to complete) included files modified and files only present in one of the snapshots.
- User will be able to calculate partial differences that will be faster but it will only inlcude files modified.
### Version 2.0
- Now, the installer creates ~/.local/share/applications directory if it didn't exist in order to allocate the ButterManager desktop launcher.
- The method of calculating the default original subvolume to consolidate the system has been reimplemented and improved to avoid some bugs detected.
- Now, the allocation of the original snapshot is stored in fstab instead of the mounted point for every snapshot of root created.
- grub-mkconfig will run after consolidating deafult root subvolume
- Consolidation process will check the original path of the default subvolume for root and will use it in fstab.
### Version 1.9
- Buttermanager has been integrated with **grub-btrfs** package. It means that, for all these users who use GRUB will be able to boot its system from any snapshot created with this version of the application and above. This integration will be optional and configurable from **Settings** tab.
### Version 1.8 ###
- Font autoscaling implemented in order to let the GUI adapts to the current screen resolution.
- It has been created a new tab for **Documentation** and a **Wiki** at Github repository.
- The text of some tooltips have been fixed.
### Version 1.7 ###
- Bug fixed for Arch Linux and derivatives installing the package from AUR. Now, the application will be installed and run from a virtual environmen with all the modules needed. This causes that the size of the package buttermanager has increased
### Version 1.6 ###
- Logs generated during the upgrade process can be stored
- Logs management implemented
- Version checker implemented. When a new version of ButterManagger is released, a new info window will be display to warn the user
### Version 1.5 ###
- Labels refreshing after balancing the filesystem has been fixed
- Values to show certaing labels have been recalculated
### Version 1.4 ###
- System progress bar has been removed because it doesn't provide any relevant information
- A new button has been implemented in order to upgrade the system whithout managing snapshots
- All the ButterManager windows and dialogs have been reconfigured using fixed pixels in order to avoid the resizing
- The ButterManager icon has been assigned to all windows and dialogs
- When ButterManager is installed for the first time, the updates checker is not checked by default
- A new option added to yay command to check for AUR packages only
- New messages implemented in the main window in order to warn the user about the space of the filesystem
- Internet connection will be checked during 5 minutes. If there is no Internet connection, then the updates checker process will be cancelled
### Version 1.3 ###
- The updates checker is executed in other thread, so now the GUI is not freezed during the process.
### Version 1.2 ###
- Some layouts and texts fixed to fit properly
- New window to list the packages to be updated implemented
- Fixed a problem in the snap package for Wayland environments
### Version 1.1 ###
- RHEL / Fedora, OpenSUSE / SUSE support added.
- New window implemented for displaying serious problems related to the proper functioning of ButterManager.
### Version 1.0 ###
- Initial release.
- It supports Arch Linux, Debian, Ubuntu and derivatives.
- Safely system upgrade.
- BTRFS filesystems detection and visualization.
- Snapshots management.
- BTRFS filesystems balancing.
- Application packaged in AUR.
- Ubuntu Snap Package implemented for universal use in the rest of Linux distributions.
## Contact ##
If you want to contact me, you can do it using this e-mail address .
================================================
FILE: aur/PKGBUILD
================================================
# Maintainer: Eloy Garcia Almaden
pkgname=buttermanager
pkgver=2.5.2
pkgrel=0
epoch=
pkgdesc="Graphical tool to create BTRFS snapshots, balance filesystems and upgrade the system safetly"
arch=('x86_64')
url="https://github.com/egara/buttermanager"
license=('GPL')
groups=()
depends=('btrfs-progs' 'python>=3' 'grub-btrfs' 'python-setuptools' 'python-pyaml' 'python-pyqt5' 'tk')
makedepends=('python>=3' 'git')
checkdepends=()
optdepends=()
provides=()
conflicts=()
replaces=()
backup=()
options=()
install=
changelog=
# Local source if user wants to build the package locally once the git repo has been cloned
source=('git+file:////home/egarcia/Development/git/buttermanager/')
# Remote source
# Master branch
# source=('git+https://github.com/egara/buttermanager#branch=master')
# Tagged version
# source=('https://github.com/egara/buttermanager/archive/"$pkgver".tar.gz')
noextract=()
md5sums=('SKIP')
validpgpkeys=()
build() {
cd "$pkgname"
python setup.py build
}
package() {
cd "$pkgname"
# Creating destination directory
install -dm755 "$pkgdir/opt/$pkgname"
# Installing ButterManager using python-setuptools
echo -e "\n Installing ButterManager. Please wait..."
python setup.py install --root="$pkgdir" --optimize=1 --skip-build
# Copying .desktop file and icon
echo -e "\n Creating desktop icon. Finishing the installation"
install -Dm644 "$srcdir/$pkgname/packaging/$pkgname.desktop" "$pkgdir/usr/share/applications/$pkgname.desktop"
install -Dm644 "$srcdir/$pkgname/packaging/$pkgname.svg" "$pkgdir/opt/$pkgname/gui/$pkgname.svg"
}
================================================
FILE: aur/README.txt
================================================
This directory contains all the files needed to package ButterManager application for Arch Linux
================================================
FILE: buttermanager/bm_main.py
================================================
from .buttermanager.buttermanager import PasswordWindow
from PyQt5.QtWidgets import QApplication
import sys
def main():
"""Main wrapper for starting ButterManager
This script is only for packaging purposes. If you are developing ButterManager, then use main.py as initial
script. This script will be copied from setup.py using setuptools and it will be invoked from the script
created within /usr/bin/buttermanager once the application is installed via sudo python setup.py install
"""
# Creating application instance
application = QApplication(sys.argv)
# Creating main window instance
PasswordWindow(None)
# Launching the application
application.exec_()
if __name__ == "__main__":
main()
================================================
FILE: buttermanager/buttermanager/__init__.py
================================================
# Copyright 2018-2019 Eloy García Almadén
#
# This file is part of buttermanager.
#
# This program is free software: you can redistribute it and / or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
name = "buttermanager"
================================================
FILE: buttermanager/buttermanager/buttermanager.py
================================================
# -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Eloy García Almadén
#
# This file is part of buttermanager.
#
# This program is free software: you can redistribute it and / or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from .exception import exception
from .filesystem import filesystem, snapshot
from .manager import upgrader
from .util import utils, settings
from .window import windows
import os
import subprocess
import sys
import time
from functools import partial
from PyQt5.QtWidgets import QMainWindow, QDesktopWidget
from PyQt5.QtGui import QCursor, QTextCursor, QIcon, QPixmap, QDesktopServices, QFontMetrics
from PyQt5 import uic, QtTest, QtWidgets
from PyQt5.QtCore import Qt, pyqtSignal, QObject, QSize, QUrl
# Constants
SNAP_COMMAND = "snap"
FLATPAK_COMMAND = "flatpak"
class EmittingStream(QObject):
text_written = pyqtSignal(str)
def write(self, text):
self.text_written.emit(str(text))
def flush(self):
pass
class PasswordWindow(QMainWindow):
"""Window to let the user type his/her password.
Class inherited from QMainWindow (Window constructor)
"""
# Constructor
def __init__(self, parent):
QMainWindow.__init__(self, parent)
self.parent = parent
# Configuring the application
self.__buttermanager_configurator = utils.ConfigManager()
self.__buttermanager_configurator.configure()
# Locating ui and images directories
settings.ui_dir = os.path.join(os.path.dirname(__file__), 'ui')
settings.images_dir = os.path.join(os.path.dirname(__file__), 'images')
# UI elements
self.__ui_elements = []
# Logger
self.__logger = utils.Logger(self.__class__.__name__).get()
# Version checker
self.__version_checker = utils.VersionChecker(self)
# Initializing the application
self.init_ui()
def init_ui(self):
"""Initializes the Graphic User Interface.
"""
# Loading User Interface
password_window_ui = os.path.join(settings.ui_dir, 'PasswordWindow.ui')
uic.loadUi(password_window_ui, self)
# Setting the window icon
buttermanager_icon = os.path.join(settings.images_dir, 'buttermanager50.png')
self.setWindowIcon(QIcon(buttermanager_icon))
# Calculating the base font size for all UI elements in the application
settings.base_font_size = self.get_base_font_size()
# Adjusting font scale
# UI elements
self.__ui_elements = [self.label_password, self.button_ok, self.button_cancel, self.button_lock,
self.input_password]
utils.scale_fonts(self.__ui_elements)
# Tooltips
self.setStyleSheet(" QToolTip{font: " + str(settings.base_font_size) + "pt}")
# Setting size for the window
self.resize(320, 240)
# Setting lock icon
lock_icon = os.path.join(settings.images_dir, 'lock_24px_icon.png')
self.button_lock.setIcon(QIcon(lock_icon))
self.button_lock.setIconSize(QSize(24, 24))
# Centering the window
qt_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
qt_rectangle.moveCenter(center_point)
self.move(qt_rectangle.topLeft())
# Events
# OK button event
self.button_ok.clicked.connect(self.load_main_window)
# Cancel button event
self.button_cancel.clicked.connect(self.exit)
# Press enter within QLineEdit
self.input_password.returnPressed.connect(self.load_main_window)
# Set focus on input_password
self.input_password.setFocusPolicy(Qt.StrongFocus)
self.input_password.setFocus()
# Checks for new versions of ButterManager
self.__version_checker.check_version()
# Showing password window
self.show()
def get_base_font_size(self):
"""Gets the base font size for all the UI elements.
Returns:
int: Base font size.
"""
self.__logger.info("Calculating appropriated base font size for UI elements...")
font_fits = False
# Base font size will be calculated using self.label_password attribute
font = self.label_password.font()
font_size = font.pointSize()
while not font_fits:
fm = QFontMetrics(font)
pixels_wide = fm.width(self.label_password.text())
pixels_high = fm.height()
bound = fm.boundingRect(0, 0, pixels_wide, pixels_high, Qt.TextWordWrap | Qt.AlignLeft,
self.label_password.text())
if bound.width() <= self.label_password.width() and \
bound.height() <= self.label_password.height():
font_fits = True
else:
font.setPointSize(font.pointSize() - 1)
font_size = font_size - 1
self.__logger.info("Base font size = " + str(font_size))
return font_size
def load_main_window(self):
# Storing user's password
settings.user_password = self.input_password.text()
# Exiting password window
self.hide()
# Creating main window
# Main window will only be displayed if everything goes right
ButtermanagerMainWindow(self)
def exit(self):
# Exits the application
self.hide()
sys.exit()
class ButtermanagerMainWindow(QMainWindow):
"""Main window.
Class inherited from QMainWindow (Window constructor)
"""
# Constructor
def __init__(self, parent):
QMainWindow.__init__(self, parent)
self.parent = parent
# Logger
self.__logger = utils.Logger(self.__class__.__name__).get()
# Current filesystem (it will be initialize in initialize method)
self.__current_filesystem = None
# Current filesystem uuid (it will be initialize in initialize method)
self.__current_filesystem_uuid = None
# Balancer that will balance the current filesystem if it is needed
self.__balancer = None
# Differentiator that will calculate the differences between a snapshot and the current
# subvolume
self.__differentiator = None
# Upgrader that will upgrade the system if it is needed
self.__upgrader = None
# Updates checker that will check for updates if it is needed
self.__updates_checker = None
# Root snapshot checker
self.__root_snapshot_checker = snapshot.RootSnapshotChecker(self)
# UI elements
self.__ui_elements = []
# Initializing the application
self.init_ui()
# Installing the custom output stream to write all the console content to the
# QTextEdit component
sys.stdout = EmittingStream(text_written=self.normal_output_written)
def __del__(self):
"""Restores sys.stdout.
"""
sys.stdout = sys.__stdout__
def normal_output_written(self, text):
"""Appends text to the QTextEdit text_edit_console.
"""
cursor = self.text_edit_console.textCursor()
cursor.movePosition(QTextCursor.End)
cursor.insertText(text)
self.text_edit_console.setTextCursor(cursor)
self.text_edit_console.ensureCursorVisible()
def init_ui(self):
"""Initializes the Graphic User Interface.
"""
try:
# Loading User Interface
main_window_ui = os.path.join(settings.ui_dir, 'MainWindow.ui')
uic.loadUi(main_window_ui, self)
# Setting the window icon
buttermanager_icon = os.path.join(settings.images_dir, 'buttermanager50.png')
self.setWindowIcon(QIcon(buttermanager_icon))
# Adjusting font scale
# UI elements
self.__ui_elements = [self.tab_buttermanager, self.label_filesystem_info, self.label_filesystem_data,
self.label_filesystem_metadata, self.label_filesystem, self.label_other_operations,
self.label_filesystem_size, self.label_filesystem_size_value,
self.label_filesystem_allocated, self.label_filesystem_allocated_value,
self.label_filesystem_lost_info, self.label_filesystem_info_more, self.label_space_ok,
self.label_space_danger, self.label_space_ko, self.label_space_data_danger,
self.label_settings_upgrade, self.label_settings_subvolumes,
self.label_existing_subvolumes, self.label_logo,
self.label_app_name, self.label_app_version, self.label_app_developer,
self.label_app_email, self.label_app_developer_2, self.button_balance,
self.button_upgrade_system, self.button_upgrade_system_without_snapshots,
self.button_fa_take_snapshot, self.button_take_snapshot,
self.button_delete_snapshot, self.button_delete_log, self.button_view_log,
self.button_edit_subvolume, self.button_delete_subvolume, self.button_add_subvolume,
self.button_save_subvolume, self.button_github, self.button_close_terminal,
self.button_save_log, self.text_edit_console, self.progressbar_metadata,
self.progressbar_data, self.combobox_filesystem, self.list_snapshots, self.list_logs,
self.combobox_subvolumes, self.line_edit_snapshot_where,
self.line_edit_snapshot_prefix, self.checkbox_edit_dont_remove_snapshots,
self.spinbox_edit_snapshots_to_keep, self.checkbox_startup, self.checkbox_log,
self.checkbox_snap, self.checkbox_flatpak, self.checkbox_aur, self.button_save_log,
self.button_close_terminal, self.button_wiki, self.label_documentation,
self.checkbox_grub_btrfs, self.button_regenerate_grub, self.label_settings_ui,
self.label_font_size, self.spinbox_font_size_increment,
self.label_settings_subvolumes_where, self.label_settings_subvolumes_prefix,
self.label_settings_subvolumes_snapshots_to_keep]
utils.scale_fonts(self.__ui_elements)
# Tooltips
self.setStyleSheet(" QToolTip{font: " + str(settings.base_font_size) + "pt}")
# Setting maximum and minimum size for the main window
self.setMinimumHeight(300)
self.setMinimumWidth(300)
# Hiding terminal and buttons
self.button_close_terminal.hide()
self.button_save_log.hide()
self.text_edit_console.hide()
# Setting initial size depending on resolution
size_object = QtWidgets.QDesktopWidget().screenGeometry(-1)
if size_object.width() == 1920:
self.resize(640, 520)
elif size_object.width() > 1920:
self.resize(1024, 832)
else:
self.resize(320, 260)
# Centering the window
qt_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
qt_rectangle.moveCenter(center_point)
self.move(qt_rectangle.topLeft())
# Retrieving BTRFS Filesystems uuid
uuid_filesystems = filesystem.get_btrfs_filesystems()
if len(uuid_filesystems) > 0:
self.__current_filesystem_uuid = uuid_filesystems[0]
self.combobox_filesystem.addItems(uuid_filesystems)
self.__current_filesystem = filesystem.Filesystem(self.__current_filesystem_uuid)
self.__logger.info("BTRFS filesystems found in the system:")
self.__logger.info(str(self.__current_filesystem))
# Space labels
self.label_space_ok.setStyleSheet('color: green')
self.label_space_danger.setStyleSheet('color: orange')
self.label_space_ko.setStyleSheet('color: red')
self.label_space_data_danger.setStyleSheet('color: orange')
# Displaying all the info related to the filesystem selected by default
# and labels (show_labels will be invoked within fill_filesystem_info method)
self.fill_filesystem_info(self.__current_filesystem)
# Displaying snapshots
self.fill_snapshots()
# Displaying logs
self.fill_logs()
# Retrieving subvolumes
self.fill_subvolumes()
# BEGIN -- Displaying settings options
# Retrieving snap packages upgrade decision
if settings.snap_packages == 0:
self.checkbox_snap.setChecked(False)
else:
self.checkbox_snap.setChecked(True)
if utils.exist_program(SNAP_COMMAND):
self.checkbox_snap.show()
else:
self.checkbox_snap.hide()
if utils.exist_program(SNAP_COMMAND):
self.checkbox_snap.show()
else:
self.checkbox_snap.hide()
# Retrieving Flatpak packages upgrade decision
if settings.flatpak_packages == 0:
self.checkbox_flatpak.setChecked(False)
else:
self.checkbox_flatpak.setChecked(True)
if utils.exist_program(FLATPAK_COMMAND):
self.checkbox_flatpak.show()
else:
self.checkbox_flatpak.hide()
# Retrieving AUR packages upgrade decision
if settings.aur_repository == 0:
self.checkbox_aur.setChecked(False)
else:
self.checkbox_aur.setChecked(True)
if settings.user_os == utils.OS_ARCH:
self.checkbox_aur.show()
else:
self.checkbox_aur.hide()
# Retrieving check for updates at startup decision
if settings.check_at_startup == 0:
self.checkbox_startup.setChecked(False)
else:
self.checkbox_startup.setChecked(True)
# Retrieving boot the system from GRUB using snapshots decision
if settings.grub_btrfs == 0:
self.checkbox_grub_btrfs.setChecked(False)
self.button_regenerate_grub.hide()
else:
self.checkbox_grub_btrfs.setChecked(True)
self.button_regenerate_grub.show()
if settings.user_os == utils.OS_ARCH or \
settings.user_os == utils.OS_DEBIAN or \
settings.user_os == utils.OS_SUSE or \
settings.user_os == utils.OS_FEDORA:
self.checkbox_startup.show()
else:
self.checkbox_startup.hide()
# Retrieving save log decision
if settings.save_log == 0:
self.checkbox_log.setChecked(False)
else:
self.checkbox_log.setChecked(True)
# Retrieving font size increment
self.spinbox_font_size_increment.setValue(settings.font_size_increment)
# END -- Displaying settings options
# Setting buttons and icons
# Snapshot buttons
add_icon = os.path.join(settings.images_dir, 'add_16px_icon.png')
self.button_take_snapshot.setIcon(QIcon(add_icon))
self.button_take_snapshot.setIconSize(QSize(16, 16))
remove_icon = os.path.join(settings.images_dir, 'remove_16px_icon.png')
self.button_delete_snapshot.setIcon(QIcon(remove_icon))
self.button_delete_snapshot.setIconSize(QSize(16, 16))
exchange_arrows_icon = os.path.join(settings.images_dir, 'exchange_arrows_16px_icon.png')
self.button_diff.setIcon(QIcon(exchange_arrows_icon))
self.button_diff.setIconSize(QSize(16, 16))
folder_icon = os.path.join(settings.images_dir, 'folder_16px_icon.png')
self.button_folder.setIcon(QIcon(folder_icon))
self.button_folder.setIconSize(QSize(16, 16))
# Logs buttons
view_icon = os.path.join(settings.images_dir, 'view_24px_icon.png')
self.button_view_log.setIcon(QIcon(view_icon))
self.button_view_log.setIconSize(QSize(16, 16))
self.button_delete_log.setIcon(QIcon(remove_icon))
self.button_delete_log.setIconSize(QSize(16, 16))
# Subvolume buttons
accept_icon = os.path.join(settings.images_dir, 'accept_16px_icon.png')
self.button_save_subvolume.setIcon(QIcon(accept_icon))
self.button_save_subvolume.setIconSize(QSize(16, 16))
edit_icon = os.path.join(settings.images_dir, 'edit_16px_icon.png')
self.button_edit_subvolume.setIcon(QIcon(edit_icon))
self.button_edit_subvolume.setIconSize(QSize(16, 16))
self.button_delete_subvolume.setIcon(QIcon(remove_icon))
self.button_delete_subvolume.setIconSize(QSize(16, 16))
self.refresh_subvolume_buttons()
# Displaying logo within About tab
self.label_logo.setPixmap(QPixmap(buttermanager_icon))
# Button events
self.combobox_filesystem.currentTextChanged.connect(self.on_combobox_filesystem_changed)
self.button_balance.clicked.connect(self.balance_filesystem)
self.button_upgrade_system.clicked.connect(partial(self.upgrade_system, True))
self.button_upgrade_system_without_snapshots.clicked.connect(partial(self.upgrade_system, False))
self.button_fa_take_snapshot.clicked.connect(self.take_snapshot)
self.button_close_terminal.clicked.connect(self.close_terminal)
self.button_save_log.clicked.connect(self.save_log)
self.button_take_snapshot.clicked.connect(self.take_snapshot)
self.button_delete_snapshot.clicked.connect(self.delete_snapshots)
self.button_diff.clicked.connect(self.find_diffs)
self.button_folder.clicked.connect(self.open_file_explorer)
self.button_delete_log.clicked.connect(self.delete_logs)
self.button_view_log.clicked.connect(self.view_log)
self.checkbox_edit_dont_remove_snapshots.clicked.connect(self.dont_remove_snapshots)
self.checkbox_snap.clicked.connect(self.include_snap)
self.checkbox_flatpak.clicked.connect(self.include_flatpak)
self.checkbox_aur.clicked.connect(self.include_aur)
self.checkbox_log.clicked.connect(self.include_log)
self.checkbox_startup.clicked.connect(self.include_startup)
self.checkbox_grub_btrfs.clicked.connect(self.include_grub_btrfs)
self.spinbox_font_size_increment.valueChanged.connect(self.change_font_size_increment)
self.button_add_subvolume.clicked.connect(self.add_subvolume)
self.button_edit_subvolume.clicked.connect(self.edit_subvolume)
self.button_save_subvolume.clicked.connect(self.save_subvolume)
self.button_delete_subvolume.clicked.connect(self.delete_subvolume)
self.combobox_subvolumes.currentTextChanged.connect(self.on_combobox_subvolumes_changed)
self.button_github.clicked.connect(self.go_to_github)
self.button_wiki.clicked.connect(self.go_to_wiki)
self.button_regenerate_grub.clicked.connect(self.regenerate_grub)
# If no subvolumes are defined, warning the user
if len(settings.subvolumes) == 0:
info_dialog = windows.GeneralInfoWindow(self, "Warning: You don't have any subvolumes "
"added.\n"
"If you upgrade the filesystem, no snapshots "
"will\n"
"be created. If you want to create "
"automatically\n"
"snapshots during the upgrading process, "
"go to\n"
"Settings and Add a subvolume.")
info_dialog.show()
# If everything goes right, the main window is displayed
self.show()
# Checks for root snapshot mounted
root_snapshot_default = self.__root_snapshot_checker.check_root_snapshot()
if root_snapshot_default:
# Show the updates window only if the user wants to and if there are updates
self.check_updates()
else:
consolidate_window = self.__root_snapshot_checker.open_consolidate_snapshot_window()
# Hiding the main window and showing the consolidate window in order to proceed
self.hide()
consolidate_window.show()
consolidation = consolidate_window.exec_()
if consolidation == 1:
# User chose Ok button to consolidate root snapshot and the process finished successfully
info_dialog = windows.ProblemsFoundWindow(self,
"The snapshot you choose to boot the system \n"
"has been consolidated as the default root \n"
"snapshot. Please, reboot the system now.")
info_dialog.show()
elif consolidation == 2:
# User chose Ok button to consolidate root snapshot and the process didn't finish
# successfully
info_dialog = windows.ProblemsFoundWindow(self,
"Error trying to substitute the root's path \n"
"in fstab with the path of the new snapshot \n"
"created")
info_dialog.show()
elif consolidation == 3:
# User chose Ok button to consolidate root snapshot and the process didn't finish
# successfully
info_dialog = windows.ProblemsFoundWindow(self,
"Error removing root snapshot because it is \n"
"not empty and there are subvolumes \n"
"within it. The consolidation process \n"
"couldn't be done.")
info_dialog.show()
else:
# User chose Cancel button so the application must be closed
info_dialog = windows.ProblemsFoundWindow(self,
"In order to avoid problems, ButterManager \n"
"cannot execute any operations under \n"
"a non default root snapshot so it will be "
"closed.")
self.close()
info_dialog.show()
else:
self.__logger.info("The application couldn't start normally. No BTRFS file system found.")
info_dialog = windows.ProblemsFoundWindow(self, "No BTRFS file system found. \n"
"The application will be closed.")
info_dialog.show()
except exception.NoCommandFound:
self.__logger.info("The application couldn't start normally. There are some programs needed that are not "
"installed.")
self.__logger.info("Please, install these programs and start ButterManager again.")
info_dialog = windows.ProblemsFoundWindow(self, "These programs need to be installed for \n"
"the proper functioning of ButterManager:\n"
"btrfs, findmnt.\n")
info_dialog.show()
def check_updates(self):
"""Creates the updates checker that will start in another thread and check system updates.
"""
self.__updates_checker = upgrader.UpdatesChecker()
self.__updates_checker.show_updates_window.connect(self.show_updates_window)
self.__updates_checker.start()
def show_updates_window(self, command_line_output):
""" Shows a new window with all the packages to be updated.
Once the updates_checker knows all the packages that need to be updated, a new
UpdatesWindow will be opened from the main GUI thread.
Arguments:
command_line_output (list(:obj:`str`)): Packages to be updated. One per line.
"""
updates_window = windows.UpdatesWindow(self, command_line_output)
updates_window.upgrade_system.connect(self.upgrade_system)
updates_window.upgrade_system_without_snanpshots.connect(partial(self.upgrade_system, False))
updates_window.show()
def balance_filesystem(self):
"""Runs the balance method.
"""
self.__balancer = filesystem.BalanceManager(self.__current_filesystem.data_percentage,
self.__current_filesystem.metadata_percentage,
self.__current_filesystem.mounted_points[0])
self.__balancer.show_one_window.connect(self.manage_window)
# Connecting the signal emitted by the balancer with this slot
self.__balancer.refresh_filesystem_statistics.connect(self.refresh_filesystem_statistics)
self.__balancer.start()
def manage_window(self, hide):
"""Shows or hide the main window
If some important operation (like, f.e. balancing the current filesystem) is being done, then
the main window should be hidden in order to avoid the user click on any other button and run
another operation until the current is finished.
Arguments:
hide (boolean): Hide or show the main window.
"""
if hide:
self.hide()
else:
self.show()
def refresh_filesystem_statistics(self):
"""Refresh current filesystem statistics in the GUI.
"""
# Calculating new values for the current filesystem
self.__current_filesystem = filesystem.Filesystem(self.__current_filesystem_uuid)
# Displaying all the info related to the current filesystem
self.fill_filesystem_info(self.__current_filesystem)
def fill_filesystem_info(self, filesystem):
"""Fills filesystem information in the GUI.
Arguments:
filesystem (obj: Filesystem): Filesystem.
"""
tooltip = "More info about the filesystem: \n \n" \
"Devices: {devices} \n" \
"Mounted points: {mounted_points}".format(devices=filesystem.devices,
mounted_points=filesystem.mounted_points)
self.label_filesystem_info_more.setToolTip(tooltip)
self.label_filesystem_info_more.setCursor(QCursor(Qt.WhatsThisCursor))
self.label_filesystem_size_value.setText(filesystem.total_size)
self.label_filesystem_allocated_value.setText(filesystem.total_allocated)
self.progressbar_data.setValue(filesystem.data_percentage)
self.progressbar_metadata.setValue(filesystem.metadata_percentage)
# self.progressbar_system.setValue(filesystem.system_percentage)
# Showing labels
self.show_space_labels()
def upgrade_system(self, snapshots=True):
"""Runs the system upgrade operation.
Arguments:
snapshots (boolean): Create and delete snapshots when the upgrading process is executed.
"""
# Showing terminal and buttons
self.button_close_terminal.show()
# Save log button will only be displayed when the logs are
# not saved automatically
if settings.save_log == 0:
self.button_save_log.show()
else:
self.button_save_log.hide()
self.text_edit_console.show()
# Checking if there is any subvolume defined by the user
if len(settings.subvolumes) == 0:
snapshots = False
# Gathering user settings
include_aur = False
if settings.user_os == utils.OS_ARCH:
include_aur = self.checkbox_aur.isChecked()
include_snap = False
if utils.exist_program(SNAP_COMMAND):
include_snap = self.checkbox_snap.isChecked()
include_flatpak = False
if utils.exist_program(FLATPAK_COMMAND):
include_flatpak = self.checkbox_flatpak.isChecked()
# Upgrading the system
self.__upgrader = upgrader.Upgrader(include_aur, include_snap, include_flatpak, snapshots)
# Connecting the signal emitted by the upgrader with this slot
self.__upgrader.disable_buttons.connect(self.__disable_buttons)
# Connecting the signal emitted by the upgrader with this slot
self.__upgrader.enable_buttons.connect(self.__enable_buttons)
# Connecting the signal emitted by the upgrader with this slot
# Depending on the decision to save or not the logs, the signal
# will be connected to a different slot
save_log = self.checkbox_log.isChecked()
if save_log:
# Saving log if it is needed
self.__upgrader.refresh_gui.connect(self.save_log_refresh_gui)
else:
self.__upgrader.refresh_gui.connect(self.refresh_gui)
self.__upgrader.start()
def close_terminal(self):
"""Closes terminal.
It will restore the proper windows size
"""
# Hiding terminal and buttons
self.button_close_terminal.hide()
self.button_save_log.hide()
self.text_edit_console.hide()
def save_log(self):
"""Saves the current content of the terminal into a file.
"""
try:
current_date = time.strftime('%Y%m%d')
index = 0
log_name = "{current_date}-{index}.txt".format(current_date=current_date, index=str(index))
log_path = os.path.join(settings.logs_path, log_name)
while os.path.exists(log_path):
index += 1
log_name = "{current_date}-{index}.txt".format(current_date=current_date, index=str(index))
log_path = os.path.join(settings.logs_path, log_name)
# Gets the content and saves it
log = self.text_edit_console.toPlainText()
with open(log_path, 'a') as file:
file.write(log)
except Exception as exception:
self.__logger.info("Error saving the log: " + str(exception))
def __disable_buttons(self):
"""Disables all the buttons of the GUI.
"""
self.combobox_filesystem.setEnabled(False)
self.button_balance.setEnabled(False)
self.button_upgrade_system.setEnabled(False)
self.button_upgrade_system_without_snapshots.setEnabled(False)
self.button_fa_take_snapshot.setEnabled(False)
self.button_close_terminal.setEnabled(False)
self.list_snapshots.setEnabled(False)
self.list_logs.setEnabled(False)
self.combobox_subvolumes.setEnabled(False)
self.checkbox_startup.setEnabled(False)
self.checkbox_log.setEnabled(False)
self.checkbox_snap.setEnabled(False)
self.checkbox_aur.setEnabled(False)
self.checkbox_grub_btrfs.setEnabled(False)
self.checkbox_flatpak.setEnabled(False)
self.spinbox_font_size_increment.setEnabled(False)
self.button_take_snapshot.setEnabled(False)
self.button_delete_snapshot.setEnabled(False)
self.button_diff.setEnabled(False)
self.button_folder.setEnabled(False)
self.button_add_subvolume.setEnabled(False)
self.button_delete_subvolume.setEnabled(False)
self.button_edit_subvolume.setEnabled(False)
self.button_save_subvolume.setEnabled(False)
self.button_view_log.setEnabled(False)
self.button_delete_log.setEnabled(False)
self.button_regenerate_grub.setEnabled(False)
def __enable_buttons(self):
"""Enable all the buttons of the GUI.
"""
self.combobox_filesystem.setEnabled(True)
self.button_balance.setEnabled(True)
self.button_upgrade_system.setEnabled(True)
self.button_upgrade_system_without_snapshots.setEnabled(True)
self.button_fa_take_snapshot.setEnabled(True)
self.button_close_terminal.setEnabled(True)
self.list_snapshots.setEnabled(True)
self.list_logs.setEnabled(True)
self.combobox_subvolumes.setEnabled(True)
self.checkbox_startup.setEnabled(True)
self.checkbox_log.setEnabled(True)
self.checkbox_snap.setEnabled(True)
self.checkbox_aur.setEnabled(True)
self.checkbox_grub_btrfs.setEnabled(True)
self.checkbox_flatpak.setEnabled(True)
self.spinbox_font_size_increment.setEnabled(True)
self.button_take_snapshot.setEnabled(True)
self.button_delete_snapshot.setEnabled(True)
self.button_diff.setEnabled(True)
self.button_folder.setEnabled(True)
self.button_add_subvolume.setEnabled(True)
self.button_delete_subvolume.setEnabled(True)
self.button_edit_subvolume.setEnabled(True)
self.button_save_subvolume.setEnabled(True)
self.button_view_log.setEnabled(True)
self.button_delete_log.setEnabled(True)
self.button_regenerate_grub.setEnabled(True)
def take_snapshot(self):
"""Takes a BTRFS subvolume snapshot.
"""
snapshot_window = windows.SnapshotWindow(self)
# Connecting the signals emitted by the snapshot window with this slot
snapshot_window.refresh_gui.connect(self.refresh_gui)
snapshot_window.enable_buttons.connect(self.__enable_buttons)
# Disabling buttons
self.__disable_buttons()
# Displaying snapshot window
snapshot_window.show()
# Enabling buttons
self.__disable_buttons()
def delete_snapshots(self):
"""Deletes one or several BTRFS subvolume snapshots.
"""
# Disabling buttons
self.__disable_buttons()
# Waiting 10 msec in order to let self.__disable_buttons to take effect
QtTest.QTest.qWait(10)
snapshots_to_delete = self.list_snapshots.selectedItems()
for snap in snapshots_to_delete:
snapshot.delete_specific_snapshot(snap.text())
# Refreshing GUI
self.refresh_gui()
# Enabling buttons
self.__enable_buttons()
def find_diffs(self):
"""Find differences between the snapshot selected and the current state of the subvolume related to it.
"""
snapshot_to_diff = self.list_snapshots.selectedItems()
if len(snapshot_to_diff) != 1:
# Only one snapshot can be selected
info_dialog = windows.GeneralInfoWindow(self, "Please, select one (and only one) snapshot\n"
"in order to find the differences between\n"
"it and the current subvolume.")
info_dialog.show()
else:
# Disabling buttons
self.__disable_buttons()
# Waiting 10 msec in order to let self.__disable_buttons to take effect
QtTest.QTest.qWait(10)
# The user has to select the kind of operation
diff_window = windows.DiffWindow()
# Hidding the main window and showing the diff window in order to proceed
self.hide()
diff_window.show()
diff_process = diff_window.exec_()
if diff_process == 1:
# A full operation will be done
self.__differentiator = snapshot.Differentiator(
snapshot_to_diff[0].text(),
snapshot.Differentiator.OPERATION_FULL)
elif diff_process == 2:
# A partial operation will be done
self.__differentiator = snapshot.Differentiator(
snapshot_to_diff[0].text(),
snapshot.Differentiator.OPERATION_PARTIAL)
self.__differentiator.show_one_window.connect(self.manage_window)
self.__differentiator.start()
# Refreshing GUI
self.refresh_gui()
# Enabling buttons
self.__enable_buttons()
# Showing main window again
self.show()
def open_file_explorer(self):
"""Opens a file explorer to see all the files within a snapshot.
"""
snapshots_selected = self.list_snapshots.selectedItems()
if len(snapshots_selected) != 1:
# Only one snapshot can be selected
info_dialog = windows.GeneralInfoWindow(self, "Please, select one (and only one) snapshot \n"
"in order to open the file explorer.")
info_dialog.show()
else:
subprocess.call(['xdg-open', snapshots_selected[0].text()])
def delete_logs(self):
"""Deletes one or several logs.
"""
logs_to_delete = self.list_logs.selectedItems()
for log in logs_to_delete:
os.remove(os.path.join(settings.logs_path, log.text()))
# Refreshing GUI
self.refresh_gui()
def view_log(self):
"""Opens the log in a new window to display it.
"""
logs_to_view = self.list_logs.selectedItems()
for log in logs_to_view:
log_window = windows.LogViewWindow(self, os.path.join(settings.logs_path, log.text()))
log_window.show()
def add_subvolume(self):
"""Adds a new subvolume to be managed by the application.
"""
subvolume_window = windows.SubvolumeWindow(self)
# Connecting the signal emitted by the subvolume window with this slot
subvolume_window.refresh_gui.connect(self.refresh_gui)
# Displaying snapshot window
subvolume_window.show()
def dont_remove_snapshots(self):
"""Actions when user checks don't remove snapshots.
"""
if self.checkbox_edit_dont_remove_snapshots.isChecked():
self.spinbox_edit_snapshots_to_keep.hide()
else:
self.spinbox_edit_snapshots_to_keep.show()
self.spinbox_edit_snapshots_to_keep.setValue(1)
def include_snap(self):
"""Actions when user checks include snap packages.
"""
# Storing value in settings
if self.checkbox_snap.isChecked():
settings.properties_manager.set_property('snap_packages', 1)
else:
settings.properties_manager.set_property('snap_packages', 0)
def include_flatpak(self):
"""Actions when user checks include flatpak packages.
"""
# Storing value in settings
if self.checkbox_flatpak.isChecked():
settings.properties_manager.set_property('flatpak_packages', 1)
else:
settings.properties_manager.set_property('flatpak_packages', 0)
def include_aur(self):
"""Actions when user checks include AUR packages.
"""
# Storing value in settings
if self.checkbox_aur.isChecked():
settings.properties_manager.set_property('aur_repository', 1)
else:
settings.properties_manager.set_property('aur_repository', 0)
def include_log(self):
"""Actions when user checks include log.
"""
# Storing value in settings
if self.checkbox_log.isChecked():
settings.properties_manager.set_property('save_log', 1)
else:
settings.properties_manager.set_property('save_log', 0)
def include_startup(self):
"""Actions when user checks check updates at startup.
"""
# Storing value in settings
if self.checkbox_startup.isChecked():
settings.properties_manager.set_property('check_at_startup', 1)
else:
settings.properties_manager.set_property('check_at_startup', 0)
def include_grub_btrfs(self):
"""Actions when user checks boot the system from GRUB using snapshots.
"""
# Storing value in settings
if self.checkbox_grub_btrfs.isChecked():
settings.properties_manager.set_property('grub_btrfs', 1)
self.button_regenerate_grub.show()
else:
settings.properties_manager.set_property('grub_btrfs', 0)
self.button_regenerate_grub.hide()
def change_font_size_increment(self):
"""Actions when user increases or decreases the UI font size.
"""
# Storing value in settings
settings.properties_manager.set_property('font_size_increment', self.spinbox_font_size_increment.value())
# Changing UI font size dynamically
utils.scale_fonts(self.__ui_elements)
def on_combobox_filesystem_changed(self):
self.__current_filesystem_uuid = self.combobox_filesystem.currentText()
self.refresh_filesystem_statistics()
def on_combobox_subvolumes_changed(self):
current_subvolume = self.combobox_subvolumes.currentText()
if current_subvolume:
self.line_edit_snapshot_where.setText(settings.subvolumes[current_subvolume].subvolume_dest)
self.line_edit_snapshot_prefix.setText(settings.subvolumes[current_subvolume].snapshot_name)
snapshots_to_keep = int(settings.subvolumes[current_subvolume].snapshots_to_keep)
if snapshots_to_keep == -1:
# Enable Don't remove snapshots
self.checkbox_edit_dont_remove_snapshots.show()
self.checkbox_edit_dont_remove_snapshots.setChecked(True)
self.checkbox_edit_dont_remove_snapshots.setDisabled(True)
# Hide snapshots to keep
self.spinbox_edit_snapshots_to_keep.hide()
else:
# Enable snapshots to keep
self.spinbox_edit_snapshots_to_keep.show()
self.spinbox_edit_snapshots_to_keep.setDisabled(True)
self.spinbox_edit_snapshots_to_keep.setValue(snapshots_to_keep)
# Show Don't remove snapshots and disable it
self.checkbox_edit_dont_remove_snapshots.show()
self.checkbox_edit_dont_remove_snapshots.setDisabled(True)
def edit_subvolume(self):
"""Actions when user wants to edit a defined subvolume.
"""
# Buttons management
self.button_save_subvolume.show()
self.button_edit_subvolume.hide()
self.button_delete_subvolume.hide()
self.line_edit_snapshot_where.setDisabled(False)
self.line_edit_snapshot_prefix.setDisabled(False)
self.spinbox_edit_snapshots_to_keep.setDisabled(False)
self.checkbox_edit_dont_remove_snapshots.setDisabled(False)
def save_subvolume(self):
"""Actions when user finishes to edit a subvolume.
"""
# Buttons management
self.button_save_subvolume.hide()
self.button_edit_subvolume.show()
self.button_delete_subvolume.show()
self.line_edit_snapshot_where.setDisabled(True)
self.line_edit_snapshot_prefix.setDisabled(True)
self.spinbox_edit_snapshots_to_keep.setDisabled(True)
self.checkbox_edit_dont_remove_snapshots.setDisabled(True)
# Storing the modified values
new_snapshot_where = self.line_edit_snapshot_where.text()
new_snapshot_prefix = self.line_edit_snapshot_prefix.text()
subvolume_selected = self.combobox_subvolumes.currentText()
snapshots_to_keep = -1
if not self.checkbox_edit_dont_remove_snapshots.isChecked():
snapshots_to_keep = self.spinbox_edit_snapshots_to_keep.value()
settings.properties_manager.set_subvolume(subvolume_selected, new_snapshot_where, new_snapshot_prefix,
snapshots_to_keep)
# Refreshing components
self.refresh_gui()
def delete_subvolume(self):
"""Actions when user wants to delete a subvolume.
"""
# Storing the modified values
subvolume_selected = self.combobox_subvolumes.currentText()
settings.properties_manager.set_subvolume(subvolume_selected, None, None, None)
# Refreshing components
self.refresh_gui()
def go_to_github(self):
"""Actions when user clicks on github button.
"""
url = QUrl('https://github.com/egara/buttermanager')
QDesktopServices.openUrl(url)
def go_to_wiki(self):
"""Actions when user clicks on github button.
"""
url = QUrl('https://github.com/egara/buttermanager/wiki')
QDesktopServices.openUrl(url)
def fill_snapshots(self):
"""Fills snapshots information in the GUI.
"""
# Resetting snapshots in the GUI
# Clearing the list
self.list_snapshots.clear()
# Adding the snapshots to the list
snapshots = []
self.list_snapshots.addItems(snapshots)
# Loading the snapshots detected
for subvolume in settings.subvolumes:
snapshots.extend(settings.subvolumes[subvolume].get_all_snapshots_with_the_same_name())
self.list_snapshots.addItems(snapshots)
def fill_logs(self):
"""Fills logs in the GUI.
"""
# Resetting logs in the GUI
# Clearing the list
self.list_logs.clear()
# Adding the logs to the list
logs = os.listdir(settings.logs_path)
self.list_logs.addItems(logs)
def fill_subvolumes(self):
"""Fills subvolumes in the GUI.
"""
# Resetting combo
self.combobox_subvolumes.clear()
# Adding the new subvolumes to the combobox
list_subvolumes = []
if len(settings.subvolumes) > 0:
for subvolume in settings.subvolumes:
list_subvolumes.append(subvolume)
self.combobox_subvolumes.addItems(list_subvolumes)
self.line_edit_snapshot_where.setDisabled(True)
self.line_edit_snapshot_where.setText(settings.subvolumes[list_subvolumes[0]].subvolume_dest)
self.line_edit_snapshot_prefix.setDisabled(True)
self.line_edit_snapshot_prefix.setText(settings.subvolumes[list_subvolumes[0]].snapshot_name)
snapshots_to_keep = int(settings.subvolumes[list_subvolumes[0]].snapshots_to_keep)
if snapshots_to_keep == -1:
# Enable Don't remove snapshots
self.checkbox_edit_dont_remove_snapshots.show()
self.checkbox_edit_dont_remove_snapshots.setChecked(True)
self.checkbox_edit_dont_remove_snapshots.setDisabled(True)
# Hide snapshots to keep
self.spinbox_edit_snapshots_to_keep.hide()
else:
# Enable snapshots to keep
self.spinbox_edit_snapshots_to_keep.show()
self.spinbox_edit_snapshots_to_keep.setDisabled(True)
self.spinbox_edit_snapshots_to_keep.setValue(snapshots_to_keep)
# Show Don't remove snapshots and disable it
self.checkbox_edit_dont_remove_snapshots.show()
self.checkbox_edit_dont_remove_snapshots.setDisabled(True)
def refresh_subvolume_buttons(self):
"""Shows or hide subvolume buttons in the GUI.
"""
# They will be shown only if some subvolume is defined by the user
if len(settings.subvolumes) > 0:
self.button_save_subvolume.hide()
self.button_edit_subvolume.show()
self.button_delete_subvolume.show()
self.combobox_subvolumes.show()
self.line_edit_snapshot_where.show()
self.label_settings_subvolumes_where.show()
self.line_edit_snapshot_prefix.show()
self.label_settings_subvolumes_prefix.show()
else:
self.label_existing_subvolumes.hide()
self.button_save_subvolume.hide()
self.button_edit_subvolume.hide()
self.button_delete_subvolume.hide()
self.combobox_subvolumes.hide()
self.line_edit_snapshot_where.hide()
self.label_settings_subvolumes_where.hide()
self.line_edit_snapshot_prefix.hide()
self.label_settings_subvolumes_prefix.hide()
def refresh_gui(self):
"""Refresh all the GUI elements.
"""
self.refresh_filesystem_statistics()
self.fill_snapshots()
self.fill_logs()
self.fill_subvolumes()
self.refresh_subvolume_buttons()
self.show_space_labels()
def save_log_refresh_gui(self):
"""Save log and refresh all the GUI elements.
"""
self.save_log()
self.refresh_gui()
def show_space_labels(self):
"""Shows the appropiate labels related to the space left of the system.
"""
filesystem_space_pertentage = utils.get_percentage(self.__current_filesystem.total_size,
self.__current_filesystem.total_allocated)
if filesystem_space_pertentage <= 70:
self.label_space_ok.show()
self.label_space_danger.hide()
self.label_space_ko.hide()
elif filesystem_space_pertentage > 70 & filesystem_space_pertentage <= 85:
self.label_space_ok.hide()
self.label_space_danger.show()
self.label_space_ko.hide()
else:
self.label_space_ok.hide()
self.label_space_danger.hide()
self.label_space_ko.show()
if self.__current_filesystem.data_percentage <= 85:
self.label_space_data_danger.show()
else:
self.label_space_data_danger.hide()
def regenerate_grub(self):
"""Regenerates GRUB menu to include the snapshots taken as bootable entries.
"""
# Disabling buttons
self.__disable_buttons()
# Waiting 100 msec in order to let self.__disable_buttons to take effect
QtTest.QTest.qWait(100)
# Run grub-btrfs in order to regenerate GRUB entries
utils.execute_command(snapshot.GRUB_BTRFS_COMMAND, console=True, root=True)
# Refreshing GUI
self.refresh_gui()
# Enabling buttons
self.__enable_buttons()
# Displaying info
info_dialog = windows.GeneralInfoWindow(self, "GRUB menu has been regenerated.")
info_dialog.show()
================================================
FILE: buttermanager/buttermanager/exception/__init__.py
================================================
#Copyright 2018-2019 Eloy García Almadén
#
# This file is part of buttermanager.
#
# This program is free software: you can redistribute it and / or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
================================================
FILE: buttermanager/buttermanager/exception/exception.py
================================================
# -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Eloy García Almadén
#
# This file is part of buttermanager.
#
# This program is free software: you can redistribute it and / or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
"""This module gathers all the custom exceptions rised in buttermanager application.
"""
# Classes
class NoCommandFound(Exception):
"""Exception raised when a needed program is not installed in the system.
"""
pass
class BtrfsSnapshotDeletion(Exception):
"""Exception raised when a subvolume can't be deleted because it is not empty.
A subvolume is not empty when there are other subvolumes within it
"""
def __init__(self, *args):
if args:
self.message = args[0]
else:
self.message = None
def __str__(self):
print('calling str')
if self.message:
return 'MyCustomError, {0} '.format(self.message)
else:
return 'MyCustomError has been raised'
================================================
FILE: buttermanager/buttermanager/filesystem/__init__.py
================================================
# Copyright 2018-2019 Eloy García Almadén
#
# This file is part of buttermanager.
#
# This program is free software: you can redistribute it and / or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
================================================
FILE: buttermanager/buttermanager/filesystem/filesystem.py
================================================
# -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Eloy García Almadén
#
# This file is part of buttermanager.
#
# This program is free software: you can redistribute it and / or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
"""This module gathers all the operations related to BTRFS filesystems.
It provides also Filesystem class.
"""
from ..exception import exception
from ..window import windows
import sys
from ..util import utils
from PyQt5.QtCore import QThread, pyqtSignal
# Constants
DEVID = "devid"
LABEL = "Label"
UUID = "uuid:"
DEVICE_SIZE = "Device size:"
DEVICE_ALLOCATED = "Device allocated:"
DATA = "Data,"
METADATA = "Metadata,"
SYSTEM = "System,"
SIZE = "Size:"
USED = "Used:"
BTRFS_SHOW_COMMAND = "sudo -S btrfs filesystem show"
FINDMT_COMMAND = "sudo -S findmnt -nt btrfs"
BTRFS_USAGE_COMMAND = "sudo -S btrfs filesystem usage"
BTRFS_BALANCE_COMMAND = "sudo -S btrfs balance start"
BTRFS_BALANCE_DATA_USAGE_FILTER = "dusage"
BTRFS_BALANCE_METADATA_USAGE_FILTER = "musage"
# Classes
class Filesystem:
"""BTRFS Filesystem.
"""
# Constructor
def __init__(self, uuid):
self.__uuid = uuid
self.__devices = self.__get_devices()
self.__mounted_points = self.__get_mounted_points()
filesystem_info = self.__get_filesystem_info(self.mounted_points[0])
self.__total_size = filesystem_info['total_size']
self.__total_allocated = filesystem_info['total_allocated']
self.__data_size = filesystem_info['data_size']
self.__data_used = filesystem_info['data_used']
self.__data_percentage = filesystem_info['data_percentage']
self.__metadata_size = filesystem_info['metadata_size']
self.__metadata_used = filesystem_info['metadata_used']
self.__metadata_percentage = filesystem_info['metadata_percentage']
self.__system_size = filesystem_info['system_size']
self.__system_used = filesystem_info['system_used']
self.__system_percentage = filesystem_info['system_percentage']
# Private attributes
# UUID
@property
def uuid(self):
return self.__uuid
# Devices
@property
def devices(self):
return self.__devices
# Mounted points
@property
def mounted_points(self):
return self.__mounted_points
# Total size
@property
def total_size(self):
return self.__total_size
# Total allocated
@property
def total_allocated(self):
return self.__total_allocated
# Data size
@property
def data_size(self):
return self.__data_size
# Data used
@property
def data_used(self):
return self.__data_used
# Data percentage
@property
def data_percentage(self):
return self.__data_percentage
# Metadata size
@property
def metadata_size(self):
return self.__metadata_size
# Metadata used
@property
def metadata_used(self):
return self.__metadata_used
# Metadata percentage
@property
def metadata_percentage(self):
return self.__metadata_percentage
# System size
@property
def system_size(self):
return self.__system_size
# System used
@property
def system_used(self):
return self.__system_used
# System percentage
@property
def system_percentage(self):
return self.__system_percentage
# Methods
# Private methods
def __get_devices(self):
"""Retrieves all the devices which the BTRFS filesystem is composed.
Returns:
list (:obj:`list` of :obj:`str`): devices.
"""
try:
devices = []
commandline_output = utils.execute_command(BTRFS_SHOW_COMMAND, root=True)
filesystem_found = False
for line in commandline_output.split("\n"):
if UUID in line:
if filesystem_found:
break
else:
if self.uuid in line:
filesystem_found = True
continue
if filesystem_found:
# The loop is inside the chosen BTRFS filesystem
# It is necessary to find devid to retrieve all the filesystem paths
if DEVID in line:
path_init = line.find('/')
# The device path is appended to the list
devices.append(line[path_init:len(line)])
return devices
except exception.NoCommandFound as no_command_found_exception:
raise no_command_found_exception
def __get_mounted_device(self):
"""Retrieves the device tha contains the BTRFS filesystem and it is mounted.
Returns:
string: device path.
"""
try:
mounted_device = ''
commandline_output = utils.execute_command(FINDMT_COMMAND)
for device in self.devices:
if device in commandline_output:
mounted_device = device
break
return mounted_device
except exception.NoCommandFound as no_command_found_exception:
raise no_command_found_exception
def __get_mounted_points(self):
"""Retrieves all the mounted points of the BTRFS filesystem.
Returns:
list (:obj:`list` of :obj:`str`): mounted points.
"""
try:
mounted_points = []
device = self.__get_mounted_device()
command = "{command} {device}".format(command=FINDMT_COMMAND, device=device)
commandline_output = utils.execute_command(command)
for line in commandline_output.split("\n"):
if len(line) > 0:
mounted_points.append(line.split(" ")[0].strip())
return mounted_points
except exception.NoCommandFound as no_command_found_exception:
raise no_command_found_exception
def __get_filesystem_info(self, mounted_point):
"""Retrieves all the information of the BTRFS filesystem.
Returns:
dictionary (key=:obj:'string', value=:obj:'str' or obj:'int'): all the info. The keys of the dictionary
will be:
- total_size: Device size
- total_allocated: Device allocated
- data_size: Data size
- data_used: Data used
- data_percentage: Percentage of data used
- metadata_size: Metadata size
- metadata_used: Metadata used
- metadata_percentage: Percentage of metadata used
- system_size: System size
- system_used: System used
- system_percentage: Percentage of system used
"""
filesystem_info = {'total_size': '0', 'total_allocated': '0',
'data_size': '0', 'data_used': '0', 'data_percentage': 0,
'metadata_size': '0', 'metadata_used': '0', 'metadata_percentage': 0,
'system_size': '0', 'system_used': '0', 'system_percentage': 0}
command = "{command} {point}".format(command=BTRFS_USAGE_COMMAND, point=mounted_point)
commandline_output = utils.execute_command(command, root=True)
for line in commandline_output.split("\n"):
if DEVICE_SIZE in line:
filesystem_info['total_size'] = line.split(DEVICE_SIZE)[1].strip()
elif DEVICE_ALLOCATED in line:
filesystem_info['total_allocated'] = line.split(DEVICE_ALLOCATED)[1].strip()
elif DATA in line:
data_size = line.split(SIZE)[1].split(',')[0].strip()
filesystem_info['data_size'] = data_size
data_used = line.split(USED)[1].strip()
if '(' in data_used:
# New versions of btrfs-progs already include the percentage
data_used = data_used.split()[0].strip()
filesystem_info['data_used'] = data_used
filesystem_info['data_percentage'] = utils.get_percentage(filesystem_info['data_size'],
filesystem_info['data_used'])
elif METADATA in line:
metadata_size = line.split(SIZE)[1].split(',')[0].strip()
filesystem_info['metadata_size'] = metadata_size
metadata_used = line.split(USED)[1].strip()
if '(' in metadata_used:
# New versions of btrfs-progs already include the percentage
metadata_used = metadata_used.split()[0].strip()
filesystem_info['metadata_used'] = metadata_used
filesystem_info['metadata_percentage'] = utils.get_percentage(filesystem_info['metadata_size'],
filesystem_info['metadata_used'])
elif SYSTEM in line:
system_size = line.split(SIZE)[1].split(',')[0].strip()
filesystem_info['system_size'] = system_size
filesystem_info['system_used'] = line.split(USED)[1].strip()
filesystem_info['system_percentage'] = utils.get_percentage(filesystem_info['system_size'],
filesystem_info['system_used'])
return filesystem_info
# Public methods
def __str__(self):
"""Reimplementation of the str method inherited from object class.
Returns:
string: String representation of the Filesystem object.
"""
return "BTRFS Filesystem -> UUID: {0}; Devices: {1}; Mounted Points: {2}".format(self.uuid, self.devices,
self.mounted_points)
# Module's methods
def get_btrfs_filesystems(mounted=True):
"""Retrieves all the BTRFS filesystems.
Keyword arguments:
mounted (bool): Only mounted filesystems will be retrieved (default True).
Returns:
list (:obj:`list` of :obj:`str`): filesystems UUID.
"""
filesystems = []
command = BTRFS_SHOW_COMMAND
if mounted:
command += " --mounted"
commandline_output = utils.execute_command(command, root=True)
for line in commandline_output.split("\n"):
if UUID in line:
# The uuid is appended to the list
filesystems.append(line.split(UUID)[1].strip())
return filesystems
def balance_filesystem(filter, percentage, mounted_point):
"""Balances a specific filesystem.
Arguments:
filter (string): filter.
percentage (int): usage filter.
mounted_point: path to balance.
"""
# Logger
logger = utils.Logger(sys.modules['__main__'].__file__).get()
logger.info("Balancing {mounted_point} using filter {filter} and "
"percentage {percentage}".format(mounted_point=mounted_point,
filter=filter,
percentage=percentage))
command = "{command} -{filter}={percentage} {mounted_point}".format(command=BTRFS_BALANCE_COMMAND,
filter=filter,
percentage=percentage,
mounted_point=mounted_point)
logger.info("Command executed {command}".format(command=command))
commandline_output = utils.execute_command(command, root=True)
for line in commandline_output.split("\n"):
logger.info(line)
class BalanceManager(QThread):
"""Independent thread that will run the filesystem balancing process.
"""
# Attributes
# pyqtSignal that will be emitted when this class requires to display
# a single information window on the screen
show_one_window = pyqtSignal('bool')
# pyqtSignal that will be emitted when this class requires that main
# window refreshes current filesystem statistics
refresh_filesystem_statistics = pyqtSignal()
# Constructor
def __init__(self, data_percentage, metadata_percentage, mounted_point):
QThread.__init__(self)
self.__data_percentage = data_percentage
self.__metadata_percentage = metadata_percentage
self.__mounted_point = mounted_point
# Methods
def run(self):
# Main window will be hidden
self.on_show_one_window(True)
info_dialog = windows.InfoWindow(None, "Balancing '{mounted_point}' mounted point. \n"
"This window will be closed automatically \n"
"when the operation is done. \n \n"
"Please wait...".format(mounted_point=self.__mounted_point))
# Displaying info window
info_dialog.show()
# Balances the filesystem
self.__balance_filesystem()
# Hiding info window
info_dialog.hide()
# Main window will be shown again
self.on_show_one_window(False)
# Refreshing current filesystem statistics
self.on_refresh_filesystem_statistics()
def __balance_filesystem(self):
"""Wraps all the operations to balance the filesystem.
"""
# Balancing data
balance_filesystem(
BTRFS_BALANCE_DATA_USAGE_FILTER,
self.__data_percentage,
self.__mounted_point)
# Balancing metadata
balance_filesystem(
BTRFS_BALANCE_METADATA_USAGE_FILTER,
self.__metadata_percentage,
self.__mounted_point)
def on_show_one_window(self, one_window):
"""Emits a QT Signal to hide or show the rest of application windows.
Arguments:
one_window (boolean): Information window should be unique?.
"""
self.show_one_window.emit(one_window)
def on_refresh_filesystem_statistics(self):
"""Emits a QT Signal to refresh filesystem statistics in main window.
"""
self.refresh_filesystem_statistics.emit()
================================================
FILE: buttermanager/buttermanager/filesystem/snapshot.py
================================================
# -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Eloy García Almadén
#
# This file is part of buttermanager.
#
# This program is free software: you can redistribute it and / or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
"""This module gathers all the operations related to BTRFS snapshots.
It provides also Snapshot class.
"""
from ..exception import exception
from ..util import settings, utils
from ..window import windows
import glob
import os
import shutil
import sys
import subprocess
import time
from PyQt5.QtCore import QThread, pyqtSignal
# Constants
BTRFS_CREATE_SNAPSHOT_R_COMMAND = "sudo -S btrfs subvolume snapshot -r"
BTRFS_CREATE_SNAPSHOT_RW_COMMAND = "sudo -S btrfs subvolume snapshot"
BTRFS_DELETE_SNAPSHOT_COMMAND = "sudo -S btrfs subvolume delete"
BTRFS_FIND_NEW_COMMAND = "sudo -S btrfs subvolume find-new"
GRUB_BTRFS_COMMAND = "sudo -S grub-mkconfig -o /boot/grub/grub.cfg"
# Classes
class Subvolume:
"""BTRFS Snapshot.
"""
# Constructor
def __init__(self, subvolume_origin, subvolume_dest, snapshot_name, snapshots_to_keep):
""" Constructor.
Arguments:
subvolume_origin (str): Full path to the subvolume.
subvolume_dest (str): Full path to the subvolume where all of the subvolumes created from origin are going
to be stored.
snapshot_name (str): Prefix for all the subvolumes created from origin
snapshots_to_keep (str): Number of snapshots to keep for this subvolume
"""
# Logger
self.__logger = utils.Logger(self.__class__.__name__).get()
self.subvolume_origin = subvolume_origin if subvolume_origin[-1] == '/' else subvolume_origin + '/'
self.subvolume_dest = subvolume_dest if subvolume_dest[-1] == '/' else subvolume_dest + '/'
self.snapshot_name = snapshot_name
self.snapshots_to_keep = int(snapshots_to_keep)
self.__current_date = time.strftime('%Y%m%d')
# Methods
# Private methods
# Public methods
def create_snapshot(self):
"""Creates a snapshot.
"""
info_message = "Creating a read-only snapshot of {subvolume_origin} in {subvolume_dest}. " \
"Please wait...".format(subvolume_origin=self.subvolume_origin,
subvolume_dest=self.subvolume_dest)
self.__logger.info(info_message)
# Checking how many snapshots are with the same name
snapshot_full_name = "{snapshot_name}-{current_date}".format(snapshot_name=self.snapshot_name,
current_date=self.__current_date)
snapshots_with_same_name = [file for file in os.listdir(self.subvolume_dest) if snapshot_full_name in file]
# Adding number to the full name
snapshot_full_name = "{snapshot_full_name}-{number}".format(snapshot_full_name=snapshot_full_name,
number=len(snapshots_with_same_name))
# Checks if grub-btrfs integration is enabled
if settings.properties_manager.get_property("grub_btrfs"):
# Checks if /etc/fstab is in subvolume_origin
fstab_path = self.subvolume_origin + 'etc/fstab'
if os.path.isfile(fstab_path):
everything_ok = True
# /etc/fstab is in the subvolume, so it is necessary to
# modify it and add the snapshot's name
# grep -rnw '/etc/fstab' -e "/_active/rootvol"
# First, it is necessary to obtain the original subvolume
# for / which is mounted in the system (subvolume_origin_real)
subvolume_origin_real = None
command_string = """sudo btrfs subvolume show /"""
command = [command_string]
commandline_output = None
try:
commandline_output = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as called_process_error_exception:
self.__logger.error("Error retrieving the real and mounted subvolume for / . Reason: " +
str(called_process_error_exception.reason))
everything_ok = False
if everything_ok:
commandline_output = commandline_output.decode('utf-8')
for line_output in commandline_output.split("\n"):
# The original subvolume mounted for / will be always the first line
# of the output
subvolume_origin_real = line_output
break
# Creating the snapshot in rw mode
command = "{command} {subvolume_origin} {subvolume_dest}{snapshot_full_name}".format(
command=BTRFS_CREATE_SNAPSHOT_RW_COMMAND,
subvolume_origin=self.subvolume_origin,
subvolume_dest=self.subvolume_dest,
snapshot_full_name=snapshot_full_name
)
utils.execute_command(command, console=True, root=True)
# Obtaining the real subvolume for the new snapshot created
subvolume_snapshot_created_real = None
command_string = """sudo btrfs subvolume show {subvolume_dest}{snapshot_full_name}""".format(
subvolume_dest=self.subvolume_dest,
snapshot_full_name=snapshot_full_name
)
command = [command_string]
commandline_output = None
try:
commandline_output = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as called_process_error_exception:
self.__logger.error("Error retrieving the real subvolume for snapshot created. Reason: " +
str(called_process_error_exception.reason))
commandline_output = commandline_output.decode('utf-8')
for line_output in commandline_output.split("\n"):
# The original subvolume mounted for / will be always the first line
# of the output
subvolume_snapshot_created_real = line_output
break
# Getting the line in fstab where it is necessary to substitute the subvolume which is going to be
# mounted as root. It is necessary to discard all the lines with comments in fstab starting with '#'
command_string = """grep -rnw '{fstab_path}' -e '{subvolume_origin_real}'""".format(
fstab_path=fstab_path, subvolume_origin_real=subvolume_origin_real)
command = [command_string]
commandline_output = None
try:
commandline_output = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError:
pass
commandline_output = commandline_output.decode('utf-8')
# line will be the line where grep has matched subvolume_origin_real. All lines commented with '#'
# will be discarded
line = "0"
for line_output in commandline_output.split("\n"):
line_splitted = line_output.split(':')
# First element of the list will be the line where subvolume_origin_real has been matched by
# grep command. If the second element is '#', this line is commented in fstab and it won't be
# taken into account
if not line_splitted[1].startswith('#'):
line = line_splitted[0]
break
command_string = """sudo -S sed -i '{line}s|{subvolume_origin_real}|{subvolume_snapshot_created_real}|g' {subvolume_dest}{snapshot_full_name}/etc/fstab""".format(
line=line,
subvolume_origin_real=subvolume_origin_real,
subvolume_snapshot_created_real=subvolume_snapshot_created_real,
subvolume_dest=self.subvolume_dest,
snapshot_full_name=snapshot_full_name
)
command = [command_string]
try:
subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as called_process_error_exception:
self.__logger.error("Error trying to substitute the root's path in fstab with the "
"path of the new snapshot created. Reason: " +
str(called_process_error_exception.reason))
everything_ok = False
if everything_ok:
# subvolume_origin_real will be stored in configuration file in order to let the
# user to consolidate the system's rollback to any snapshot different from the main one
settings.properties_manager.set_property('path_to_consolidate_root_snapshot',
subvolume_origin_real)
# Run grub-btrfs in order to regenerate GRUB entries
self.__logger.info("Regenerating GRUB entries. Please wait...")
utils.execute_command(GRUB_BTRFS_COMMAND, console=True, root=True)
else:
# The original subvolume mounted for / couldn't be found
# Snapshot won't be created
self.__logger.error("The original subvolume mounted for / couldn't be found. "
"Snapshot won't be created: ")
pass
else:
command = "{command} {subvolume_origin} {subvolume_dest}{snapshot_full_name}".format(
command=BTRFS_CREATE_SNAPSHOT_R_COMMAND,
subvolume_origin=self.subvolume_origin,
subvolume_dest=self.subvolume_dest,
snapshot_full_name=snapshot_full_name
)
utils.execute_command(command, console=True, root=True)
else:
command = "{command} {subvolume_origin} {subvolume_dest}{snapshot_full_name}".format(
command=BTRFS_CREATE_SNAPSHOT_R_COMMAND,
subvolume_origin=self.subvolume_origin,
subvolume_dest=self.subvolume_dest,
snapshot_full_name=snapshot_full_name
)
utils.execute_command(command, console=True, root=True)
def delete_snapshots(self):
"""Deletes (or not if user has defined it) all the snapshots needed to keep the desired number set by the user.
It will delete the related logs if they exist
"""
info_message = "Deleting snapshot of {subvolume_origin} in {subvolume_dest}. " \
"Please wait...".format(subvolume_origin=self.subvolume_origin,
subvolume_dest=self.subvolume_dest)
self.__logger.info(info_message)
# If user has selected not delete any snapshot, this operation won't be done
if self.snapshots_to_keep > -1:
# Checking how many snapshots are with the same name ordered by date
snapshots = self.get_all_snapshots_with_the_same_name()
# Removing all the snapshots needed starting with the oldest one until reach
# the limit defined by the user
snapshots_to_delete = len(snapshots) - self.snapshots_to_keep
index = 0
while snapshots_to_delete > 0:
# Deletes the snapshot
command = "{command} {snapshot}".format(command=BTRFS_DELETE_SNAPSHOT_COMMAND,
snapshot=snapshots[index])
utils.execute_command(command, console=True, root=True)
info_message = "Snapshot {snapshot} deleted.\n".format(snapshot=snapshots[index])
self.__logger.info(info_message)
# Deletes the log if it exists
snapshot_name = snapshots[index].split("/")[-1]
log = "{snapshot_name}-{index}.txt".format(snapshot_name=snapshot_name.split("-")[-2],
index=snapshot_name.split("-")[-1])
log_path = os.path.join(settings.logs_path, log)
if os.path.exists(log_path):
try:
os.remove(log_path)
info_message = "Log {log} deleted.\n".format(log=log)
self.__logger.info(info_message)
except OSError as os_error_exception:
info_message = "Error deleting log {log}. Error {exception}\n".format(log=log,
exception=str(
os_error_exception))
self.__logger.info(info_message)
else:
info_message = "Log {log} doesn't exist. Skipping...deleted.\n".format(log=log)
self.__logger.info(info_message)
snapshots_to_delete -= 1
index += 1
# Checks if grub-btrfs integration is enabled
if settings.properties_manager.get_property("grub_btrfs"):
# Run grub-btrfs in order to regenerate GRUB entries
utils.execute_command(GRUB_BTRFS_COMMAND, console=True, root=True)
def delete_origin(self):
"""Deletes the original subvolume, i.e. the subvolume in subvolume_origin
"""
info_message = "Deleting subvolume from origin {subvolume_origin}. " \
"Please wait...".format(subvolume_origin=self.subvolume_origin)
self.__logger.info(info_message)
errors = False
# Deletes the subvolume
command_string = "{command} {snapshot}".format(command=BTRFS_DELETE_SNAPSHOT_COMMAND,
snapshot=self.subvolume_origin)
command = [command_string]
commandline_output = None
try:
# This is a special way for executing a command using Python:
# shell=True allows the execution of complex shell commands
# stdout=subprocess.PIPE captures the output generated by the command
# stderr=subprocess.STDOUT captures the errors generated by the command and redirects them to stdout
commandline_output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
commandline_output = commandline_output.stdout.decode('utf-8')
except subprocess.CalledProcessError:
pass
for line in commandline_output.split("\n"):
if 'Directory not empty' in line:
errors = True
break
if errors:
# Subvolume is not empty so it can't be deleted. Exception is thrown
raise exception.BtrfsSnapshotDeletion("Error: {snapshot} is not empty.\n".
format(snapshot=self.subvolume_origin))
else:
info_message = "Snapshot {snapshot} deleted.\n".format(snapshot=self.subvolume_origin)
self.__logger.info(info_message)
def get_all_snapshots_with_the_same_name(self):
"""Retrieves all the snapshots with name self.snapshot_name stored within self.subvolume_dest.
Returns:
list (:obj:`list` of :obj:`str`): paths to the snapshots.
"""
# Checking how many snapshots are with the same name ordered by date
snapshots = glob.glob("{snapshot_directory}/*".format(snapshot_directory=self.subvolume_dest))
snapshots.sort(key=os.path.getmtime)
snapshots_whit_same_name = [file for file in snapshots if self.snapshot_name in file]
return snapshots_whit_same_name
class RootSnapshotChecker:
"""Checks if the current snapshot used for root is the default or the user has booted the system from
an alternate snapshot.
"""
def __init__(self, parent_window):
# Attributes
self.__snapshot_to_clone_in_root_full_path = None
self.__root_subvolume = None
# Logger
self.__logger = utils.Logger(self.__class__.__name__).get()
self.__logger.info("Checking if the current snapshot used for root is the default. Please wait...")
self.__parent_window = parent_window
def check_root_snapshot(self):
"""Checks if the current snapshot used for root is the default or the user has booted the system from
an alternate snapshot.
Returns:
boolean: true if current snapshot used for root is the default or this paramenter has not been stored yet;
false otherwise.
"""
# First, it is necessary to check if path_to_consolidate_root_snapshot is defined
if settings.properties_manager.get_property("path_to_consolidate_root_snapshot") != 0:
# Obtaining the mounted subvolume for root partition
# mount | grep 'on / ' | grep -o 'subvol=/.*' | cut -f2- -d=
command_string = """mount | grep 'on / ' | grep -o 'subvol=/.*' | cut -f2- -d="""
command = [command_string]
mounted_snapshot_raw = None
try:
mounted_snapshot_raw = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError:
pass
if mounted_snapshot_raw:
# Removing the last two characters (a /n and a ")")
mounted_snapshot_raw = mounted_snapshot_raw[:-2]
# Converting bytes into string
mounted_snapshot_raw = mounted_snapshot_raw.decode("utf-8")
# Removing first / if path_to_consolidate_root_snapshot doesn't start with /
if not settings.properties_manager.get_property("path_to_consolidate_root_snapshot")\
.startswith("/"):
mounted_snapshot_raw = mounted_snapshot_raw[1:]
if mounted_snapshot_raw != settings.properties_manager. \
get_property("path_to_consolidate_root_snapshot"):
# If mounted snapshot is different from the supposed default root subvolume
# it means that user has booted the system using an alternate snapshot from GRUB.
# ButterManager will ask to consolidate the current snapshot as the default root
# subvolume
# Obtaining the snapshot mounted
mounted_snapshot_full_path = None
while mounted_snapshot_full_path is None:
for subvolume in settings.subvolumes:
snapshots = settings.subvolumes[subvolume].get_all_snapshots_with_the_same_name()
for snapshot in snapshots:
if mounted_snapshot_raw in snapshot:
mounted_snapshot_full_path = snapshot
break
if mounted_snapshot_full_path is not None:
break
self.__snapshot_to_clone_in_root_full_path = mounted_snapshot_full_path
self.__root_subvolume = settings.subvolumes[subvolume]
return False
else:
return True
else:
# Path to consolidate root snapshot hasn't been defined yet so this check is skipped
return True
def open_consolidate_snapshot_window(self):
"""Checks if the current snapshot used for root is the default or the user has booted the system from
an alternate snapshot.
Returns:
QDialog: The dialog window to consolidate the root snapshot.
"""
info_window = windows.ConsolidateSnapshotWindow(self.__parent_window,
self.__snapshot_to_clone_in_root_full_path,
self.__root_subvolume)
return info_window
class Differentiator(QThread):
"""Independent thread that will calculate the differences between a snapshot and its current state.
"""
# Constants
DIFFS_DIR = "diffs"
DIFF_COMMAND = "sudo -S diff -qr"
MODIFIED_FILE = "modified.txt"
OPERATION_FULL = "full_operation"
OPERATION_PARTIAL = "partial_operation"
# Attributes
# pyqtSignal that will be emitted when this class requires to display
# a single information window on the screen
show_one_window = pyqtSignal('bool')
# Constructor
def __init__(self, snapshot_full_path, operation_type):
QThread.__init__(self)
self.__snapshot_full_path = snapshot_full_path
self.__snapshot_name = snapshot_full_path.split("/")[-1]
self.__operation_type = operation_type
# Methods
def run(self):
# Main window will be hidden
self.on_show_one_window(True)
info_dialog = windows.InfoWindow(None, "Calculating differences in\n"
"'{snapshot_name}'.\n"
"Please, be patient. This process\n"
"can take several minutes. This\n"
"window will be closed when the\n"
"operation is done. Calculating..."
.format(snapshot_name=self.__snapshot_full_path))
# Displaying info window
info_dialog.show()
# Calculates differences
self.__calculate_differences()
# Hiding info window
info_dialog.hide()
# Main window will be shown again
self.on_show_one_window(False)
def __calculate_differences(self):
"""Wraps all the operations to calculate differences.
"""
# Gets the subvolume of the snapshot
subvolume = get_subvolume_by_snapshot_name(self.__snapshot_full_path)
if subvolume:
# Creating a directory to store all the diff files generated if it doesn't exist
# or removing and creating it if it existed
diffs_path = os.path.join(settings.application_path, self.DIFFS_DIR, self.__snapshot_name)
if os.path.exists(diffs_path):
shutil.rmtree(diffs_path)
os.makedirs(diffs_path)
# Getting the current subvolune name. This subvolume is the current one which is going to be
# used for the comparison. It is needed to remove all the empty strings within the list
subvolume_name_list = subvolume.subvolume_origin.split("/")
cleaned_subvolume_name_list = list(filter(None, subvolume_name_list))
if not cleaned_subvolume_name_list:
subvolume_name = "original"
else:
subvolume_name = cleaned_subvolume_name_list[-1]
if self.__operation_type == self.OPERATION_FULL:
# Full operation
# Creating 3 different files to store differences
files_only_in_dir1_path = os.path.join(diffs_path, "{file_name}.txt".format(file_name=subvolume_name))
files_only_in_dir2_path = os.path.join(diffs_path, "{file_name}.txt".format(
file_name=self.__snapshot_name))
files_in_both_modified_path = os.path.join(diffs_path, self.MODIFIED_FILE)
files_only_in_dir1 = open(files_only_in_dir1_path, "w+")
files_only_in_dir2 = open(files_only_in_dir2_path, "w+")
files_in_both_modified = open(files_in_both_modified_path, "w+")
files_in_both_modified.write("Files in both snapshots that have been modified" + "\r\n\r\n")
files_only_in_dir1.write("Files only in ${dir}".format(dir=subvolume.subvolume_origin) + "\r\n\r\n")
files_only_in_dir2.write("Files only in ${dir}".format(dir=self.__snapshot_full_path) + "\r\n\r\n")
# Calculating differences
command = "{command} {dir1} {dir2}".format(command=self.DIFF_COMMAND, dir1=subvolume.subvolume_origin,
dir2=self.__snapshot_full_path)
echo = subprocess.Popen(['echo', settings.user_password], stdout=subprocess.PIPE)
result = subprocess.Popen(command.split(), stdin=echo.stdout, stdout=subprocess.PIPE)
for line in iter(result.stdout.readline, b''):
line_decoded = line.decode('utf-8')
if " differ" in line_decoded:
file_modified_splitted = line_decoded.split(
"Files {path}".format(path=subvolume.subvolume_origin))
file_modified = "/" + file_modified_splitted[1].split(" ")[0]
files_in_both_modified.write(file_modified + "\r\n")
elif "Only in {dir1}".format(dir1=subvolume.subvolume_origin) in line_decoded:
file_only_in_dir1_splitted = line_decoded.split("Only in {path}".format(
path=subvolume.subvolume_origin))
file_only_in_dir1_splitted = file_only_in_dir1_splitted[1].split(":")
file_name = file_only_in_dir1_splitted[1].strip()
file_only_in_dir1 = "/" + file_only_in_dir1_splitted[0] + "/" + file_name
files_only_in_dir1.write(file_only_in_dir1 + "\r\n")
elif "Only in {dir2}".format(dir2=self.__snapshot_full_path) in line_decoded:
file_only_in_dir2_splitted = line_decoded.split("Only in {path}".format(
path=self.__snapshot_full_path))
file_only_in_dir2_splitted = file_only_in_dir2_splitted[1].split(":")
file_name = file_only_in_dir2_splitted[1].strip()
file_only_in_dir2 = file_only_in_dir2_splitted[0] + "/" + file_name
files_only_in_dir2.write(file_only_in_dir2 + "\r\n")
# Closing files
files_only_in_dir1.close()
files_only_in_dir2.close()
files_in_both_modified.close()
# Opening the file with the default application installed in the OS
# Warning, xdg-open is not working executing the code from PyCharm so
# it seems it doesn't work but it is really working
subprocess.call(['xdg-open', files_only_in_dir1_path])
subprocess.call(['xdg-open', files_only_in_dir2_path])
subprocess.call(['xdg-open', files_in_both_modified_path])
else:
# Partial operation
# Creating only one file to store differences
temp_sorted_modified_path = os.path.join(diffs_path, "tmp.txt")
temp_sorted_modified = open(temp_sorted_modified_path, "w+")
# Calculating differences
# sudo btrfs subvolume find-new /mnt/defvol/_snapshots/root-20201021-0/ '9999999'
# sudo btrfs subvolume find-new /mnt/defvol/_active/rootvol/ 463579 | sed '$d' | cut -f17- -d' ' |
# sort | uniq
# First, old transid is calculated. This ID will be used as a reference for the comparison
transid = "9999999"
command = "{command} {dir1} {transid}".format(command=BTRFS_FIND_NEW_COMMAND,
dir1=self.__snapshot_full_path, transid=transid)
echo = subprocess.Popen(['echo', settings.user_password], stdout=subprocess.PIPE)
result = subprocess.Popen(command.split(), stdin=echo.stdout, stdout=subprocess.PIPE)
for line in iter(result.stdout.readline, b''):
line_decoded = line.decode('utf-8')
line_splitted = line_decoded.split(" ")
transid = line_splitted[-1].strip()
# Then, the differences are obtained using transid
command = "{command} {dir1} {transid}".format(
command=BTRFS_FIND_NEW_COMMAND,
dir1=subvolume.subvolume_origin,
transid=transid)
echo = subprocess.Popen(['echo', settings.user_password], stdout=subprocess.PIPE)
result = subprocess.Popen(command.split(), stdin=echo.stdout, stdout=subprocess.PIPE)
temp_sorted_modified.write("- Files in both snapshots that have been modified" + "\r\n")
for line in iter(result.stdout.readline, b''):
line_decoded = line.decode('utf-8')
line_splitted = line_decoded.split(" ")
file_modified = "/" + line_splitted[-1].strip()
temp_sorted_modified.write(file_modified + "\r\n")
# Closing file
temp_sorted_modified.close()
# Sorting file
files_in_both_modified_path = os.path.join(diffs_path, self.MODIFIED_FILE)
files_in_both_modified = open(files_in_both_modified_path, "w+")
command = "sort {file}".format(file=temp_sorted_modified_path)
subprocess.Popen(command.split(), stdout=files_in_both_modified)
# Opening the file with the default application installed in the OS
# Warning, xdg-open is not working executing the code from PyCharm so
# it seems it doesn't work but it is really working
subprocess.call(['xdg-open', files_in_both_modified_path])
def on_show_one_window(self, one_window):
"""Emits a QT Signal to hide or show the rest of application windows.
Arguments:
one_window (boolean): Information window should be unique?.
"""
self.show_one_window.emit(one_window)
# Module's methods
def delete_specific_snapshot(snapshot_full_path):
"""Deletes a specific snapshot.
It will delete the specific log related if it exists too.
Arguments:
snapshot_full_path (string): path to the snapshot that user wants to delete.
"""
# Logger
logger = utils.Logger(sys.modules['__main__'].__file__).get()
info_message = "Deleting snapshot {snapshot}".format(snapshot=snapshot_full_path)
logger.info(info_message)
command = "{command} {snapshot}".format(command=BTRFS_DELETE_SNAPSHOT_COMMAND, snapshot=snapshot_full_path)
utils.execute_command(command, root=True)
info_message = "Snapshot {snapshot} deleted.\n".format(snapshot=snapshot_full_path)
logger.info(info_message)
# Checks if grub-btrfs integration is enabled
if settings.properties_manager.get_property("grub_btrfs"):
# Run grub-btrfs in order to regenerate GRUB entries
utils.execute_command(GRUB_BTRFS_COMMAND, console=True, root=True)
info_message = "Regenerating GRUB entries. Please wait..."
logger.info(info_message)
# Deletes the log if it exists
snapshot_name = snapshot_full_path.split("/")[-1]
log = "{snapshot_name}-{index}.txt".format(snapshot_name=snapshot_name.split("-")[-2],
index=snapshot_name.split("-")[-1])
log_path = os.path.join(settings.logs_path, log)
if os.path.exists(log_path):
try:
os.remove(log_path)
info_message = "Log {log} deleted.\n".format(log=log)
logger.info(info_message)
except OSError as os_error_exception:
info_message = "Error deleting log {log}. Error {exception}\n".format(log=log,
exception=str(os_error_exception))
logger.info(info_message)
else:
info_message = "Log {log} doesn't exist. Skipping...deleted.\n".format(log=log)
logger.info(info_message)
def get_subvolume_by_snapshot_name(snapshot_name):
"""Gets a subvolume object using the name of the snapshot.
Arguments:
snapshot_name (string): name of the snapshot.
Returns:
Subvolume: The subvolume which belongs the snapshot. None if subvolume was not found.
"""
# Logger
logger = utils.Logger(sys.modules['__main__'].__file__).get()
info_message = "Getting subvolume from snapshot's name {snapshot_name}".format(snapshot_name=snapshot_name)
logger.info(info_message)
subvolume_found = None
for subvolume_key in settings.subvolumes:
subvolume = settings.subvolumes[subvolume_key]
subvolume_snapshots_prefix = "{subvolume_dest}{subvolume_prefix}".format(
subvolume_dest=subvolume.subvolume_dest,
subvolume_prefix=subvolume.snapshot_name)
if snapshot_name.startswith(subvolume_snapshots_prefix):
info_message = "Found subvolume {subvolume}".format(subvolume=subvolume.subvolume_origin)
logger.info(info_message)
subvolume_found = subvolume
return subvolume_found
================================================
FILE: buttermanager/buttermanager/manager/__init__.py
================================================
================================================
FILE: buttermanager/buttermanager/manager/upgrader.py
================================================
# -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Eloy García Almadén
#
# This file is part of buttermanager.
#
# This program is free software: you can redistribute it and / or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
"""This module gathers all the managers built for the application.
"""
from .. import manager
from ..util import settings, utils
import sys
import urllib.request
from PyQt5.QtCore import QThread, pyqtSignal
from urllib.error import URLError
# Constants
ARCH_PACMAN_REFRESH_REPOSITORIES = "sudo -S pacman -Sy"
ARCH_PACMAN_CHECK_UPDATES = "sudo -S pacman -Qu"
ARCH_PACMAN_UPGRADE_COMMAND = "sudo -S pacman -Syu --noconfirm"
DEBIAN_APT_UPDATE_COMMAND = "sudo -S apt update"
DEBIAN_APT_UPGRADE_COMMAND = "sudo -S apt upgrade -y"
DEBIAN_APT_CHECK_UPDATES = "sudo -S apt list --upgradable"
ARCH_YAOURT_UPGRADE_COMMAND = "yaourt -Syua --noconfirm"
ARCH_YAOURT_COMMAND = "yaourt"
ARCH_YAY_UPGRADE_COMMAND = "yay -Syua --noconfirm"
ARCH_YAY_COMMAND = "yay"
ARCH_TRIZEN_UPGRADE_COMMAND = "trizen -Syua --noconfirm"
ARCH_TRIZEN_COMMAND = "trizen"
SNAP_COMMAND = "snap"
FLATPAK_COMMAND = "flatpak"
SNAP_UPGRADE_COMMAND = "sudo -S snap refresh"
FLATPAK_UPGRADE_COMMAND = "flatpak update -y"
SUSE_ZYPPER_UPGRADE_COMMAND = "sudo -S zypper -n update"
SUSE_ZYPPER_CHECK_UPDATES = "sudo -S zypper list-updates"
FEDORA_DNF_UPGRADE_COMMAND = "sudo -S dnf upgrade --refresh --assumeyes"
FEDORA_DNF_CHECK_UPDATES = "sudo -S dnf check-update"
class Upgrader(QThread):
"""Independent thread that will run the system upgrading process.
"""
# Attributes
# pyqtSignal that will be emitted when this class requires that main
# window disables all the buttons
disable_buttons = pyqtSignal()
# pyqtSignal that will be emitted when this class requires that main
# window enables all the buttons
enable_buttons = pyqtSignal()
# pyqtSignal that will be emitted when this class requires that main
# window refreshes GUI
refresh_gui = pyqtSignal()
# Constructor
def __init__(self, include_aur, include_snap, include_flatpak, snapshots):
QThread.__init__(self)
# Logger
self.__logger = utils.Logger(self.__class__.__name__).get()
# Include AUR packages upgrade
self.__include_aur = include_aur
# Include snap packages upgrade
self.__include_snap = include_snap
# Include flatpak packages upgrade
self.__include_flatpak = include_flatpak
# Create and delete snapshots
self.__snapshots = snapshots
# Methods
def run(self):
# Upgrading the system
self.__upgrade_system()
def __upgrade_system(self):
"""Wraps all the operations to upgrade the system.
"""
# Check for updates
if check_updates():
# There are system updates
# Starting the upgrading process. Disabling all the buttons.
self.on_disable_gui_buttons()
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
self.__logger.info("Starting system upgrading process.")
sys.stdout.write("Starting system upgrading process. Please wait...")
sys.stdout.write("\n")
# Creates all the snapshots needed before upgrading the system
# only if it is needed
if self.__snapshots:
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
sys.stdout.write("Creating snapshots and updating GRUB entries if it is necessary...")
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
for snapshot in settings.subvolumes:
try:
settings.subvolumes[snapshot].create_snapshot()
except Exception as exception:
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
sys.stdout.write("Error creating the snapshot " +
settings.subvolumes[snapshot].subvolume_origin)
sys.stdout.write("\n")
sys.stdout.write("Error: " + str(exception))
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
# Upgrades the system
upgrading_command = ""
if settings.user_os == utils.OS_ARCH:
upgrading_command = ARCH_PACMAN_UPGRADE_COMMAND
elif settings.user_os == utils.OS_DEBIAN:
# First, it is necessary to update the system
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
sys.stdout.write("Updating the system. Please wait...")
sys.stdout.write("\n")
utils.execute_command(DEBIAN_APT_UPDATE_COMMAND, console=True)
sys.stdout.write("\n")
upgrading_command = DEBIAN_APT_UPGRADE_COMMAND
elif settings.user_os == utils.OS_SUSE:
upgrading_command = SUSE_ZYPPER_UPGRADE_COMMAND
elif settings.user_os == utils.OS_FEDORA:
upgrading_command = FEDORA_DNF_UPGRADE_COMMAND
if upgrading_command:
try:
sys.stdout.write("Upgrading the system. Please wait...")
sys.stdout.write("\n")
utils.execute_command(upgrading_command, console=True)
except Exception as exception:
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
sys.stdout.write("Error upgrading the system")
sys.stdout.write("\n")
sys.stdout.write("Error: " + str(exception))
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
# Upgrades AUR if distro is ArchLinux or derivatives
if settings.user_os == utils.OS_ARCH:
if self.__include_aur:
try:
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
sys.stdout.write("Updating AUR packages if it is needed. Please wait...")
sys.stdout.write("\n")
if utils.exist_program(ARCH_YAY_COMMAND):
utils.execute_command(ARCH_YAY_UPGRADE_COMMAND, console=True)
elif utils.exist_program(ARCH_TRIZEN_COMMAND):
utils.execute_command(ARCH_TRIZEN_UPGRADE_COMMAND, console=True)
elif utils.exist_program(ARCH_YAOURT_COMMAND):
utils.execute_command(ARCH_YAOURT_UPGRADE_COMMAND, console=True)
except Exception as exception:
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
sys.stdout.write("Error upgrading AUR packages")
sys.stdout.write("\n")
sys.stdout.write("Error: " + str(exception))
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
# Upgrades snap packages
if self.__include_snap:
if utils.exist_program(SNAP_COMMAND):
try:
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
sys.stdout.write("Updating snap applications. Please wait...")
sys.stdout.write("\n")
utils.execute_command(SNAP_UPGRADE_COMMAND, console=True)
except Exception as exception:
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
sys.stdout.write("Error upgrading snap packages")
sys.stdout.write("\n")
sys.stdout.write("Error: " + str(exception))
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
# Upgrades flatpak packages
if self.__include_flatpak:
if utils.exist_program(FLATPAK_COMMAND):
try:
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
sys.stdout.write("Updating flatpak applications. Please wait...")
sys.stdout.write("\n")
utils.execute_command(FLATPAK_UPGRADE_COMMAND, console=True)
except Exception as exception:
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
sys.stdout.write("Error upgrading flatpak packages")
sys.stdout.write("\n")
sys.stdout.write("Error: " + str(exception))
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
# Removes all the snapshots not needed any more it is needed
if self.__snapshots:
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
sys.stdout.write("Removing old snapshots if it is needed and updating GRUB entries. Please wait...")
sys.stdout.write("\n")
for snapshot in settings.subvolumes:
try:
settings.subvolumes[snapshot].delete_snapshots()
except Exception as exception:
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
sys.stdout.write("Error deleting the snapshot " +
settings.subvolumes[snapshot].subvolume_origin)
sys.stdout.write("\n")
sys.stdout.write("Error: " + str(exception))
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
self.__logger.info("System upgrading process finished.")
sys.stdout.write("System upgrading process finished. You can close the terminal output now.")
sys.stdout.write("\n")
sys.stdout.write("\n")
# Refreshing GUI
self.on_refresh_gui()
else:
# There are not system updates
self.__logger.info("Your system is up to date.")
sys.stdout.write("Your system is up to date. You can close the terminal output now.")
sys.stdout.write("\n")
sys.stdout.write("\n")
# Finishing the upgrading process. Enabling all the buttons.
self.on_enable_gui_buttons()
def on_disable_gui_buttons(self):
"""Emits a QT Signal to disable all the buttons in main window.
"""
self.disable_buttons.emit()
def on_enable_gui_buttons(self):
"""Emits a QT Signal to enable all the buttons in main window.
"""
self.enable_buttons.emit()
def on_refresh_gui(self):
"""Emits a QT Signal to refresh filesystem statistics in main window.
"""
self.refresh_gui.emit()
class UpdatesChecker(QThread):
"""Independent thread that will run the system checking for updates.
"""
# Attributes
# pyqtSignal that will be emitted when this class requires that main
# window shows the updates window. The signal will emit an 'object' that,
# in hits case, will be a list of strings.
show_updates_window = pyqtSignal(object)
# Constructor
def __init__(self):
QThread.__init__(self)
# Logger
self.__logger = utils.Logger(self.__class__.__name__).get()
# Methods
def run(self):
# Checks for updates
self.__check_updates()
def __check_updates(self):
"""Wraps all the operations to check updates.
First, it will check Internet connectivity for doing the operation.
Emits a signal with the packages found. Otherwise, it won't emit this signal and
nothing will happen.
"""
# Checking Internet connection for 5 minutes
tries = 0
internet_available = self.__internet_available()
while (not internet_available) & (tries < 60):
self.__logger.info("Trying to reach Internet again. If there is no Internet connection in 5 minutes, this"
"operation will be canceled")
self.sleep(5)
internet_available = self.__internet_available()
tries += 1
# Checking updates only if Internet connection is available
if internet_available:
# Checking updates only if the user selected the option
if settings.check_at_startup == 1:
# Emmiting the signal only if there are updates
if manager.upgrader.check_updates():
commandline_output = []
if settings.user_os == utils.OS_ARCH:
refresh_repositories_command = manager.upgrader.ARCH_PACMAN_REFRESH_REPOSITORIES
utils.execute_command(refresh_repositories_command)
check_for_updates_command = manager.upgrader.ARCH_PACMAN_CHECK_UPDATES
commandline_output = utils.execute_command(check_for_updates_command)
elif settings.user_os == utils.OS_DEBIAN:
check_for_updates_command = manager.upgrader.DEBIAN_APT_CHECK_UPDATES
commandline_output = utils.execute_command(check_for_updates_command)
elif settings.user_os == utils.OS_SUSE:
check_for_updates_command = manager.upgrader.SUSE_ZYPPER_CHECK_UPDATES
commandline_output = utils.execute_command(check_for_updates_command)
elif settings.user_os == utils.OS_FEDORA:
check_for_updates_command = manager.upgrader.FEDORA_DNF_CHECK_UPDATES
commandline_output = utils.execute_command(check_for_updates_command)
# If there are updates, emits the signal thta will be captured in buttermanager.py
self.show_updates_window.emit(commandline_output)
else:
self.__logger.error("Timeout. Checking updates process has been cancelled because there is no Intenert"
" connection")
def __internet_available(self):
"""Checks Internet connection.
Returns:
boolean: true if there is Internet connection available; false otherwise.
"""
self.__logger.info("Checking Internet connection. Please wait...")
try:
urllib.request.urlopen('https://www.google.com', timeout=20)
self.__logger.info("Internet connection is available!")
return True
except urllib.error.URLError as error:
self.__logger.error("Internet connection is not available... Error: {error}".format(error=error))
return False
# Module's methods
def check_updates():
"""Checks for updates.
Returns:
boolean: true if there are updates; false otherwise.
"""
# Logger
logger = utils.Logger(sys.modules['__main__'].__file__).get()
logger.info("Checking for system updates.")
sys.stdout.write("Checking for system updates.")
sys.stdout.write("\n")
sys.stdout.write("--------")
sys.stdout.write("\n")
updates = False
if settings.user_os == utils.OS_ARCH:
refresh_repositories_command = ARCH_PACMAN_REFRESH_REPOSITORIES
utils.execute_command(refresh_repositories_command)
check_for_updates_command = ARCH_PACMAN_CHECK_UPDATES
commandline_output = utils.execute_command(check_for_updates_command)
for line in commandline_output.split("\n"):
if line:
updates = True
elif settings.user_os == utils.OS_DEBIAN:
check_for_updates_command = DEBIAN_APT_CHECK_UPDATES
commandline_output = utils.execute_command(check_for_updates_command)
lines = commandline_output.split("\n")
if len(lines) > 2:
updates = True
elif settings.user_os == utils.OS_SUSE:
check_for_updates_command = SUSE_ZYPPER_CHECK_UPDATES
commandline_output = utils.execute_command(check_for_updates_command)
lines = commandline_output.split("\n")
if len(lines) > 4:
updates = True
elif settings.user_os == utils.OS_FEDORA:
check_for_updates_command = FEDORA_DNF_CHECK_UPDATES
commandline_output = utils.execute_command(check_for_updates_command)
lines = commandline_output.split("\n")
if len(lines) > 2:
updates = True
else:
updates = True
return updates
================================================
FILE: buttermanager/buttermanager/ui/ConsolidateSnapshotWindow.ui
================================================
Dialog
0
0
424
300
ButterManager
-
10
10
10
10
-
Qt::AlignCenter
-
Qt::Horizontal
QDialogButtonBox::Cancel|QDialogButtonBox::Ok
================================================
FILE: buttermanager/buttermanager/ui/GeneralInfoWindow.ui
================================================
Dialog
0
0
420
285
ButterManager
-
10
10
10
10
-
Qt::AlignCenter
-
Qt::Horizontal
QDialogButtonBox::Close
================================================
FILE: buttermanager/buttermanager/ui/InfoWindow.ui
================================================
Dialog
0
0
320
240
ButterManager
-
10
10
10
10
-
Qt::LeftToRight
false
TextLabel
Qt::AlignCenter
================================================
FILE: buttermanager/buttermanager/ui/LogViewWindow.ui
================================================
LogViewWindow
0
0
767
442
ButterManager
-
10
10
10
10
-
Log details
-
================================================
FILE: buttermanager/buttermanager/ui/MainWindow.ui
================================================
MainWindow
0
0
756
746
ButterManager
-
0
Main
-
-
10
10
-
75
true
true
Filesystem Information
-
15
?
-
-
Qt::Vertical
20
40
-
Filesystem
-
-
10
0
10
10
-
Size:
-
30 GB
-
19.77 GB
-
Allocated:
-
Qt::Horizontal
40
20
-
10
10
-
75
true
true
Keep calm and clean a little bit your filesystem
-
75
true
true
No problem, you have enough free space in your filesystem
-
75
true
true
Low space svailable. Remove old snapshots, clean the filesystem and balance it
-
Qt::Vertical
20
40
-
10
10
10
10
-
-
75
true
true
Used space of total allocated
-
Qt::Vertical
QSizePolicy::Fixed
20
10
-
6
-
Data
-
Qt::Horizontal
QSizePolicy::Fixed
65
20
-
85
-
Qt::Horizontal
QSizePolicy::Fixed
40
20
-
-
Metadata
-
Qt::Horizontal
QSizePolicy::Fixed
40
20
-
50
-
Qt::Horizontal
QSizePolicy::Fixed
40
20
-
-
75
true
true
It is a perfect time to balance the filesystem. Click on Balance button to free some unused space
-
Balance the selected filesystem
Balance
-
Qt::Vertical
20
40
-
Qt::Horizontal
-
-
0
10
10
10
10
-
Fast actions
-
Qt::Vertical
QSizePolicy::Fixed
20
10
-
-
Upgrade the system creating a previous snapshot and removing old snapshots according to configuration
Upgrade System with snapshots
-
Upgrade the system without creating or deleting snapshots
Upgrade System without snapshots
-
Take a BTRFS snapshot
Take snapshots
-
Regenerates GRUB menu including entries for the current snapshots
Regenerate GRUB
-
-
-
50
false
false
false
false
true
Save the log in a txt file
Qt::LeftToRight
Save Log
-
Qt::Horizontal
40
20
-
50
false
false
false
false
true
Close the terminal below
Qt::LeftToRight
Close Terminal
Snapshots
-
-
-
QAbstractItemView::MultiSelection
QAbstractItemView::SelectItems
-
-
Qt::Vertical
20
40
-
Remove one or several BTRF snapshots
-
Take a BTRFS snapshot
false
-
Find differences between the selected snapshot and the current state
-
Open the selected snapshot in a file browser
-
Qt::Vertical
20
40
Logs
-
-
QAbstractItemView::SingleSelection
QAbstractItemView::SelectItems
-
-
Qt::Vertical
20
40
-
View the entire log
false
-
Remove the log selected
-
Qt::Vertical
20
40
Settings
-
-
10
10
-
75
true
true
Subvolumes
-
-
Add subvolume
-
Qt::Horizontal
40
20
-
Qt::Vertical
20
40
-
10
10
6
-
-
Qt::Horizontal
100
20
-
Remove the selected subvolume
-
Edit subvolume configuration
-
Apply changes
-
75
true
true
Existing subvolumes
-
10
10
-
false
-
8
true
(Prefix of the snapshot stored)
-
Don't remove any snapshot
-
8
true
(Path where the snapshot of the subvolume is stored)
-
8
true
(Snapshots to keep)
-
false
-
-
Qt::Vertical
20
40
-
10
10
-
75
true
true
Upgrade System
-
Check updates at startup
-
Save logs automatically
-
Include snap packages
-
Include Flatpak packages
-
Include AUR packages
-
Before checking this option, make sure you have GRUB installed. After marking it, the created snapshots of the subvolume mounted as root will be modified to include the appropriate path in the /etc/fstab file
Boot the system from GRUB using snapshots
-
Qt::Vertical
20
40
-
75
true
true
UI
-
-
Font size increment
-
-99
-
Qt::Horizontal
40
20
-
Qt::Vertical
20
40
Documentation
-
-
Qt::Vertical
20
40
-
Qt::LeftToRight
false
For additional documentation about setting up and using Buttermanager, please go to the Wiki of the project
Qt::AlignCenter
-
Qt::Vertical
QSizePolicy::Fixed
20
40
-
true
true
PointingHandCursor
false
border: none;
https://github.com/egara/buttermanager/wiki
-
Qt::Vertical
20
40
About
-
-
Qt::Vertical
20
40
-
Logo
Qt::AlignCenter
-
Qt::Vertical
20
40
-
75
true
ButterManager (A BTRFS Tool)
Qt::AlignCenter
-
75
true
v2.5.2
Qt::AlignCenter
-
Qt::Vertical
20
40
-
50
false
Eloy García Almadén
Qt::AlignCenter
-
50
false
eloy.garcia.pca@gmail.com
Qt::AlignCenter
-
true
true
PointingHandCursor
false
border: none;
https://github.com/egara/buttermanager
-
50
false
Jaime Álvarez Fernández (Icon)
Qt::AlignCenter
-
Qt::Vertical
20
40
================================================
FILE: buttermanager/buttermanager/ui/PasswordWindow.ui
================================================
PasswordWindow
0
0
330
195
ButterManager
-
Qt::Vertical
20
40
-
10
10
-
-
Qt::Horizontal
40
20
-
false
ArrowCursor
false
true
-
Qt::Horizontal
40
20
-
Qt::Vertical
20
40
-
Please. type your password:
-
QLineEdit::Password
-
Qt::Vertical
20
40
-
10
10
-
Qt::Horizontal
40
20
-
Ok
-
Cancel
================================================
FILE: buttermanager/buttermanager/ui/ProblemsFoundWindow.ui
================================================
SnapshotWindow
0
0
420
285
ButterManager
-
10
10
10
10
-
Qt::AlignCenter
-
-
Qt::Horizontal
40
20
-
OK
================================================
FILE: buttermanager/buttermanager/ui/SnapshotWindow.ui
================================================
SnapshotWindow
0
0
640
300
ButterManager
-
10
20
10
10
-
Take snapshots
-
Qt::Vertical
QSizePolicy::Fixed
20
10
-
All s&ubvolumes
-
One speci&fic subvolume
-
-
Qt::Horizontal
QSizePolicy::Fixed
40
20
-
-
Qt::Vertical
20
40
-
-
Qt::Horizontal
40
20
-
OK
-
Cancel
================================================
FILE: buttermanager/buttermanager/ui/SubvolumeWindow.ui
================================================
SubvolumeWindow
0
0
640
300
ButterManager
10
10
-
Qt::Vertical
QSizePolicy::Fixed
20
10
-
Add subvolume
-
Qt::Vertical
QSizePolicy::Fixed
20
10
-
-
-
Subvolume to manage
-
Select the subvolume you want to create the snapshot, f.i. / if you have a subvolume created for root
-
Selet the path where the snapshot will be stored. it is advisable to store the snapshot in a different subvolume
-
Path where the snapshot will be stored
-
-
-
Snapshot prefix
-
-
-
Don't remove any snapshot
-
Qt::Horizontal
40
20
-
Snapshot to keep
-
-
Qt::Vertical
20
40
-
-
Qt::Horizontal
40
20
-
OK
-
Cancel
================================================
FILE: buttermanager/buttermanager/ui/UpdatesWindow.ui
================================================
UpdatesWindow
0
0
767
442
ButterManager
10
10
-
10
10
10
10
-
-
Packages to update
-
Qt::Horizontal
40
20
-
Upgrade the system creating a previous snapshot and removing old snapshots according to configuration
Upgrade with snapshots
-
Upgrade the system without creating snapshots
Upgrade without snapshots
-
Cancel
-
================================================
FILE: buttermanager/buttermanager/util/__init__.py
================================================
#Copyright 2018-2019 Eloy García Almadén
#
# This file is part of buttermanager.
#
# This program is free software: you can redistribute it and / or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
================================================
FILE: buttermanager/buttermanager/util/settings.py
================================================
# -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Eloy García Almadén
#
# This file is part of buttermanager.
#
# This program is free software: you can redistribute it and / or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
"""This module gathers all the global attributes, methods and classes needed for application settings.
"""
from . import utils
from .. import filesystem
import os
import yaml
# Global module constants
CONF_FILE = "buttermanager.yaml"
VERSION = "2.5.2"
# Global module attributes
# Application version
application_version = ""
# Application name
application_name = ""
# Application work directory
application_path = ""
# Logs directory
logs_path = ""
# User's password
user_password = ""
# Linux distribution
user_os = ""
# Do user want to remove snapshots? 0=False 1=True
remove_snapshots = 1
# Do user want to upgrade snap packages? 0=False 1=True
snap_packages = 1
# Do user want to upgrade flatpak packages? 0=False 1=True
flatpak_packages = 1
# Do user want to upgrade packages from AUR? 0=False 1=True
aur_repository = 1
# Do user want to check for updates at startup? 0=False 1=True
check_at_startup = 1
# The path of the root snapshot that must be within /etc/fstab as / mount point
path_to_consolidate_root_snapshot = "0"
# Do user want to boot the system from GRUB using snapshots? 0=False 1=True
grub_btrfs = 0
# Do user want to save log automatically after upgrading system? 0=False 1=True
save_log = 1
# Subvolumes managed by the application
# It will be a dictionary:
# Key=origin path for the subvolume; Value=Subvolume object
subvolumes = {}
# Properties Manager
properties_manager = None
# Base fot size for all the UI elements (it is dynamically calculated during application start up)
base_font_size = 10
# Fot size increment defined by the user
font_size_increment = 0
# Location of the UI layouts directory
ui_dir = ""
# Location of the images directory
images_dir = ""
# Desktop environment
desktop_environment = ""
# Installation type
installation_type = ""
class PropertiesManager:
"""Manages the user properties for the application.
If no user settings are loaded yet, then the yaml file ~/.buttermanager/buttermanager.yaml will be
read and parsed in self.__user_settings dictionary.
The keys of the dictionary will be the properties name in the yaml file. The values will be the values
in the yaml file for every property.
"""
# Constructor
def __init__(self):
# Logger
self.__logger = utils.Logger(self.__class__.__name__).get()
# Setting global values related to the application
self.__conf_file_path = '{application_path}/{conf_file}'.format(application_path=application_path,
conf_file=CONF_FILE)
self.__user_settings = []
# Reading configuration file (buttermanager.yaml file within ~/.buttermanager directory)
if os.path.exists(self.__conf_file_path):
conf_file = open(self.__conf_file_path)
self.__user_settings = yaml.load(conf_file, Loader=yaml.FullLoader)
conf_file.close()
else:
self.__logger.info("Warning: There is no configuration file...")
def get_property(self, property):
"""Gets the value of a property.
Arguments:
property (string): Property to get its value.
Returns:
string: The value of the property. 0 if the property was not found.
"""
value = ""
if len(self.__user_settings) > 0:
value = self.__user_settings.get(property, 0)
return value
def set_property(self, property, value):
"""Sets the value of a property.
Arguments:
property (string): Property to set its value.
value (string): Value to be set.
"""
self.__logger.info("Setting property {property} with value {value}".format(property=property, value=value))
# Setting property in memory
self.__user_settings[property] = value
# Setting property in buttermanager.yaml file
self.__store_configuration()
def remove_property(self, property):
"""Removes s property from properties file.
Arguments:
property (string): Property to be removed.
"""
self.__logger.info("Removing property {property}".format(property=property))
self.__user_settings.pop(property)
# Storing buttermanager.yaml file
self.__store_configuration()
def set_subvolume(self, subvolume_selected, snapshot_where, snapshot_prefix, snapshots_to_keep):
"""Sets the value of a subvolume.
If snapshot_where = None and snapshot_prefix = None, then the subvolume
will be removed
Arguments:
subvolume_selected (string): Subvolume selected to be set with the new values.
snapshot_where (string): Path where the snapshot is going to be stored. None if the subvolume is removed
snapshot_prefix (string): Prefix used to store the snapshot of a specific subvolume. None if the subvolume
is removed
snapshots_to_keep (int): Number of the snapshots to keep in the filesystem for this subvolume
"""
self.__logger.info("Setting subvolume {subvolume} with new values: where {where}; prefix {prefix}; "
"snapshots to keep {snapshots_to_keep}".format(subvolume=subvolume_selected,
where=snapshot_where,
prefix=snapshot_prefix,
snapshots_to_keep=snapshots_to_keep))
if subvolume_selected in subvolumes:
if not snapshot_where and not snapshot_prefix:
# The subvolume has to be removed from memory
subvolumes.pop(subvolume_selected, 'None')
else:
# Modifying subvolume in memory
subvolumes[subvolume_selected].subvolume_dest = snapshot_where if snapshot_where[-1] == '/' else snapshot_where + '/'
subvolumes[subvolume_selected].snapshot_name = snapshot_prefix
subvolumes[subvolume_selected].snapshots_to_keep = snapshots_to_keep
else:
subvolumes[subvolume_selected] = filesystem.snapshot.Subvolume(subvolume_selected,
snapshot_where,
snapshot_prefix,
snapshots_to_keep)
subvolumes_orig = ""
subvolumes_dest = ""
subvolumes_prefix = ""
subvolumes_snapshost_to_keep = ""
index = 0
for subvolume in subvolumes:
subvolumes_orig += subvolumes[subvolume].subvolume_origin
subvolumes_dest += subvolumes[subvolume].subvolume_dest
subvolumes_prefix += subvolumes[subvolume].snapshot_name
subvolumes_snapshost_to_keep += str(subvolumes[subvolume].snapshots_to_keep)
if index + 1 < len(subvolumes):
subvolumes_orig += "|"
subvolumes_dest += "|"
subvolumes_prefix += "|"
subvolumes_snapshost_to_keep += "|"
index += 1
self.__user_settings['subvolumes_orig'] = subvolumes_orig
self.__user_settings['subvolumes_dest'] = subvolumes_dest
self.__user_settings['subvolumes_prefix'] = subvolumes_prefix
self.__user_settings['subvolumes_snapshots_to_keep'] = subvolumes_snapshost_to_keep
# Setting property in buttermanager.yaml file
self.__store_configuration()
def __store_configuration(self):
"""Stores configuration file.
"""
# Setting property in buttermanager.yaml file
if os.path.exists(self.__conf_file_path):
conf_file = open(self.__conf_file_path, 'w')
yaml.dump(self.__user_settings, conf_file)
conf_file.close()
else:
self.__logger.info("Warning: There is no configuration file...")
================================================
FILE: buttermanager/buttermanager/util/utils.py
================================================
# -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Eloy García Almadén
#
# This file is part of buttermanager.
#
# This program is free software: you can redistribute it and / or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
"""This module gathers all the utils and tools for buttermanager application.
"""
from . import settings
from ..exception import exception
from ..filesystem import snapshot
from ..window import windows
from PyQt5.QtWidgets import QFileDialog
from tkinter import Tk
from tkinter.filedialog import askdirectory
import logging
import logging.handlers
import os
import pathlib
import shutil
import subprocess
import sys
import urllib.request
import urllib.error
import yaml
# Constants
GB = "GiB" # Gigabytes
MB = "MiB" # Megabytes
KB = "KiB" # Kilobytes
B = "B" # Bytes
BYTE_SIZE = 1024
ARCH_PM = "pacman"
DEBIAN_PM = "apt"
SUSE_PM = "zypper"
FEDORA_PM = "dnf"
SNAP_PM = "snap"
OS_ARCH = "ARCH"
OS_DEBIAN = "DEBIAN"
OS_SUSE = "SUSE"
OS_FEDORA = "FEDORA"
VERSION_URL = "https://raw.githubusercontent.com/egara/buttermanager/master/version.txt"
class ConfigManager:
"""Manages the configuration.
"""
# Constants
APP_NAME = "buttermanager"
LOGS_DIR = "logs"
# Constructor
def __init__(self):
# Setting global values related to the application
settings.application_name = self.APP_NAME
application_directory = ".{name}".format(name=settings.application_name)
settings.application_path = os.path.join(str(pathlib.Path.home()), application_directory)
settings.logs_path = os.path.join(settings.application_path, self.LOGS_DIR)
# Creating application's directory if it is needed
if not os.path.exists(settings.application_path):
# Application directory does not exist. Creating directory...
os.makedirs(settings.application_path)
# Creating buttermanager.yaml file with default values
config_file_as_dictionary = '''
aur_repository: 0
check_at_startup: 0
snap_packages: 0
flatpak_packages: 0
save_log: 1
grub_btrfs: 0
path_to_consolidate_root_snapshot: 0
subvolumes_dest:
subvolumes_orig:
subvolumes_prefix:
subvolumes_snapshots_to_keep:
font_size_increment: 0
'''
config_file_dictionary = yaml.safe_load(config_file_as_dictionary)
conf_file_path = '{application_path}/{conf_file}'.format(application_path=settings.application_path,
conf_file=settings.CONF_FILE)
conf_file = open(conf_file_path, 'w')
yaml.dump(config_file_dictionary, conf_file)
conf_file.close()
# Sanitazing config file. All null values will be replaced by blank spaces
with open(conf_file_path, 'r') as file:
config_file_data = file.read()
config_file_data = config_file_data.replace('null', '')
with open(conf_file_path, 'w') as file:
file.write(config_file_data)
# Creating logs directory if it doesn't exist
if not os.path.exists(settings.logs_path):
os.makedirs(settings.logs_path)
# Logger
self.__logger = Logger(self.__class__.__name__).get()
def configure(self):
"""Configures the application.
"""
# Version
settings.application_version = settings.VERSION
# Checking OS
if exist_program(SUSE_PM):
settings.user_os = OS_SUSE
elif exist_program(DEBIAN_PM):
settings.user_os = OS_DEBIAN
elif exist_program(ARCH_PM):
settings.user_os = OS_ARCH
elif exist_program(FEDORA_PM):
settings.user_os = OS_FEDORA
self.__logger.info("Checking OS. {os} found".format(os=settings.user_os))
# Checking Desktop Environment
settings.desktop_environment = get_desktop_environment()
self.__logger.info("Checking Desktop Environment. {de} found".format(de=settings.desktop_environment))
# Checking Installation Type
if not os.path.exists("/opt/buttermanager/buttermanager"):
settings.installation_type = "native"
else:
settings.installation_type = "venv"
self.__logger.info("Installation type: {installation}".format(installation=settings.installation_type))
# Creating a properties manager to manage all the application properties
self.__logger.info("Creating PropertiesManager...")
settings.properties_manager = settings.PropertiesManager()
# Triggering migration process
self.migrate_properties()
# Retrieving configuration...
self.__logger.info("Retrieving user's configuration from buttermanager.yaml file and loading it in memory...")
# Do the user want to update snap packages during the upgrading process
settings.snap_packages = int(settings.properties_manager.get_property('snap_packages'))
# Do the user want to update flatpak packages during the upgrading process
settings.flatpak_packages = int(settings.properties_manager.get_property('flatpak_packages'))
# Do the user want to update AUR packages during the upgrading process
settings.aur_repository = int(settings.properties_manager.get_property('aur_repository'))
# Do the user want to check for updates at startup
settings.check_at_startup = int(settings.properties_manager.get_property('check_at_startup'))
# Do user want to boot the system from GRUB using snapshots
settings.grub_btrfs = int(settings.properties_manager.get_property('grub_btrfs'))
# The path of the root snapshot that must be within /etc/fstab as / mount point
# It will be 0 if this property is not defined yet or it is empty
settings.path_to_consolidate_root_snapshot = settings.properties_manager.\
get_property('path_to_consolidate_root_snapshot')
# Do the user want to save logs automatically
settings.save_log = int(settings.properties_manager.get_property('save_log'))
# Font size increment defined by the user
settings.font_size_increment = int(settings.properties_manager.get_property('font_size_increment'))
# Subvolumes to manage
subvolumes_list = get_subvolumes()
subvolumes = {}
for subvolume in subvolumes_list:
subvolumes[subvolume.subvolume_origin] = subvolume
settings.subvolumes = subvolumes
def migrate_properties(self):
"""Migrates buttermanager.yaml properties file from one version to another if necessary.
"""
# Checking if it is necessary to do some migrations to newer versions
# ##########################################
# BEGIN Version 2.3 or older -> 2.4 or newer
# ##########################################
# Number of snapshots per subvolume have been introduced in version 2.4
# Filling this property in case the user comes from version 2.3
snapshots_to_keep = int(settings.properties_manager.get_property('snapshots_to_keep'))
remove_snapshots = settings.properties_manager.get_property('remove_snapshots')
if snapshots_to_keep != 0:
# snapshots_to_keep property is still in buttermanager.yaml
self.__logger.info("Migrating from version 2.3 or older to version 2.4 or newer. Please wait...")
self.__logger.info("snapshots_to_keep property and remove_snapshots will be removed from buttermanager.yaml"
" configuration file and every subvolume defined will have their own properties")
subvolumes_orig_raw = settings.properties_manager.get_property('subvolumes_orig')
subvolumes_snapshots_to_keep_raw = ""
if subvolumes_orig_raw is not None and subvolumes_orig_raw != "":
subvolumes_orig = subvolumes_orig_raw.split("|")
for index, subvolume_orig in enumerate(subvolumes_orig):
if remove_snapshots == 0:
# From this moment, when snapshots_to_keep is -1, then the user havve decided not to
# delete any snapshot
snapshots_to_keep = -1
subvolumes_snapshots_to_keep_raw += str(snapshots_to_keep)
if index + 1 < len(subvolumes_orig):
subvolumes_snapshots_to_keep_raw += "|"
# Adding the new property
settings.properties_manager.set_property('subvolumes_snapshots_to_keep', subvolumes_snapshots_to_keep_raw)
# Removing old snapshots_to_keep and remove_snapshots properties
settings.properties_manager.remove_property('snapshots_to_keep')
settings.properties_manager.remove_property('remove_snapshots')
# ########################################
# END Version 2.3 or older -> 2.4 or newer
# ########################################
self.__logger.info("Migration process has finished successfully!")
class Logger(object):
"""Creates the logs of the application.
"""
def __init__(self, class_name):
name = os.path.join(settings.application_path, "buttermanager.log")
logger = logging.getLogger(class_name)
logger.setLevel(logging.DEBUG)
# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(name, maxBytes=1048576, backupCount=5)
formatter = logging.Formatter('%(asctime)s %(levelname)s:%(name)s. %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
self.__logger = logger
def get(self):
return self.__logger
class VersionChecker:
"""Checks if there is a newest version of ButterManager available.
"""
def __init__(self, parent_window):
# Logger
self.__logger = Logger(self.__class__.__name__).get()
self.__logger.info("Checking for a new version of ButterManager. Please wait...")
self.__version_url = VERSION_URL
self.__parent_window = parent_window
def check_version(self):
"""Checks if there is a newest version of ButterManager available.
"""
try:
# Retrieving the last version from GitHub
response = urllib.request.urlopen(self.__version_url)
last_version = response.read().decode(response.headers.get_content_charset()).strip()
except urllib.error.HTTPError as exception:
self.__logger.error("Error checking new versions of ButterManager. Reason: " + str(exception.reason))
except urllib.error.URLError as exception:
self.__logger.error("Error checking new versions of ButterManager. Reason: " + str(exception.reason))
else:
self.__logger.info("Last version is " + last_version + " and current version is " +
settings.application_version)
if last_version != settings.application_version:
if settings.user_os == OS_ARCH:
info_window = windows.GeneralInfoWindow(self.__parent_window, "New version " +
last_version + " is available. Update ButterManager "
"via AUR")
else:
info_window = windows.GeneralInfoWindow(self.__parent_window, "New version " +
last_version + " is available. Check the repository "
"\nof the project "
"(https://github.com/egara/buttermanager)\n "
"to get the latest code")
info_window.show()
# Module's methods
def execute_command(command, console=False, root=False):
"""Executes a shell command.
Arguments:
command (str): Command to be executed.
console (boolean): The command output needs to be redirected to the console.
root (boolean): The command is only accesible by root user
Returns:
str: Command line output encoded in UTF-8.
"""
# Checking if the program executed by the command is installed in the system
program = command.split()
single_command = program[0]
if "sudo" in program:
sudo_position = program.index("sudo")
single_command = program[sudo_position + 2]
if exist_program(single_command, root=root):
echo = subprocess.Popen(['echo', settings.user_password], stdout=subprocess.PIPE)
# run method receives a list, so it is necessary to convert command string into a list using split
result = subprocess.Popen(command.split(), stdin=echo.stdout, stdout=subprocess.PIPE)
if not console:
# The whole output will be returned
# result is Bytes type, so it is needed to decode Unicode string using UTF-8
commandline_output = result.stdout.read().decode('utf-8')
else:
# The output will be written in stdout in real time
# It is good for operations that need to display the output
# in the GUI terminal of the application in real time
for line in iter(result.stdout.readline, b''):
sys.stdout.write(line.decode('utf-8'))
commandline_output = None
return commandline_output
else:
# Logger
logger = Logger(sys.modules['__main__'].__file__).get()
logger.info(single_command + " program does not exist in the system")
raise exception.NoCommandFound()
def get_percentage(total, parcial):
"""Calculates the percentage between total amount and parcial amount.
Arguments:
total (str): Total amount. It should be specified the unit, f.i.: 30.00GiB
parcial (str): Parcial amount. It should be specified the unit, f.i.: 3.00GiB
Returns:
int: Percentage between total and parcial, f.i.: 10 (3.00GiB is 10% of 30.00GiB).
>>> get_percentage("30.00GiB", "3.00GiB")
10
"""
total_number_unit = get_number_unit(total)
parcial_number_unit = get_number_unit(parcial)
# All the operations will be done using Bytes unit as reference
total_number = convert_to_bytes(total_number_unit)
parcial_number = convert_to_bytes(parcial_number_unit)
percentage = int((parcial_number * 100) / total_number)
return percentage
def get_number_unit(number_unit_string):
"""Gets the number and the unit present in a specific string.
Arguments:
number_unit_string (str): String consisting of amount and unit, f.i.: 30.00GiB
Returns:
dictionary (key=:obj:'str', value=:obj:'str' or obj:'int'): all the info. The keys of the dictionary will be:
- total_size: Device size
- total_allocated: Device allocated
>>> get_number_unit("30.00GiB")
['number': 30.00, 'unit': 'GiB']
"""
number_unit = {'number': 0.0, 'unit': 'GiB'}
number_unit_string_list = number_unit_string.split('.')
number = float("{integer}.{decimal}".format(integer=number_unit_string_list[0].strip(),
decimal=number_unit_string_list[1][0:2]))
number_unit['number'] = number
number_unit['unit'] = number_unit_string_list[1][2:]
return number_unit
def convert_to_bytes(number_unit):
"""Converts a number into a bytes depending on its unit.
Arguments:
number_unit (dictionary): Number and unit to convert
Returns:
float: Number in bytes
>>> number_unit = {'number': 30.00, 'unit': 'GiB'}
>>> convert_to_bytes(number_unit)
32212254720
"""
factor = 1
if number_unit['unit'] == GB:
factor = factor * BYTE_SIZE * BYTE_SIZE * BYTE_SIZE
elif number_unit['unit'] == MB:
factor = factor * BYTE_SIZE * BYTE_SIZE
elif number_unit['unit'] == KB:
factor = factor * BYTE_SIZE
elif number_unit['unit'] == B:
factor = factor
return number_unit['number'] * factor
def exist_program(program, root=False):
"""Checks if a program is installed on the system.
Some problems have been detected in distributions like SUSE and OpenSUSE using
shutil.which function. There are some commands, like btrfs, that are only found
if sudo which is used instead of simply which from current user.
Because of that, root variable has been declared above. By default, root value
will be False, i.e. for those commands which are discoverable simply by using
which without sudo.
Arguments:
program (string): Program to check
root (boolean): The program to be checked is only usable by root user
Returns:
bool: True if the program is installed, False otherwise
>>> exist_program('ls')
True
"""
if root:
command = "sudo -S which " + program
# Checking if the program executed by the command is installed in the system
echo = subprocess.Popen(['echo', settings.user_password], stdout=subprocess.PIPE)
# run method receives a list, so it is necessary to convert command string into a list using split
result = subprocess.Popen(command.split(), stdin=echo.stdout, stdout=subprocess.PIPE)
# The whole output will be returned
# result is Bytes type, so it is needed to decode Unicode string using UTF-8
commandline_output = result.stdout.read().decode('utf-8')
exist = not commandline_output.startswith("which:")
return exist
else:
path = shutil.which(program)
return path is not None
def get_subvolumes():
"""Gets the subvolumes defined by the user in the properties file.
Returns:
list (:obj:`list` of :obj:`Subvolume`): subvolumes objects defined by the user.
"""
subvolumes = []
subvolumes_orig_raw = settings.properties_manager.get_property('subvolumes_orig')
subvolumes_dest_raw = settings.properties_manager.get_property('subvolumes_dest')
subvolumes_prefix_raw = settings.properties_manager.get_property('subvolumes_prefix')
subvolumes_snapshots_to_keep_raw = settings.properties_manager.get_property('subvolumes_snapshots_to_keep')
if subvolumes_orig_raw is not None and subvolumes_orig_raw != "":
subvolumes_orig = subvolumes_orig_raw.split("|")
subvolumes_dest = subvolumes_dest_raw.split("|")
subvolumes_prefix = subvolumes_prefix_raw.split("|")
subvolumes_snapshots_to_keep = subvolumes_snapshots_to_keep_raw.split("|")
for index, subvolume_orig in enumerate(subvolumes_orig):
subvolume = snapshot.Subvolume(subvolume_orig, subvolumes_dest[index], subvolumes_prefix[index],
subvolumes_snapshots_to_keep[index])
subvolumes.append(subvolume)
return subvolumes
def scale_fonts(ui_elements):
"""Scales all the UI elements fonts in order to fit on the window.
Arguments:
ui_elements (list): UI elements to change the font
"""
font_size = settings.base_font_size + int(settings.properties_manager.get_property('font_size_increment'))
# Changing the font for every UI element
for label in ui_elements:
font = label.font()
font.setPointSize(font_size)
label.setFont(font)
def get_desktop_environment():
"""Gets desktop environment.
"""
desktop_environment = 'generic'
if os.environ.get('KDE_FULL_SESSION') == 'true':
desktop_environment = 'kde'
elif os.environ.get('GNOME_DESKTOP_SESSION_ID'):
desktop_environment = 'gnome'
else:
try:
info = subprocess.getoutput('xprop -root _DT_SAVE_MODE')
if ' = "xfce4"' in info:
desktop_environment = 'xfce'
except (OSError, RuntimeError):
pass
return desktop_environment
def open_file_browser_directory(parent_window):
"""Opens a file browser to select a directory.
A bug has being detected in KDE Plasma native installatiom. When a native file browser is opened to
select a directory, then the application crashes. This doesn't happen in GNOME for example. So a
fallback has had to be implemented for this case, suing TKinter.
Arguments:
parent_window: Parent window
Returns:
str: Path of the directory selected
"""
# Creating a QFileDialog or Tkinter file browser to select the directory
# Only directories will be allowed
selected_path = ""
if settings.desktop_environment == 'kde' and settings.installation_type == 'native':
Tk().withdraw()
filename = askdirectory()
if filename:
selected_path = filename
else:
file_dialog = QFileDialog(parent_window)
file_dialog.setFileMode(QFileDialog.Directory)
file_dialog.setOption(QFileDialog.ShowDirsOnly, True)
file_dialog.setOption(QFileDialog.DontUseNativeDialog)
if file_dialog.exec_():
selected_path = file_dialog.selectedFiles()[0]
return selected_path
================================================
FILE: buttermanager/buttermanager/window/__init__.py
================================================
================================================
FILE: buttermanager/buttermanager/window/windows.py
================================================
# -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Eloy García Almadén
#
# This file is part of buttermanager.
#
# This program is free software: you can redistribute it and / or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
"""This module gathers all the additional windows for displaying information in the application.
"""
from ..exception import exception
from ..filesystem import snapshot
from ..util import settings, utils
import os
import subprocess
import sys
from PyQt5.QtWidgets import QDesktopWidget, QDialog, QMainWindow, QPushButton, QVBoxLayout, QLabel
from PyQt5 import uic, QtCore, QtTest
from PyQt5.QtCore import pyqtSignal, QSize
from PyQt5.QtGui import QIcon, QTextCursor
class InfoWindow(QDialog):
"""Window to display information.
"""
# Constructor
def __init__(self, parent, information):
QDialog.__init__(self, parent)
# Setting window flags, f.i. this window won't have a close button
self.setWindowFlags(
QtCore.Qt.Window |
QtCore.Qt.CustomizeWindowHint |
QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowMinimizeButtonHint |
QtCore.Qt.WindowStaysOnTopHint
)
self.parent = parent
# UI elements
self.__ui_elements = []
# Initializing the window
self.init_ui(information)
def init_ui(self, information):
"""Initializes the Graphic User Interface.
"""
# Loading User Interface
info_window_ui = os.path.join(settings.ui_dir, 'InfoWindow.ui')
uic.loadUi(info_window_ui, self)
# Setting the window icon
buttermanager_icon = os.path.join(settings.images_dir, 'buttermanager50.png')
self.setWindowIcon(QIcon(buttermanager_icon))
# Adjusting font scale
# UI elements
self.__ui_elements = [self.label_info]
utils.scale_fonts(self.__ui_elements)
# Tooltips
self.setStyleSheet(" QToolTip{font: " + str(settings.base_font_size) + "pt}")
# Setting size for the window
self.resize(320, 240)
# Centering the window
qt_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
qt_rectangle.moveCenter(center_point)
self.move(qt_rectangle.topLeft())
# Setting information
self.label_info.setText(information)
class GeneralInfoWindow(QDialog):
"""Window to display generic information.
"""
# Constructor
def __init__(self, parent, information):
QDialog.__init__(self, parent)
# Setting window flags, f.i. this window won't have a close button
self.setWindowFlags(
QtCore.Qt.Window |
QtCore.Qt.CustomizeWindowHint |
QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowStaysOnTopHint
)
self.parent = parent
# UI elements
self.__ui_elements = []
# Initializing the window
self.init_ui(information)
def init_ui(self, information):
"""Initializes the Graphic User Interface.
"""
# Loading User Interface
general_window_ui = os.path.join(settings.ui_dir, 'GeneralInfoWindow.ui')
uic.loadUi(general_window_ui, self)
# Setting the window icon
buttermanager_icon = os.path.join(settings.images_dir, 'buttermanager50.png')
self.setWindowIcon(QIcon(buttermanager_icon))
# Adjusting font scale
# UI elements
self.__ui_elements = [self.label_info, self.button_box]
utils.scale_fonts(self.__ui_elements)
# Tooltips
self.setStyleSheet(" QToolTip{font: " + str(settings.base_font_size) + "pt}")
# Setting size for the window
self.resize(420, 285)
# Centering the window
qt_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
qt_rectangle.moveCenter(center_point)
self.move(qt_rectangle.topLeft())
# Setting information
self.label_info.setText(information)
# Buttons
self.button_box.rejected.connect(self.reject)
class ConsolidateSnapshotWindow(QDialog):
"""Window to consolidate or not root snapshot.
This window will be displayed when user boots his/her system using a snapshot from GRUB different that
the default snapshot for root. The user will be asked if he/she wants to consolidate the current
snapshot as default snapshot for root.
"""
# Constructor
def __init__(self, parent, snapshot_to_clone_in_root_full_path, root_subvolume):
""" Constructor.
Arguments:
snapshot_to_clone_in_root_full_path (str): Full path of the snapshot booted and the one to use for
consolidating as default root subvolume.
root_subvolume (filesyste.snapshot.Subvolume): Subvolume representing system's root
"""
QDialog.__init__(self, parent)
# Setting window flags, f.i. this window won't have a close button
self.setWindowFlags(
QtCore.Qt.Window |
QtCore.Qt.CustomizeWindowHint |
QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowStaysOnTopHint
)
self.parent = parent
# UI elements
self.__ui_elements = []
# Logger
self.__logger = utils.Logger(self.__class__.__name__).get()
# Initializing private attributes
self.__snapshot_to_clone_in_root_full_path = snapshot_to_clone_in_root_full_path
self.__root_subvolume = root_subvolume
# Initializing the window
self.init_ui()
def init_ui(self):
"""Initializes the Graphic User Interface.
"""
# Loading User Interface
consolidate_snapshot_window_ui = os.path.join(settings.ui_dir, 'ConsolidateSnapshotWindow.ui')
uic.loadUi(consolidate_snapshot_window_ui, self)
# Setting the window icon
buttermanager_icon = os.path.join(settings.images_dir, 'buttermanager50.png')
self.setWindowIcon(QIcon(buttermanager_icon))
# Adjusting font scale
# UI elements
self.__ui_elements = [self.label_info, self.button_box]
utils.scale_fonts(self.__ui_elements)
# Tooltips
self.setStyleSheet(" QToolTip{font: " + str(settings.base_font_size) + "pt}")
# Setting size for the window
self.resize(420, 285)
# Centering the window
qt_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
qt_rectangle.moveCenter(center_point)
self.move(qt_rectangle.topLeft())
# Setting information
information = "You have booted into an alternative snapshot. \n " \
"Do you want to consolidate it as your default?"
self.label_info.setText(information)
# Buttons
self.button_box.accepted.connect(self.consolidate)
self.button_box.rejected.connect(self.cancel)
def consolidate(self):
"""Accepts root snapshot consolidation.
"""
self.__logger.info("Consolidating default root snapshot. The system has booted in " +
self.__snapshot_to_clone_in_root_full_path + " and it will be consolidated into " +
self.__root_subvolume.subvolume_origin[:-1])
# Removes root snapshot
try:
self.__root_subvolume.delete_origin()
# Creates a new snapshot for root
command = "{command} {subvolume_origin} {subvolume_dest}".format(
command=snapshot.BTRFS_CREATE_SNAPSHOT_RW_COMMAND,
subvolume_origin=self.__snapshot_to_clone_in_root_full_path,
subvolume_dest=self.__root_subvolume.subvolume_origin[:-1]
)
utils.execute_command(command, console=True, root=True)
# Replace /etc/fstab with the default snapshot
# Substitute the entry in fstab for root
# Obtaining the real subvolumes for changing paths in fstab
subvolume_origin = self.__snapshot_to_clone_in_root_full_path
command_string = """sudo btrfs subvolume show {subvolume_origin}""".format(
subvolume_origin=subvolume_origin
)
command = [command_string]
commandline_output = None
try:
commandline_output = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as called_process_error_exception:
self.__logger.error("Error retrieving the real subvolume. Reason: " +
str(called_process_error_exception.reason))
commandline_output = commandline_output.decode('utf-8')
for line_output in commandline_output.split("\n"):
# The original subvolume mounted for / will be always the first line
# of the output
subvolume_origin_real = line_output
break
subvolume_dest_real = self.__root_subvolume.subvolume_origin[:-1]
command_string = """sudo btrfs subvolume show {subvolume_dest_real}""".format(
subvolume_dest_real=subvolume_dest_real
)
command = [command_string]
commandline_output = None
try:
commandline_output = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as called_process_error_exception:
self.__logger.error("Error retrieving the real subvolume. Reason: " +
str(called_process_error_exception.reason))
commandline_output = commandline_output.decode('utf-8')
for line_output in commandline_output.split("\n"):
# The original subvolume mounted for / will be always the first line
# of the output
subvolume_dest_real = line_output
break
command_string = """sudo -S sed -i 's|{subvolume_origin_real}|{subvolume_dest_real}|g' {subvolume_dest}/etc/fstab""".format(
subvolume_origin_real=subvolume_origin_real,
subvolume_dest=self.__root_subvolume.subvolume_origin[:-1],
subvolume_dest_real=subvolume_dest_real
)
command = [command_string]
try:
subprocess.check_output(command, shell=True)
# Checks if grub-btrfs integration is enabled
if settings.properties_manager.get_property("grub_btrfs"):
# Run grub-btrfs in order to regenerate GRUB entries
utils.execute_command(snapshot.GRUB_BTRFS_COMMAND, console=True, root=True)
# The consolidation process was OK so this QDialong window is closed and returns integer 1
self.done(1)
except subprocess.CalledProcessError as subprocess_exception:
self.__logger.error("Error trying to substitute the root's path in fstab with the "
"path of the new snapshot created. Reason: " + str(subprocess_exception.reason))
# The consolidation process was KO so this QDialong window is closed and returns integer 2
self.done(2)
except exception.BtrfsSnapshotDeletion as btrfs_snapshot_exception:
self.__logger.error("Error removing root snapshot {root_snapshot} because it is not empty and there are "
"subvolumes within it "
.format(root_snapshot=self.__root_subvolume.subvolume_origin[:-1]))
# The consolidation process was KO so this QDialong window is closed and returns integer 3
self.done(3)
def cancel(self):
"""Rejects root snapshot consolidation.
"""
self.__logger.info("Rejecting default root snapshot")
self.done(4)
class SnapshotWindow(QMainWindow):
"""Window to select a subvolume to take a snapshot.
"""
# pyqtSignal that will be emitted when this class requires that main
# window refreshes GUI
refresh_gui = pyqtSignal()
# pyqtSignal that will be emitted when this class requires that main
# window enables all the buttons
enable_buttons = pyqtSignal()
# Constructor
def __init__(self, parent):
QMainWindow.__init__(self, parent)
self.parent = parent
# UI elements
self.__ui_elements = []
# Logger
self.__logger = utils.Logger(self.__class__.__name__).get()
# Initializing the window
self.init_ui()
def init_ui(self):
"""Initializes the Graphic User Interface.
"""
# Loading User Interface
snapshot_window_ui = os.path.join(settings.ui_dir, 'SnapshotWindow.ui')
uic.loadUi(snapshot_window_ui, self)
# Setting the window icon
buttermanager_icon = os.path.join(settings.images_dir, 'buttermanager50.png')
self.setWindowIcon(QIcon(buttermanager_icon))
# Adjusting font scale
# UI elements
self.__ui_elements = [self.radiobutton_all_subvolumes, self.radiobutton_one_subvolume,
self.label_take_snapshots, self.combobox_subvolumes, self.button_ok,
self.button_cancel]
utils.scale_fonts(self.__ui_elements)
# Tooltips
self.setStyleSheet(" QToolTip{font: " + str(settings.base_font_size) + "pt}")
# Setting size for the window
self.resize(500, 200)
# Centering the window
qt_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
qt_rectangle.moveCenter(center_point)
self.move(qt_rectangle.topLeft())
# Loading GUI components
self.enable_all_subvolumes()
# Retrieveing subvolumes
subvolumes = []
for subvolume in settings.subvolumes:
subvolumes.append(subvolume)
self.combobox_subvolumes.addItems(subvolumes)
# Button events
self.radiobutton_all_subvolumes.clicked.connect(self.enable_all_subvolumes)
self.radiobutton_one_subvolume.clicked.connect(self.enable_one_subvolume)
self.button_ok.clicked.connect(self.take_snapshot)
self.button_cancel.clicked.connect(self.cancel)
def enable_all_subvolumes(self):
"""Enables all subvolumes option.
"""
self.radiobutton_all_subvolumes.setEnabled(True)
self.radiobutton_all_subvolumes.setChecked(True)
self.radiobutton_one_subvolume.setEnabled(True)
self.radiobutton_one_subvolume.setChecked(False)
self.combobox_subvolumes.setEnabled(False)
def enable_one_subvolume(self):
"""Enables one subvolume option.
"""
self.radiobutton_all_subvolumes.setEnabled(True)
self.radiobutton_all_subvolumes.setChecked(False)
self.radiobutton_one_subvolume.setEnabled(True)
self.radiobutton_one_subvolume.setChecked(True)
self.combobox_subvolumes.setEnabled(True)
def take_snapshot(self):
"""Takes a snapshot of the selected subvolume.
"""
# Disabling window buttons
self.__disable_buttons()
# Waiting 10 msec in order to let self.__disable_buttons to take effect
QtTest.QTest.qWait(10)
if self.radiobutton_all_subvolumes.isChecked():
for subvolume in settings.subvolumes:
settings.subvolumes[subvolume].create_snapshot()
else:
subvolume_selected = self.combobox_subvolumes.currentText()
settings.subvolumes[subvolume_selected].create_snapshot()
# Refreshing GUI
self.on_refresh_gui()
# Enabling main window buttons
self.on_enable_buttons()
# Closes the window
self.cancel()
def cancel(self):
"""Closes the window.
"""
# Enabling main window buttons
self.on_enable_buttons()
# Refreshing GUI
self.on_refresh_gui()
self.close()
def on_refresh_gui(self):
"""Emits a QT Signal to refresh main window GUI.
"""
self.refresh_gui.emit()
def on_enable_buttons(self):
"""Emits a QT Signal for main window enabling all the buttons.
"""
self.enable_buttons.emit()
def on_disable_buttons(self):
"""Emits a QT Signal for main window disabling all the buttons.
"""
self.disable_buttons.emit()
def __disable_buttons(self):
"""Disables all the buttons of the GUI.
"""
self.combobox_subvolumes.setEnabled(False)
self.radiobutton_all_subvolumes.setEnabled(False)
self.radiobutton_one_subvolume.setEnabled(False)
self.button_ok.setEnabled(False)
self.button_cancel.setEnabled(False)
def __enable_buttons(self):
"""Enable all the buttons of the GUI.
"""
self.combobox_subvolumes.setEnabled(True)
self.radiobutton_all_subvolumes.setEnabled(True)
self.radiobutton_one_subvolume.setEnabled(True)
self.button_ok.setEnabled(True)
self.button_cancel.setEnabled(True)
class SubvolumeWindow(QMainWindow):
"""Window to add a new subvolume to be managed byt the application.
"""
# pyqtSignal that will be emitted when this class requires that main
# window refreshes GUI
refresh_gui = pyqtSignal()
# Constructor
def __init__(self, parent):
QMainWindow.__init__(self, parent)
self.parent = parent
# UI elements
self.__ui_elements = []
# Logger
self.__logger = utils.Logger(self.__class__.__name__).get()
# Initializing the window
self.init_ui()
def init_ui(self):
"""Initializes the Graphic User Interface.
"""
# Loading User Interface
subvolume_window_ui = os.path.join(settings.ui_dir, 'SubvolumeWindow.ui')
uic.loadUi(subvolume_window_ui, self)
# Setting the window icon
buttermanager_icon = os.path.join(settings.images_dir, 'buttermanager50.png')
self.setWindowIcon(QIcon(buttermanager_icon))
# Adjusting font scale
# UI elements
self.__ui_elements = [self.button_ok, self.button_cancel, self.button_add_subvolume_orig,
self.button_add_subvolume_dest, self.label_subvolume_origin, self.label_subvolume_dest,
self.label_subvolume_prefix, self.line_subvolume_origin, self.line_subvolume_dest,
self.line_snapshot_name, self.label_subvolume_snapshots_to_keep,
self.spinbox_snapshots_to_keep, self.checkbox_dont_remove_snapshots,
self.label_add_subvolume]
utils.scale_fonts(self.__ui_elements)
# Tooltips
self.setStyleSheet(" QToolTip{font: " + str(settings.base_font_size) + "pt}")
# Setting size for the window
self.resize(640, 300)
# Centering the window
qt_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
qt_rectangle.moveCenter(center_point)
self.move(qt_rectangle.topLeft())
# Loading icons
folder_icon = os.path.join(settings.images_dir, 'folder_16px_icon.png')
self.button_add_subvolume_orig.setIcon(QIcon(folder_icon))
self.button_add_subvolume_orig.setIconSize(QSize(16, 16))
self.button_add_subvolume_dest.setIcon(QIcon(folder_icon))
self.button_add_subvolume_dest.setIconSize(QSize(16, 16))
# Snapshots to keep by default will be 1
self.spinbox_snapshots_to_keep.setValue(1)
# Button events
self.button_add_subvolume_orig.clicked.connect(self.add_subvolume_orig)
self.button_add_subvolume_dest.clicked.connect(self.add_subvolume_dest)
self.checkbox_dont_remove_snapshots.clicked.connect(self.dont_remove_snapshots)
self.button_ok.clicked.connect(self.add_subvolume)
self.button_cancel.clicked.connect(self.cancel)
def add_subvolume_orig(self):
"""Adds the origin path for the subvolume to manage.
"""
selected_path = utils.open_file_browser_directory(self)
self.line_subvolume_origin.setText(selected_path)
def add_subvolume_dest(self):
"""Adds the destination where the snapshot of the subvolume will be stored.
"""
selected_path = utils.open_file_browser_directory(self)
self.line_subvolume_dest.setText(selected_path)
def add_subvolume(self):
"""Adds a new subvolume to be managed by the application.
"""
# All the fields must be filled
origin = self.line_subvolume_origin.text()
dest = self.line_subvolume_dest.text()
name = self.line_snapshot_name.text()
snapshots_to_keep = "-1"
if not self.checkbox_dont_remove_snapshots.isChecked():
snapshots_to_keep = str(self.spinbox_snapshots_to_keep.value())
if not origin or not dest or not name or not snapshots_to_keep:
info_dialog = GeneralInfoWindow(self, "Please, fill all the fields.")
info_dialog.show()
else:
# Adding a new subvolume
settings.properties_manager.set_subvolume(origin, dest, name, snapshots_to_keep)
# Refreshing GUI
self.on_refresh_gui()
# Closes the window
self.cancel()
def dont_remove_snapshots(self):
"""Actions when user checks don't remove snapshots.
"""
if self.checkbox_dont_remove_snapshots.isChecked():
self.spinbox_snapshots_to_keep.hide()
self.label_subvolume_snapshots_to_keep.hide()
else:
self.spinbox_snapshots_to_keep.show()
self.label_subvolume_snapshots_to_keep.show()
self.spinbox_snapshots_to_keep.setValue(1)
def cancel(self):
"""Closes the window.
"""
self.close()
def on_refresh_gui(self):
"""Emits a QT Signal to refresh main window GUI.
"""
self.refresh_gui.emit()
class UpdatesWindow(QMainWindow):
"""Window to check new updates and start the upgrading process.
"""
# pyqtSignal that will be emitted when this class requires to upgrade
# the system with snapshots
upgrade_system = pyqtSignal()
# pyqtSignal that will be emitted when this class requires to upgrade
# the system without snapshots
upgrade_system_without_snanpshots = pyqtSignal()
# Constructor
def __init__(self, parent, command_line_text):
""" Constructor.
Arguments:
command_line_text (list(:obj:`str`)): Packages obtained from command line to be updated. One per line.
"""
QMainWindow.__init__(self, parent)
self.parent = parent
# UI elements
self.__ui_elements = []
# Logger
self.__logger = utils.Logger(self.__class__.__name__).get()
# Command line text
self.__command_line_text = command_line_text
# Initializing the window
self.init_ui()
def init_ui(self):
"""Initializes the Graphic User Interface.
"""
# Loading User Interface
updates_window_ui = os.path.join(settings.ui_dir, 'UpdatesWindow.ui')
uic.loadUi(updates_window_ui, self)
# Setting the window icon
buttermanager_icon = os.path.join(settings.images_dir, 'buttermanager50.png')
self.setWindowIcon(QIcon(buttermanager_icon))
# Adjusting font scale
# UI elements
self.__ui_elements = [self.button_upgrade_system, self.button_cancel,
self.button_upgrade_system_without_snapshots, self.label_updates, self.text_edit_console]
utils.scale_fonts(self.__ui_elements)
# Tooltips
self.setStyleSheet(" QToolTip{font: " + str(settings.base_font_size) + "pt}")
# Setting size for the window
self.resize(767, 442)
# Centering the window
qt_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
qt_rectangle.moveCenter(center_point)
self.move(qt_rectangle.topLeft())
# Displaying packages to be updated
for line in self.__command_line_text.split("\n"):
self.text_edit_console.moveCursor(QTextCursor.End)
self.text_edit_console.insertHtml(line + '
')
self.text_edit_console.moveCursor(QTextCursor.End)
# Hiding upgrade button with snapshots if there is no subvolume defined
if len(settings.subvolumes) == 0:
self.button_upgrade_system.hide()
# Button events
self.button_upgrade_system.clicked.connect(self.full_system_upgrade)
self.button_upgrade_system_without_snapshots.clicked.connect(self.full_system_upgrade_without_snapshots)
self.button_cancel.clicked.connect(self.cancel)
def full_system_upgrade(self):
"""Upgrades the system doing snapshots.
"""
# The main window will upgrade the system
self.upgrade_system.emit()
# Closes the window
self.cancel()
def full_system_upgrade_without_snapshots(self):
"""Upgrades the system without doing snapshots.
"""
# The main window will upgrade the system
self.upgrade_system_without_snanpshots.emit()
# Closes the window
self.cancel()
def cancel(self):
"""Closes the window.
"""
self.close()
class ProblemsFoundWindow(QMainWindow):
"""Window to display problems found.
Those problems will cause the application exits.
"""
# Constructor
def __init__(self, parent, information):
QMainWindow.__init__(self, parent)
self.setWindowFlags(
QtCore.Qt.Window |
QtCore.Qt.CustomizeWindowHint |
QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowStaysOnTopHint
)
self.parent = parent
# UI elements
self.__ui_elements = []
# Initializing the window
self.init_ui(information)
def init_ui(self, information):
"""Initializes the Graphic User Interface.
"""
# Loading User Interface
problems_found_window_ui = os.path.join(settings.ui_dir, 'ProblemsFoundWindow.ui')
uic.loadUi(problems_found_window_ui, self)
# Setting the window icon
buttermanager_icon = os.path.join(settings.images_dir, 'buttermanager50.png')
self.setWindowIcon(QIcon(buttermanager_icon))
# Adjusting font scale
# UI elements
self.__ui_elements = [self.label_info, self.button_ok]
utils.scale_fonts(self.__ui_elements)
# Tooltips
self.setStyleSheet(" QToolTip{font: " + str(settings.base_font_size) + "pt}")
# Setting size for the window
self.resize(420, 285)
# Centering the window
qt_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
qt_rectangle.moveCenter(center_point)
self.move(qt_rectangle.topLeft())
# Setting information
self.label_info.setText(information)
# Button events
self.button_ok.clicked.connect(self.exit)
def exit(self):
"""Exits the application.
"""
self.close()
sys.exit()
class LogViewWindow(QMainWindow):
"""Window display a log.
"""
# Constructor
def __init__(self, parent, log_path):
""" Constructor.
Arguments:
log_path (string): Path of the log that the user wants to see.
"""
QMainWindow.__init__(self, parent)
self.parent = parent
# UI elements
self.__ui_elements = []
# Logger
self.__logger = utils.Logger(self.__class__.__name__).get()
# Command line text
self.__log_path = log_path
# Initializing the window
self.init_ui()
def init_ui(self):
"""Initializes the Graphic User Interface.
"""
# Loading User Interface
log_view_window_ui = os.path.join(settings.ui_dir, 'LogViewWindow.ui')
uic.loadUi(log_view_window_ui, self)
# Setting the window icon
buttermanager_icon = os.path.join(settings.images_dir, 'buttermanager50.png')
self.setWindowIcon(QIcon(buttermanager_icon))
# Adjusting font scale
# UI elements
self.__ui_elements = [self.label_log, self.text_log]
utils.scale_fonts(self.__ui_elements)
# Tooltips
self.setStyleSheet(" QToolTip{font: " + str(settings.base_font_size) + "pt}")
# Setting size for the window
self.resize(767, 442)
# Centering the window
qt_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
qt_rectangle.moveCenter(center_point)
self.move(qt_rectangle.topLeft())
# Displaying the log
log_file = open(self.__log_path, 'r')
for line in log_file:
self.text_log.moveCursor(QTextCursor.End)
self.text_log.insertHtml(line + '
')
self.text_log.moveCursor(QTextCursor.End)
class DiffWindow(QDialog):
"""Window to select the level of details when obtaining differences between two subvolumes.
This window will be displayed when user wants to get the differences between two different subvolumes.
If user choose Yes, ButterManager will perform a full process to obtain diferences, so it will take a lot
of time to complete but it will obtain files with differences in bot subolumes and files which are present
only in one subvolume or the other. If user chooses No, ButterManager will only obtain those files which
have been modified but this operation will be done quickly.
"""
# Constructor
def __init__(self):
""" Constructor.
"""
QDialog.__init__(self)
self.setWindowFlags(
QtCore.Qt.Window |
QtCore.Qt.CustomizeWindowHint |
QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowStaysOnTopHint
)
# UI elements
self.__ui_elements = []
# Logger
self.__logger = utils.Logger(self.__class__.__name__).get()
self.__label_info = QLabel()
self.__label_info.setAlignment(QtCore.Qt.AlignCenter)
self.__button_partial = QPushButton('Partial diff')
self.__button_full = QPushButton('Full diff')
layout = QVBoxLayout()
layout.addWidget(self.__label_info)
layout.addWidget(self.__button_partial)
layout.addWidget(self.__button_full)
self.setLayout(layout)
# Initializing the window
self.init_ui()
def init_ui(self):
"""Initializes the Graphic User Interface.
"""
# Setting the window icon
buttermanager_icon = os.path.join(settings.images_dir, 'buttermanager50.png')
self.setWindowIcon(QIcon(buttermanager_icon))
self.setWindowTitle('Calculating differences')
# Adjusting font scale
# UI elements
self.__ui_elements = [self.__label_info, self.__button_partial, self.__button_full]
utils.scale_fonts(self.__ui_elements)
# Tooltips
self.setStyleSheet(" QToolTip{font: " + str(settings.base_font_size) + "pt}")
# Setting maximum and minimum size for the main window
self.setMinimumHeight(285)
self.setMinimumWidth(420)
self.setMaximumHeight(285)
self.setMaximumWidth(420)
# Centering the window
qt_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
qt_rectangle.moveCenter(center_point)
self.move(qt_rectangle.topLeft())
# Setting information
information = "Partial diff will calculate only modified files. \n " \
"This operation will be done quickly. Full diff \n " \
"will take long but it will obtain modified files \n " \
"and those which are only in one of the subvolumes."
self.__label_info.setText(information)
# Buttons
self.__button_full.clicked.connect(self.full_operation)
self.__button_partial.clicked.connect(self.partial_operation)
def full_operation(self):
"""User selects Full diff, so a full diff operation will be done.
"""
self.__logger.info("Starting the process to obtain full differences between subvolumes. Please wait...")
self.done(1)
def partial_operation(self):
"""User selects Partial diff, so a partial diff operation will be done.
"""
self.__logger.info("Starting the process to obtain partial differences between subvolumes. Please wait...")
self.done(2)
================================================
FILE: buttermanager/main.py
================================================
from buttermanager.buttermanager import PasswordWindow
from PyQt5.QtWidgets import QApplication
import sys
def main():
"""Main wrapper for starting the program
"""
# Creating application instance
application = QApplication(sys.argv)
# Creating main window instance
PasswordWindow(None)
# Launching the application
application.exec_()
if __name__ == "__main__":
main()
================================================
FILE: doc/README.md
================================================
# Documentation
This is the documentation related to [Buttermanager](https://github.com/egara/buttermanager) GUI tool for easily management of BTRFS snapshots and system upgrades.
## BTRFS filesystem initial layout
For the purpose of this documentation, we are going to suppose that we have installed [Manjaro]() using a manual partitioning with this requirements:
- Only one disk: **sda**
- Only one partition in the disk: **sda1**
- *sda1* has been formatted using **btrfs**
- The mount point selected for this partition is **/**
After the installation of the operating system, the subvolumes automatically created are two (**@** and **@home**) as you can see in the screenshot below:
So the layout is something like this
```
Main Volume (ID 5)
|
|--- @ (Subvolume ID 257)
|
|--- @home (Subvolume ID 258)
```
**Important Note: If you are installing Arch from scratch or want to reshape your default BTRFS layout, you can check out this tips [https://github.com/egara/arch-btrfs-installation](https://github.com/egara/arch-btrfs-installation).**
## Mounting main volume (ID 5)
In order to manage in a proper way all the snapshots created and make things easier if you want to rollback your system to a previous snapshot, we are going to mount the main BTRFS volume in **/mnt/defvol** directory. For this, you first has to create this directory.
Include this new mounting point in **/etc/fstab** just to automount it when the system boots. Please, change the UID to the appropriate one or use labels if it is your case.
Once **fstab** is changed you can type
sudo mount -a
and go to **/mnt/defvol**. You should see something like this:
Create a new subvolume called **snapshots** at top level (as you can see above) using the command:
sudo btrfs subvolume create snapshots
The final layout will be:
```
Main Volume (ID 5)
|
|--- @ (Subvolume ID 257)
|
|--- @home (Subvolume ID 258)
|
|--- snapshots (Subvolume ID 271)
```
## Setting up Buttermanager
Yes, finally we are going to configure **Buttermanager**!. The first time you open the application, you will be warned because no subvolumes to create snapshots has been defined yet. You could use the application, but if you upgrade your system, **Buttermanager** won't create any snapshot.
Go to **Settings** tab and click on **Add subvolume** button.
Now, using the layout defined in this example, we are going to configure two subvolumes to create snapshots of **root** and **home**.
### Subvolume 1 (root)
If you want **Buttermanager** creates a snapshot of your **root** partition everytime it upgrades the system, then you should fill the **Add a subvolume** window like this:
- *Subvolume to manage*: **/mnt/defvol/@**
- *Path where the snapshot will be stored*: **/mnt/defvol/snapshots**
- *Snapshot prefix*: **root**
>Please, use always different prefixes for different subvolumes (prefixes shouldn't even include words contained in other prefixes, i.e. in this example, you should never include root word in other prefixes).
This way, everytime **Buttermanager** upgrades the system, it will automatically create a snapshot of the **root** mounted subvolume called **root-[date]-[number]** within **/mnt/defvol/snapshots/** directory. This snapshot will be **read only** by default.
### Subvolume 2 (/home)
If you want **Buttermanager** creates a snapshot of your **home** partition everytime it upgrades the system, then you should fill the **Add a subvolume** window like this:
- *Subvolume to manage*: **/mnt/defvol/@home**
- *Path where the snapshot will be stored*: **/mnt/defvol/snapshots**
- *Snapshot prefix*: **home**
This way, everytime **Buttermanager** upgrades the system, it will automatically create a snapshot of the **home** mounted subvolume called **home-[date]-[number]** within **/mnt/defvol/snapshots/** directory. This snapshot will be **read only** by default.
## Integrating Buttermanager with GRUB
Since version **1.9**, Buttermanager can be integrated with GRUB using the awesome package **grub-btrfs**. If you have installed Buttermanager via your package manager, this depency is installed automatically, if don't, please install it manually. When the integration is enabled, all the root snapshots created since then, will be bootable directly from the GRUB menu.
To enable this feature, go to **Settings** and check **Boot the system from GRUB using snapshots**.
When this option is checked, **all the snapshots created will have read and write permissions** and the **/etc/fstab** file within the snapshot created will be modified in order to let GRUB to boot from it.
### Consolidating the snapshot booted
Buttermanager cannot properly work from a snapshot selected from the GRUB menu. Because of this, when you run Buttermanager again in this situation, you will see a message like this.
If you want to consolidate the current state of your filesystem (the snapshot in which you have booted) reverting all the changes done since then, then click button **Ok**.
If you don't want to consolidate this snapshot and you want to boot your system using the default root, then restart your computer and don't select any snapshot.
>After consolidating the current snapshot and rebooting the system, run Buttermanager again and click on button **Regenerate GRUB** in order to rebuild GRUB menu with all the snapshots present in the filesystem.
### Common problems
The integration of Buttermanager with GRUB can only be done if there is not any subvolume defined inside the root file system. As an example, take the case of the automatic installation using BTRFS in some distros.
By default, some distros (or more precisely systemd) create this BTRFS layout when the system is installed for the first time:
```
Main Volume (ID 5)
|
|--- @
| |
| |--- @/var/lib/portables
| |--- @/var/lib/machines
|
|--- @home
```
You can see this layout in EndevourOS (MATE online installation) for example:
In this case, if you boot the system using an alternate snapshot, run Buttermanager and try to consolidate this snapshot as the default, you will receive this message:
If you want to fix this problem, first execute these two commands in a terminal (please, adjust this command to your needs. In this case, main volume with ID 5 is mounted on /defvol):
Those subvolumes (**@/var/lib/portables** and **@/var/lib/machines**) will be probably empty as you can see in the picture above. If this is the case, you can remove them without any problem. To do this, take a look at the commands you have to type in the picture below please, adjust this commands to your needs. In this case, main volume with ID 5 is mounted on /defvol):
================================================
FILE: install/native_install.sh
================================================
#!/bin/bash
# Script for installing ButterManager
# -----------------------------------
#
# @author: Eloy García Almadén
# @email: eloy.garcia.pca@gmail.com
# -------------------------------------
# Displaying requirements
echo "You are about to install ButterManager natively."
echo ""
echo "These packages MUST be installed before executing this script: 'python-setuptools' and 'tkinter'. The name of these packages can be different depending on the distro you are using. Example: On Arch -> 'python-setuptools' and 'tk'. On Fedora 'python3-setuptools' and 'python3-tkinter'. In addition, if you are on Ubuntu or derivative, 'libxcb-xinerama0' needs to be installed too."
echo ""
echo "Do you want to proceed with the installation? [y/n]"
read installButterManager
if [[ "$installButterManager" == "y" ]]; then
# Installing ButterManager
# Variables
python_bin="python"
# Getting python3 binary
if hash python3 2>/dev/null; then
python_bin="python3"
fi
# Removing old installations
echo "Removing old installation..."
sudo rm -rf /opt/buttermanager/
# Creating installation directory
echo "Creating installation directory in /opt/buttermanager"
sudo mkdir /opt/buttermanager/
sudo mkdir /opt/buttermanager/buttermanager
sudo mkdir /opt/buttermanager/gui
sudo chown ${USER:=$(/usr/bin/id -run)}:$USER -R /opt/buttermanager
# Copying all the files needed
echo "Copying all the files needed into /opt/buttermanager"
cp -ar ../buttermanager/* /opt/buttermanager/buttermanager
cp -ar ../setup.py /opt/buttermanager/
cp -ar ../README.md /opt/buttermanager
cp -ar ../packaging/buttermanager.svg /opt/buttermanager/gui/
# Creating desktop launcher
echo -e "Creating desktop launcher..."
if [ ! -d "${HOME}/.local/share/applications/" ]
then
echo "Directory ${HOME}/.local/share/applications/ doesn't exist. Creating it to store ButterManager desktop launcher."
mkdir -p ${HOME}/.local/share/applications/
fi
cp ../packaging/buttermanager.desktop ${HOME}/.local/share/applications/
# Installing libraries and ButterManager natively
echo "Installing libraries and ButterManager natively..."
cd /opt/buttermanager/
sudo $python_bin setup.py install --record installed_files.txt
echo ""
echo ""
echo '@@@@@@@@@@@@@@@@@@&&&&&&&&&&&&&&&&&&&@@@@@@@@@@@@@+
@@@@@@@@@@@@&&%%#########%%%%%#########%%&&@@@@@@@+
@@@@@@@&&((%&(/*****************/(%&&%((%&&@@@+
@@@@@@&%(#%#/*****************************/#%##%&@+
@@@@@(&(*****************/%%%%/************#%(%&+
@@@@&#&/***************#%#****%%***********(&(%&+
@@@@@&(#%%%%%*******/%%/******#&******%%%%%#(%&&+
@@@@@@@&&&%%(#&*****(%(*******(%#*******(%%&&&@@+
@@@@@@@@@@&&(#&**/%%*,.****/%%/*********#&&@@@@@+
@@@@@@@@@@&&((/(%#**.,.**(%%************#&&@@@@@+
@@@@@@@@@@&%%(****.,,#%/**************#&&@@@@@+
@@@@@@@@@@&&%/*******%%*****************#&&@@@@@+
@@@@@@@&&%#(#%%(*/#%(*******************#&&@@@@@+
@@@@@&%%((((#%&%%%**********************#&&@@@@@+
@@&&%#(((#%#&**********************%#*#&&@@@@@+
&%%((((#&&&&(#&*******************//*%#*#&&@@@@@+
%#((#%&@@@&&(#&*******************#%*%#*#&&@@@@@+
@&%%%@@@@@&&(#&///////////////////#%/%#/#&&@@@@@+
@@@@@@@@@@&##############################&&@@@@@'
echo ""
echo ""
echo "The installation has finished. Please, review the logs in order to see if everything was OK"
echo ""
echo ""
echo "You should find a new icon and desktop launcher called ButterManager. You are good to go."
else
# Exit
echo "Ok. Bye!"
fi
================================================
FILE: install/uninstall.sh
================================================
#!/bin/bash
# Script for uninstalling ButterManager
# -------------------------------------
#
# @author: Eloy García Almadén
# @email: eloy.garcia.pca@gmail.com
# -------------------------------------
# Removing old installations
echo "Removing old installation..."
installed_files=/opt/buttermanager/installed_files.txt
if test -f "$installed_files"; then
echo "ButterManager was installed natively. Removing libraries..."
cat $installed_files | xargs sudo rm -rf
fi
sudo rm -rf /opt/buttermanager/
rm ${HOME}/.local/share/applications/buttermanager.desktop
echo "Uninstallation process has been successfully completed. You are good to go!"
================================================
FILE: install/venv_install.sh
================================================
#!/bin/bash
# Script for installing ButterManager
# -----------------------------------
#
# @author: Eloy García Almadén
# @email: eloy.garcia.pca@gmail.com
# -------------------------------------
# Displaying requirements
echo "You are about to install ButterManager in a virtual environment."
echo "These packages MUST be installed before executing this script: 'python-setuptools', 'python-virtualenv' and 'tkinter'. The name of these packages can be different depending on the distro you are using. Example: On Arch -> 'python-setuptools', 'python-virtualenv' and 'tk'. On Fedora 'python3-setuptools', 'python3-virtualenv' and 'python3-tkinter'. In addition, if you are on Ubuntu or derivative, 'libxcb-xinerama0' needs to be installed too."
echo "Do you want to proceed with the installation? [y/n]"
read installButterManager
if [[ "$installButterManager" == "y" ]]; then
# Installing ButterManager
# Variables
python_bin="python"
# Getting python3 binary
if hash python3 2>/dev/null; then
python_bin="python3"
fi
# Removing old installations
echo "Removing old installation..."
sudo rm -rf /opt/buttermanager/
# Creating installation directory
echo "Creating installation directory in /opt/buttermanager"
sudo mkdir /opt/buttermanager/
sudo mkdir /opt/buttermanager/buttermanager
sudo mkdir /opt/buttermanager/gui
sudo chown ${USER:=$(/usr/bin/id -run)}:$USER -R /opt/buttermanager
# Copying all the files needed
echo "Copying all the files needed into /opt/buttermanager"
cp -ar ../buttermanager/* /opt/buttermanager/buttermanager
cp -ar ../requirements.txt /opt/buttermanager/
cp -ar ../packaging/buttermanager.svg /opt/buttermanager/gui/
# Creating desktop launcher
echo -e "Creating desktop launcher..."
if [ ! -d "${HOME}/.local/share/applications/" ]
then
echo "Directory ${HOME}/.local/share/applications/ doesn't exist. Creating it to store ButterManager desktop launcher."
mkdir -p ${HOME}/.local/share/applications/
fi
cp ../packaging/buttermanager_venv.desktop ${HOME}/.local/share/applications/buttermanager.desktop
# Creating virtual environment
echo "Creating virtual environment..."
cd /opt/buttermanager/
$python_bin -m venv env
# Enabling virtual environment
echo -e "Enabling virtual environment..."
source env/bin/activate
# Installing requirements
echo -e "Installing all the required modules into the virtual environment. Please wait..."
pip install --upgrade pip
pip install -r requirements.txt
echo ""
echo ""
echo '@@@@@@@@@@@@@@@@@@&&&&&&&&&&&&&&&&&&&@@@@@@@@@@@@@+
@@@@@@@@@@@@&&%%#########%%%%%#########%%&&@@@@@@@+
@@@@@@@&&((%&(/*****************/(%&&%((%&&@@@+
@@@@@@&%(#%#/*****************************/#%##%&@+
@@@@@(&(*****************/%%%%/************#%(%&+
@@@@&#&/***************#%#****%%***********(&(%&+
@@@@@&(#%%%%%*******/%%/******#&******%%%%%#(%&&+
@@@@@@@&&&%%(#&*****(%(*******(%#*******(%%&&&@@+
@@@@@@@@@@&&(#&**/%%*,.****/%%/*********#&&@@@@@+
@@@@@@@@@@&&((/(%#**.,.**(%%************#&&@@@@@+
@@@@@@@@@@&%%(****.,,#%/**************#&&@@@@@+
@@@@@@@@@@&&%/*******%%*****************#&&@@@@@+
@@@@@@@&&%#(#%%(*/#%(*******************#&&@@@@@+
@@@@@&%%((((#%&%%%**********************#&&@@@@@+
@@&&%#(((#%#&**********************%#*#&&@@@@@+
&%%((((#&&&&(#&*******************//*%#*#&&@@@@@+
%#((#%&@@@&&(#&*******************#%*%#*#&&@@@@@+
@&%%%@@@@@&&(#&///////////////////#%/%#/#&&@@@@@+
@@@@@@@@@@&##############################&&@@@@@'
echo ""
echo ""
echo "The installation has finished. Please, review the logs in order to see if everything was OK"
echo ""
echo "You should find a new icon and desktop launcher called ButterManager. You are good to go."
else
# Exit
echo "Ok. Bye!"
fi
================================================
FILE: packaging/buttermanager.desktop
================================================
[Desktop Entry]
Name=ButterManager
GenericName=ButterManager
Comment=ButterManager, a BTRFS tool for snapshoting, balancing and managing safe system upgrades.
Keywords=BTRFS;btrfs;system;filesystem;snapshot;balance;tool;gui
Exec=buttermanager
Icon=/opt/buttermanager/gui/buttermanager.svg
Terminal=false
Type=Application
Categories=Utility;System;
================================================
FILE: packaging/buttermanager_venv.desktop
================================================
[Desktop Entry]
Name=ButterManager
GenericName=ButterManager
Comment=ButterManager, a BTRFS tool for snapshoting, balancing and managing safe system upgrades.
Keywords=BTRFS;btrfs;system;filesystem;snapshot;balance;tool;gui
Exec=/opt/buttermanager/env/bin/python3 /opt/buttermanager/buttermanager/main.py
Path=/opt/buttermanager/buttermanager
Icon=/opt/buttermanager/gui/buttermanager.svg
Terminal=false
Type=Application
Categories=Utility;System;
================================================
FILE: requirements.txt
================================================
PyQt5>=5.10.1
PyQt5-sip>=12.7.0
PyYAML>=4.2b1
sip>=4.19.8
================================================
FILE: rpm/README.txt
================================================
This directory contains all the files needed to package ButterManager application for RPM based distributions.
This packaging was validated for Fedora 33, and should work for newer releases of Fedora or similar distributions.
================================================
FILE: rpm/buttermanager.spec
================================================
Name: buttermanager
Version: 2.5.2
Release: 0%{?dist}
Summary: Tool for managing Btrfs snapshots, balancing filesystems and more
License: GPLv3
URL: https://github.com/egara/buttermanager
Source0: %{url}/archive/%{version}/%{name}-%{version}.tar.gz
BuildArch: noarch
BuildRequires: python3-devel
BuildRequires: python3dist(setuptools)
Requires: btrfs-progs
Recommends: grub2-btrfs
%description
ButterManager is a BTRFS tool for managing snapshots, balancing filesystems
and upgrading the system safely.
%prep
%autosetup -p1
%build
%py3_build
%install
%py3_install
install -Dpm 644 packaging/%{name}.desktop %{buildroot}%{_datadir}/applications/%{name}.desktop
install -Dpm 644 packaging/%{name}.svg %{buildroot}%{_datadir}/icons/hicolor/scalable/%{name}.svg
# Fix the desktop file
sed -e "s/^Exec=.*/Exec=%{name}/" \
-e "/^Path=.*/d" \
-e "s/Icon=.*/Icon=%{name}/" \
-i %{buildroot}%{_datadir}/applications/%{name}.desktop
%files
%license LICENSE
%doc README.md doc
%{_bindir}/buttermanager
%{python3_sitelib}/buttermanager*
%{_datadir}/applications/%{name}.desktop
%{_datadir}/icons/hicolor/scalable/%{name}.svg
%changelog
* Thu Aug 15 2024 Eloy García Almadén - 2.5.2-0
- New release 2.5.2
* Mon Feb 19 2024 Eloy García Almadén - 2.5.1-0
- New release 2.5.1
* Sun Sept 18 2022 Eloy García Almadén - 2.5.0-0
- New release 2.5.0
* Sat Apr 7 2022 Eloy García Almadén - 2.4.3-0
- New release 2.4.3
* Sat July 3 2021 Eloy García Almadén - 2.4.2-0
- New release 2.4.2
* Sat May 1 2021 Eloy García Almadén - 2.4.1-0
- New release 2.4.1
* Mon Mar 31 2021 Eloy García Almadén - 2.4-0
- New release 2.4
* Mon Feb 15 2021 Neal Gompa - 2.3-0
- New release 2.3
* Wed Dec 30 2020 Neal Gompa - 2.2-0
- New release 2.2
* Wed Jun 17 2020 Neal Gompa - 1.9-0
- Initial package
================================================
FILE: setup.py
================================================
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="buttermanager",
version="2.5.2",
author="Eloy García Almadén",
author_email="eloy.garcia.pca@gmail.com",
description="BTRFS tool for managing snapshots, balancing filesystems and upgrading the system safetly",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/egara/buttermanager",
packages=['buttermanager', 'buttermanager.buttermanager', 'buttermanager.buttermanager.exception', 'buttermanager.buttermanager.filesystem', 'buttermanager.buttermanager.manager', 'buttermanager.buttermanager.util', 'buttermanager.buttermanager.window'],
package_data= {'buttermanager.buttermanager': ['ui/*', 'images/*']},
install_requires=[
'PyQt5>=5.10.1',
'PyYAML>=4.2b1',
],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
"Operating System :: POSIX :: Linux",
"Development Status :: 4 - Beta",
"Environment :: X11 Applications :: Qt",
"Intended Audience :: End Users/Desktop",
"Topic :: System :: Filesystems",
"Topic :: Utilities"
],
entry_points={
"console_scripts": [
"buttermanager = buttermanager.bm_main:main",
],
},
)
================================================
FILE: version.txt
================================================
2.5.2