chore: Reorganize file tree for easier onboarding. Rust project now at the root for simple git clone && cargo run
This commit is contained in:
4162
harmony-rs/Cargo.lock
generated
4162
harmony-rs/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,41 +0,0 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"private_repos/*",
|
||||
"examples/*",
|
||||
"harmony",
|
||||
"harmony_types",
|
||||
"harmony_macros",
|
||||
"harmony_tui",
|
||||
"opnsense-config",
|
||||
"opnsense-config-xml",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
readme = "README.md"
|
||||
license = "GNU AGPL v3"
|
||||
|
||||
[workspace.dependencies]
|
||||
log = "0.4.22"
|
||||
env_logger = "0.11.5"
|
||||
derive-new = "0.7.0"
|
||||
async-trait = "0.1.82"
|
||||
tokio = { version = "1.40.0", features = ["io-std", "fs"] }
|
||||
cidr = "0.2.3"
|
||||
russh = "0.45.0"
|
||||
russh-keys = "0.45.0"
|
||||
rand = "0.8.5"
|
||||
url = "2.5.4"
|
||||
kube = "0.98.0"
|
||||
k8s-openapi = { version = "0.24.0", features = [ "v1_30" ] }
|
||||
serde_yaml = "0.9.34"
|
||||
http = "1.2.0"
|
||||
|
||||
[workspace.dependencies.uuid]
|
||||
version = "1.11.0"
|
||||
features = [
|
||||
"v4", # Lets you generate random UUIDs
|
||||
"fast-rng", # Use a faster (but still sufficiently random) RNG
|
||||
"macro-diagnostics", # Enable better diagnostics for compile-time UUIDs
|
||||
]
|
||||
@@ -1,660 +0,0 @@
|
||||
# GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc.
|
||||
<https://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this
|
||||
license document, but changing it is not allowed.
|
||||
|
||||
## Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains
|
||||
free software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing
|
||||
under this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
## TERMS AND CONDITIONS
|
||||
|
||||
### 0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public
|
||||
License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds
|
||||
of works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of
|
||||
an exact copy. The resulting work is called a "modified version" of
|
||||
the earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user
|
||||
through a computer network, with no transfer of a copy, is not
|
||||
conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices" to
|
||||
the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
### 1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work for
|
||||
making modifications to it. "Object code" means any non-source form of
|
||||
a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can
|
||||
regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same
|
||||
work.
|
||||
|
||||
### 2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey,
|
||||
without conditions so long as your license otherwise remains in force.
|
||||
You may convey covered works to others for the sole purpose of having
|
||||
them make modifications exclusively for you, or provide you with
|
||||
facilities for running those works, provided that you comply with the
|
||||
terms of this License in conveying all material for which you do not
|
||||
control copyright. Those thus making or running the covered works for
|
||||
you must do so exclusively on your behalf, under your direction and
|
||||
control, on terms that prohibit them from making any copies of your
|
||||
copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the
|
||||
conditions stated below. Sublicensing is not allowed; section 10 makes
|
||||
it unnecessary.
|
||||
|
||||
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such
|
||||
circumvention is effected by exercising rights under this License with
|
||||
respect to the covered work, and you disclaim any intention to limit
|
||||
operation or modification of the work as a means of enforcing, against
|
||||
the work's users, your or third parties' legal rights to forbid
|
||||
circumvention of technological measures.
|
||||
|
||||
### 4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
### 5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these
|
||||
conditions:
|
||||
|
||||
- a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
- b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under
|
||||
section 7. This requirement modifies the requirement in section 4
|
||||
to "keep intact all notices".
|
||||
- c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
- d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
### 6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms of
|
||||
sections 4 and 5, provided that you also convey the machine-readable
|
||||
Corresponding Source under the terms of this License, in one of these
|
||||
ways:
|
||||
|
||||
- a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
- b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the Corresponding
|
||||
Source from a network server at no charge.
|
||||
- c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
- d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
- e) Convey the object code using peer-to-peer transmission,
|
||||
provided you inform other peers where the object code and
|
||||
Corresponding Source of the work are being offered to the general
|
||||
public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal,
|
||||
family, or household purposes, or (2) anything designed or sold for
|
||||
incorporation into a dwelling. In determining whether a product is a
|
||||
consumer product, doubtful cases shall be resolved in favor of
|
||||
coverage. For a particular product received by a particular user,
|
||||
"normally used" refers to a typical or common use of that class of
|
||||
product, regardless of the status of the particular user or of the way
|
||||
in which the particular user actually uses, or expects or is expected
|
||||
to use, the product. A product is a consumer product regardless of
|
||||
whether the product has substantial commercial, industrial or
|
||||
non-consumer uses, unless such uses represent the only significant
|
||||
mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to
|
||||
install and execute modified versions of a covered work in that User
|
||||
Product from a modified version of its Corresponding Source. The
|
||||
information must suffice to ensure that the continued functioning of
|
||||
the modified object code is in no case prevented or interfered with
|
||||
solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or
|
||||
updates for a work that has been modified or installed by the
|
||||
recipient, or for the User Product in which it has been modified or
|
||||
installed. Access to a network may be denied when the modification
|
||||
itself materially and adversely affects the operation of the network
|
||||
or violates the rules and protocols for communication across the
|
||||
network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
### 7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders
|
||||
of that material) supplement the terms of this License with terms:
|
||||
|
||||
- a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
- b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
- c) Prohibiting misrepresentation of the origin of that material,
|
||||
or requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
- d) Limiting the use for publicity purposes of names of licensors
|
||||
or authors of the material; or
|
||||
- e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
- f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions
|
||||
of it) with contractual assumptions of liability to the recipient,
|
||||
for any liability that these contractual assumptions directly
|
||||
impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions; the
|
||||
above requirements apply either way.
|
||||
|
||||
### 8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license
|
||||
from a particular copyright holder is reinstated (a) provisionally,
|
||||
unless and until the copyright holder explicitly and finally
|
||||
terminates your license, and (b) permanently, if the copyright holder
|
||||
fails to notify you of the violation by some reasonable means prior to
|
||||
60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
### 9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or run
|
||||
a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
### 10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
### 11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims owned
|
||||
or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within the
|
||||
scope of its coverage, prohibits the exercise of, or is conditioned on
|
||||
the non-exercise of one or more of the rights that are specifically
|
||||
granted under this License. You may not convey a covered work if you
|
||||
are a party to an arrangement with a third party that is in the
|
||||
business of distributing software, under which you make payment to the
|
||||
third party based on the extent of your activity of conveying the
|
||||
work, and under which the third party grants, to any of the parties
|
||||
who would receive the covered work from you, a discriminatory patent
|
||||
license (a) in connection with copies of the covered work conveyed by
|
||||
you (or copies made from those copies), or (b) primarily for and in
|
||||
connection with specific products or compilations that contain the
|
||||
covered work, unless you entered into that arrangement, or that patent
|
||||
license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
### 12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under
|
||||
this License and any other pertinent obligations, then as a
|
||||
consequence you may not convey it at all. For example, if you agree to
|
||||
terms that obligate you to collect a royalty for further conveying
|
||||
from those to whom you convey the Program, the only way you could
|
||||
satisfy both those terms and this License would be to refrain entirely
|
||||
from conveying the Program.
|
||||
|
||||
### 13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your
|
||||
version supports such interaction) an opportunity to receive the
|
||||
Corresponding Source of your version by providing access to the
|
||||
Corresponding Source from a network server at no charge, through some
|
||||
standard or customary means of facilitating copying of software. This
|
||||
Corresponding Source shall include the Corresponding Source for any
|
||||
work covered by version 3 of the GNU General Public License that is
|
||||
incorporated pursuant to the following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
### 14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Affero General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever
|
||||
published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions
|
||||
of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
### 15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
|
||||
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
|
||||
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
|
||||
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
|
||||
CORRECTION.
|
||||
|
||||
### 16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
|
||||
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
|
||||
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
|
||||
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
|
||||
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
|
||||
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
|
||||
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
### 17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
## How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these
|
||||
terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to
|
||||
attach them to the start of each source file to most effectively state
|
||||
the exclusion of warranty; and each file should have at least the
|
||||
"copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper
|
||||
mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for
|
||||
the specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. For more information on this, and how to apply and follow
|
||||
the GNU AGPL, see <https://www.gnu.org/licenses/>.
|
||||
@@ -1,7 +0,0 @@
|
||||
Due to the current setup being a mix of separate repositories with gitignore and rust workspace, a few options are required for cargo-watch to have the desired behavior :
|
||||
|
||||
```sh
|
||||
RUST_LOG=info cargo watch --ignore-nothing -w harmony -w private_repos/ -x 'run --bin nationtech'
|
||||
```
|
||||
|
||||
This will run the nationtech bin (likely `private_repos/nationtech/src/main.rs`) on any change in the harmony or private_repos folders.
|
||||
@@ -1,20 +0,0 @@
|
||||
[package]
|
||||
name = "example-kube-rs"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
harmony = { version = "0.1.0", path = "../../harmony" }
|
||||
cidr = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
url = { workspace = true }
|
||||
kube = "0.98.0"
|
||||
k8s-openapi = { version = "0.24.0", features = [ "v1_30" ] }
|
||||
http = "1.2.0"
|
||||
serde_yaml = "0.9.34"
|
||||
@@ -1,194 +0,0 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use harmony_macros::yaml;
|
||||
use k8s_openapi::{
|
||||
api::{
|
||||
apps::v1::{Deployment, DeploymentSpec},
|
||||
core::v1::{Container, Node, Pod, PodSpec, PodTemplateSpec},
|
||||
},
|
||||
apimachinery::pkg::apis::meta::v1::LabelSelector,
|
||||
};
|
||||
use kube::{
|
||||
Api, Client, Config, ResourceExt,
|
||||
api::{ListParams, ObjectMeta, PostParams},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let client = Client::try_default()
|
||||
.await
|
||||
.expect("Should instanciate client from defaults");
|
||||
println!("apiserver_version {:?}", client.apiserver_version().await);
|
||||
println!("default namespace {:?}", client.default_namespace());
|
||||
// println!(
|
||||
// "apiserver_groups {:?}",
|
||||
// client
|
||||
// .list_api_groups()
|
||||
// .await
|
||||
// .unwrap()
|
||||
// .groups
|
||||
// .iter()
|
||||
// .map(|g| g.name.clone())
|
||||
// .collect::<Vec<_>>()
|
||||
// );
|
||||
|
||||
// let pods: Api<Pod> = Api::default_namespaced(client.clone());
|
||||
// for p in pods.list(&ListParams::default()).await.unwrap() {
|
||||
// println!("found pod {}", p.name_any())
|
||||
// }
|
||||
|
||||
// let nodes : Api<Node> = Api::all(client.clone());
|
||||
// for n in nodes.list(&ListParams::default()).await.unwrap() {
|
||||
// println!("found node {} status {:?}", n.name_any(), n.status.unwrap())
|
||||
// }
|
||||
|
||||
let nginxdeployment = nginx_deployment_2();
|
||||
let nginxdeployment = nginx_deployment_serde();
|
||||
assert_eq!(nginx_deployment_2(), nginx_macro());
|
||||
assert_eq!(nginx_deployment_serde(), nginx_macro());
|
||||
let nginxdeployment = nginx_macro();
|
||||
let deployment: Api<Deployment> = Api::default_namespaced(client.clone());
|
||||
match deployment
|
||||
.create(&PostParams::default(), &nginxdeployment)
|
||||
.await
|
||||
{
|
||||
Ok(_d) => println!("Deployment success"),
|
||||
Err(e) => {
|
||||
println!("Error creating deployment {}", e);
|
||||
if let kube::Error::Api(error_response) = &e {
|
||||
if error_response.code == http::StatusCode::CONFLICT.as_u16() {
|
||||
println!("Already exists");
|
||||
return;
|
||||
}
|
||||
}
|
||||
panic!("{}", e)
|
||||
}
|
||||
};
|
||||
println!(
|
||||
"{:?}",
|
||||
deployment
|
||||
.get_status(&nginxdeployment.name_unchecked())
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
println!("Hello world");
|
||||
}
|
||||
|
||||
fn nginx_macro() -> Deployment {
|
||||
yaml!(
|
||||
r#"
|
||||
metadata:
|
||||
name: "nginx-test"
|
||||
spec:
|
||||
selector:
|
||||
matchLabels:
|
||||
app: nginx-test
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: nginx-test
|
||||
spec:
|
||||
containers:
|
||||
- image: nginx
|
||||
name: nginx"#
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn nginx_deployment_serde() -> Deployment {
|
||||
let deployment: Deployment = serde_yaml::from_str(
|
||||
r#"
|
||||
metadata:
|
||||
name: "nginx-test"
|
||||
spec:
|
||||
selector:
|
||||
matchLabels:
|
||||
app: nginx-test
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: nginx-test
|
||||
spec:
|
||||
containers:
|
||||
- image: nginx
|
||||
name: nginx"#,
|
||||
)
|
||||
.unwrap();
|
||||
return deployment;
|
||||
}
|
||||
fn nginx_deployment_2() -> Deployment {
|
||||
let mut pod_template = PodTemplateSpec::default();
|
||||
pod_template.metadata = Some(ObjectMeta {
|
||||
labels: Some(BTreeMap::from([(
|
||||
"app".to_string(),
|
||||
"nginx-test".to_string(),
|
||||
)])),
|
||||
..Default::default()
|
||||
});
|
||||
pod_template.spec = Some(PodSpec {
|
||||
containers: vec![Container {
|
||||
name: "nginx".to_string(),
|
||||
image: Some("nginx".to_string()),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
});
|
||||
let mut spec = DeploymentSpec::default();
|
||||
spec.template = pod_template;
|
||||
spec.selector = LabelSelector {
|
||||
match_expressions: None,
|
||||
match_labels: Some(BTreeMap::from([(
|
||||
"app".to_string(),
|
||||
"nginx-test".to_string(),
|
||||
)])),
|
||||
};
|
||||
|
||||
let mut deployment = Deployment::default();
|
||||
deployment.spec = Some(spec);
|
||||
deployment.metadata.name = Some("nginx-test".to_string());
|
||||
|
||||
deployment
|
||||
}
|
||||
fn nginx_deployment() -> Deployment {
|
||||
let deployment = Deployment {
|
||||
metadata: ObjectMeta {
|
||||
name: Some("nginx-test".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
spec: Some(DeploymentSpec {
|
||||
min_ready_seconds: None,
|
||||
paused: None,
|
||||
progress_deadline_seconds: None,
|
||||
replicas: Some(1),
|
||||
revision_history_limit: Some(10),
|
||||
selector: LabelSelector {
|
||||
match_expressions: None,
|
||||
match_labels: Some(BTreeMap::from([(
|
||||
"app".to_string(),
|
||||
"nginx-test".to_string(),
|
||||
)])),
|
||||
},
|
||||
strategy: None,
|
||||
template: PodTemplateSpec {
|
||||
metadata: Some(ObjectMeta {
|
||||
labels: Some(BTreeMap::from([(
|
||||
"app".to_string(),
|
||||
"nginx-test".to_string(),
|
||||
)])),
|
||||
..Default::default()
|
||||
}),
|
||||
spec: Some(PodSpec {
|
||||
containers: vec![Container {
|
||||
name: "nginx".to_string(),
|
||||
image: Some("nginx".to_string()),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}),
|
||||
},
|
||||
}),
|
||||
status: None,
|
||||
};
|
||||
println!("{:?}", deployment.managed_fields());
|
||||
deployment
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
[package]
|
||||
name = "example-opnsense"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
harmony = { path = "../../harmony" }
|
||||
harmony_tui = { path = "../../harmony_tui" }
|
||||
harmony_types = { path = "../../harmony_types" }
|
||||
cidr = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
url = { workspace = true }
|
||||
@@ -1,15 +0,0 @@
|
||||
## OPNSense demo
|
||||
|
||||
Download the virtualbox snapshot from {{TODO URL}}
|
||||
|
||||
Start the virtualbox image
|
||||
|
||||
This virtualbox image is configured to use a bridge on the host's physical interface, make sure the bridge is up and the virtual machine can reach internet.
|
||||
|
||||
Credentials are opnsense default (root/opnsense)
|
||||
|
||||
Run the project with the correct ip address on the command line :
|
||||
|
||||
```bash
|
||||
cargo run -p example-opnsense -- 192.168.5.229
|
||||
```
|
||||
@@ -1,104 +0,0 @@
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use cidr::Ipv4Cidr;
|
||||
use harmony::{
|
||||
hardware::{FirewallGroup, HostCategory, Location, PhysicalHost, SwitchGroup},
|
||||
infra::opnsense::OPNSenseManagementInterface,
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::{
|
||||
dummy::{ErrorScore, PanicScore, SuccessScore},
|
||||
http::HttpScore,
|
||||
okd::{dhcp::OKDDhcpScore, dns::OKDDnsScore},
|
||||
opnsense::OPNSenseShellCommandScore,
|
||||
tftp::TftpScore,
|
||||
},
|
||||
topology::{LogicalHost, UnmanagedRouter, Url},
|
||||
};
|
||||
use harmony_macros::{ip, mac_address};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let firewall = harmony::topology::LogicalHost {
|
||||
ip: ip!("192.168.5.229"),
|
||||
name: String::from("opnsense-1"),
|
||||
};
|
||||
|
||||
let opnsense = Arc::new(
|
||||
harmony::infra::opnsense::OPNSenseFirewall::new(firewall, None, "root", "opnsense").await,
|
||||
);
|
||||
let lan_subnet = Ipv4Addr::new(10, 100, 8, 0);
|
||||
let gateway_ipv4 = Ipv4Addr::new(10, 100, 8, 1);
|
||||
let gateway_ip = IpAddr::V4(gateway_ipv4);
|
||||
let topology = harmony::topology::HAClusterTopology {
|
||||
domain_name: "demo.harmony.mcd".to_string(),
|
||||
router: Arc::new(UnmanagedRouter::new(
|
||||
gateway_ip,
|
||||
Ipv4Cidr::new(lan_subnet, 24).unwrap(),
|
||||
)),
|
||||
load_balancer: opnsense.clone(),
|
||||
firewall: opnsense.clone(),
|
||||
tftp_server: opnsense.clone(),
|
||||
http_server: opnsense.clone(),
|
||||
dhcp_server: opnsense.clone(),
|
||||
dns_server: opnsense.clone(),
|
||||
control_plane: vec![LogicalHost {
|
||||
ip: ip!("10.100.8.20"),
|
||||
name: "cp0".to_string(),
|
||||
}],
|
||||
bootstrap_host: LogicalHost {
|
||||
ip: ip!("10.100.8.20"),
|
||||
name: "cp0".to_string(),
|
||||
},
|
||||
workers: vec![],
|
||||
switch: vec![],
|
||||
};
|
||||
|
||||
let inventory = Inventory {
|
||||
location: Location::new(
|
||||
"232 des Éperviers, Wendake, Qc, G0A 4V0".to_string(),
|
||||
"wk".to_string(),
|
||||
),
|
||||
switch: SwitchGroup::from([]),
|
||||
firewall: FirewallGroup::from([PhysicalHost::empty(HostCategory::Firewall)
|
||||
.management(Arc::new(OPNSenseManagementInterface::new()))]),
|
||||
storage_host: vec![],
|
||||
worker_host: vec![],
|
||||
control_plane_host: vec![
|
||||
PhysicalHost::empty(HostCategory::Server)
|
||||
.mac_address(mac_address!("08:00:27:62:EC:C3")),
|
||||
],
|
||||
};
|
||||
|
||||
// TODO regroup smaller scores in a larger one such as this
|
||||
// let okd_boostrap_preparation();
|
||||
|
||||
let dhcp_score = OKDDhcpScore::new(&topology, &inventory);
|
||||
let dns_score = OKDDnsScore::new(&topology);
|
||||
let load_balancer_score =
|
||||
harmony::modules::okd::load_balancer::OKDLoadBalancerScore::new(&topology);
|
||||
|
||||
let tftp_score = TftpScore::new(Url::LocalFolder("../../../watchguard/tftpboot".to_string()));
|
||||
let http_score = HttpScore::new(Url::LocalFolder(
|
||||
"../../../watchguard/pxe-http-files".to_string(),
|
||||
));
|
||||
let mut maestro = Maestro::new(inventory, topology);
|
||||
maestro.register_all(vec![
|
||||
Box::new(dns_score),
|
||||
Box::new(dhcp_score),
|
||||
Box::new(load_balancer_score),
|
||||
Box::new(tftp_score),
|
||||
Box::new(http_score),
|
||||
Box::new(OPNSenseShellCommandScore {
|
||||
opnsense: opnsense.get_opnsense_config(),
|
||||
command: "touch /tmp/helloharmonytouching".to_string(),
|
||||
}),
|
||||
Box::new(SuccessScore {}),
|
||||
Box::new(ErrorScore {}),
|
||||
Box::new(PanicScore {}),
|
||||
]);
|
||||
harmony_tui::init(maestro).await.unwrap();
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
[package]
|
||||
name = "example-tui"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
harmony = { path = "../../harmony" }
|
||||
harmony_tui = { path = "../../harmony_tui" }
|
||||
harmony_types = { path = "../../harmony_types" }
|
||||
cidr = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
url = { workspace = true }
|
||||
@@ -1,20 +0,0 @@
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::{dummy::{ErrorScore, PanicScore, SuccessScore}, k8s::deployment::K8sDeploymentScore},
|
||||
topology::HAClusterTopology,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let inventory = Inventory::autoload();
|
||||
let topology = HAClusterTopology::autoload();
|
||||
let mut maestro = Maestro::new(inventory, topology);
|
||||
|
||||
maestro.register_all(vec![
|
||||
Box::new(SuccessScore {}),
|
||||
Box::new(ErrorScore {}),
|
||||
Box::new(PanicScore {}),
|
||||
]);
|
||||
harmony_tui::init(maestro).await.unwrap();
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
[package]
|
||||
name = "harmony"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
libredfish = "0.1.1"
|
||||
reqwest = {version = "0.11", features = ["blocking", "json"] }
|
||||
russh = "0.45.0"
|
||||
rust-ipmi = "0.1.1"
|
||||
semver = "1.0.23"
|
||||
serde = { version = "1.0.209", features = ["derive"] }
|
||||
serde_json = "1.0.127"
|
||||
tokio = { workspace = true }
|
||||
derive-new = { workspace = true }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
async-trait = { workspace = true }
|
||||
cidr = { workspace = true }
|
||||
opnsense-config = { path = "../opnsense-config" }
|
||||
opnsense-config-xml = { path = "../opnsense-config-xml" }
|
||||
harmony_macros = { path = "../harmony_macros" }
|
||||
harmony_types = { path = "../harmony_types" }
|
||||
uuid = { workspace = true }
|
||||
url = { workspace = true }
|
||||
kube = { workspace = true }
|
||||
k8s-openapi = { workspace = true }
|
||||
serde_yaml = { workspace = true }
|
||||
http = { workspace = true }
|
||||
@@ -1,12 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Id {
|
||||
value: String,
|
||||
}
|
||||
|
||||
impl Id {
|
||||
pub fn from_string(value: String) -> Self {
|
||||
Self { value }
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
mod id;
|
||||
mod version;
|
||||
pub use id::*;
|
||||
pub use version::*;
|
||||
@@ -1,76 +0,0 @@
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Version {
|
||||
value: semver::Version,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct VersionError {
|
||||
_msg: String,
|
||||
}
|
||||
|
||||
impl From<semver::Error> for VersionError {
|
||||
fn from(value: semver::Error) -> Self {
|
||||
Self {
|
||||
_msg: value.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Version {
|
||||
pub fn from(val: &str) -> Result<Self, VersionError> {
|
||||
Ok(Self {
|
||||
value: semver::Version::parse(val)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> serde::Deserialize<'de> for Version {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
semver::Version::parse(&s)
|
||||
.map(|value| Version { value })
|
||||
.map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
impl serde::Serialize for Version {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
self.value.to_string().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Version {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
return self.value.fmt(f);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn version_serialize_deserialize() {
|
||||
let v = "10.0.1331-ababa+b123";
|
||||
let version = Version {
|
||||
value: semver::Version::parse(v).unwrap(),
|
||||
};
|
||||
|
||||
let s = serde_json::to_string(&version).unwrap();
|
||||
let version2: Version = serde_json::from_str(&s).unwrap();
|
||||
|
||||
assert_eq!(version2.value.major, 10);
|
||||
assert_eq!(version2.value.minor, 0);
|
||||
assert_eq!(version2.value.patch, 1331);
|
||||
assert_eq!(version2.value.build.to_string(), "b123");
|
||||
assert_eq!(version2.value.pre.to_string(), "ababa");
|
||||
assert_eq!(version2.value.to_string(), v);
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
use std::fmt;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::topology::IpAddress;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ExecutorError {
|
||||
NetworkError(String),
|
||||
AuthenticationError(String),
|
||||
ConfigurationError(String),
|
||||
UnexpectedError(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for ExecutorError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ExecutorError::NetworkError(msg) => write!(f, "Network error: {}", msg),
|
||||
ExecutorError::AuthenticationError(msg) => write!(f, "Authentication error: {}", msg),
|
||||
ExecutorError::ConfigurationError(msg) => write!(f, "Configuration error: {}", msg),
|
||||
ExecutorError::UnexpectedError(msg) => write!(f, "Unexpected error: {}", msg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ExecutorError {}
|
||||
|
||||
#[async_trait]
|
||||
pub trait SshClient {
|
||||
async fn test_connection(
|
||||
&self,
|
||||
address: IpAddress,
|
||||
username: &str,
|
||||
password: &str,
|
||||
) -> Result<(), ExecutorError>;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
use derive_new::new;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum FilterKind {
|
||||
Label,
|
||||
Kind,
|
||||
}
|
||||
|
||||
pub type FilterValue = String;
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct Filter {
|
||||
_kind: FilterKind,
|
||||
_value: FilterValue,
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use derive_new::new;
|
||||
use harmony_types::net::MacAddress;
|
||||
|
||||
pub type HostGroup = Vec<PhysicalHost>;
|
||||
pub type SwitchGroup = Vec<Switch>;
|
||||
pub type FirewallGroup = Vec<PhysicalHost>;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PhysicalHost {
|
||||
pub category: HostCategory,
|
||||
pub network: Vec<NetworkInterface>,
|
||||
pub management: Arc<dyn ManagementInterface>,
|
||||
pub storage: Vec<Storage>,
|
||||
pub labels: Vec<Label>,
|
||||
pub memory_size: Option<u64>,
|
||||
pub cpu_count: Option<u64>,
|
||||
}
|
||||
|
||||
impl PhysicalHost {
|
||||
pub fn empty(category: HostCategory) -> Self {
|
||||
Self {
|
||||
category,
|
||||
network: vec![],
|
||||
storage: vec![],
|
||||
labels: vec![],
|
||||
management: Arc::new(ManualManagementInterface {}),
|
||||
memory_size: None,
|
||||
cpu_count: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cluster_mac(&self) -> MacAddress {
|
||||
self.network
|
||||
.get(0)
|
||||
.expect("Cluster physical host should have a network interface")
|
||||
.mac_address
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub fn cpu(mut self, cpu_count: Option<u64>) -> Self {
|
||||
self.cpu_count = cpu_count;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn memory_size(mut self, memory_size: Option<u64>) -> Self {
|
||||
self.memory_size = memory_size;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn storage(
|
||||
mut self,
|
||||
connection: StorageConnectionType,
|
||||
kind: StorageKind,
|
||||
size: u64,
|
||||
serial: String,
|
||||
) -> Self {
|
||||
self.storage.push(Storage {
|
||||
connection,
|
||||
kind,
|
||||
size,
|
||||
serial,
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
pub fn mac_address(mut self, mac_address: MacAddress) -> Self {
|
||||
self.network.push(NetworkInterface {
|
||||
name: None,
|
||||
mac_address,
|
||||
speed: None,
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
pub fn label(mut self, name: String, value: String) -> Self {
|
||||
self.labels.push(Label {
|
||||
_name: name,
|
||||
_value: value,
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
pub fn management(mut self, management: Arc<dyn ManagementInterface>) -> Self {
|
||||
self.management = management;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(new)]
|
||||
pub struct ManualManagementInterface;
|
||||
|
||||
impl ManagementInterface for ManualManagementInterface {
|
||||
fn boot_to_pxe(&self) {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_supported_protocol_names(&self) -> String {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ManagementInterface: Send + Sync {
|
||||
fn boot_to_pxe(&self);
|
||||
fn get_supported_protocol_names(&self) -> String;
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for dyn ManagementInterface {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!(
|
||||
"ManagementInterface protocols : {}",
|
||||
self.get_supported_protocol_names(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum HostCategory {
|
||||
Server,
|
||||
Firewall,
|
||||
Switch,
|
||||
}
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct NetworkInterface {
|
||||
pub name: Option<String>,
|
||||
pub mac_address: MacAddress,
|
||||
pub speed: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub enum StorageConnectionType {
|
||||
Sata3g,
|
||||
Sata6g,
|
||||
Sas6g,
|
||||
Sas12g,
|
||||
PCIE,
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum StorageKind {
|
||||
SSD,
|
||||
NVME,
|
||||
HDD,
|
||||
}
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct Storage {
|
||||
pub connection: StorageConnectionType,
|
||||
pub kind: StorageKind,
|
||||
pub size: u64,
|
||||
pub serial: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Switch {
|
||||
_interface: Vec<NetworkInterface>,
|
||||
_management_interface: NetworkInterface,
|
||||
}
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct Label {
|
||||
_name: String,
|
||||
_value: String,
|
||||
}
|
||||
pub type Address = String;
|
||||
|
||||
#[derive(new, Debug)]
|
||||
pub struct Location {
|
||||
pub address: Address,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl Location {
|
||||
pub fn test_building() -> Location {
|
||||
Self {
|
||||
address: String::new(),
|
||||
name: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
use std::error::Error;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use derive_new::new;
|
||||
|
||||
use super::{
|
||||
data::{Id, Version},
|
||||
executors::ExecutorError,
|
||||
inventory::Inventory,
|
||||
topology::HAClusterTopology,
|
||||
};
|
||||
|
||||
pub enum InterpretName {
|
||||
OPNSenseDHCP,
|
||||
OPNSenseDns,
|
||||
LoadBalancer,
|
||||
Tftp,
|
||||
Http,
|
||||
Dummy,
|
||||
Panic,
|
||||
OPNSense,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for InterpretName {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
InterpretName::OPNSenseDHCP => f.write_str("OPNSenseDHCP"),
|
||||
InterpretName::OPNSenseDns => f.write_str("OPNSenseDns"),
|
||||
InterpretName::LoadBalancer => f.write_str("LoadBalancer"),
|
||||
InterpretName::Tftp => f.write_str("Tftp"),
|
||||
InterpretName::Http => f.write_str("Http"),
|
||||
InterpretName::Dummy => f.write_str("Dummy"),
|
||||
InterpretName::Panic => f.write_str("Panic"),
|
||||
InterpretName::OPNSense => f.write_str("OPNSense"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait Interpret: std::fmt::Debug + Send {
|
||||
async fn execute(
|
||||
&self,
|
||||
inventory: &Inventory,
|
||||
topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError>;
|
||||
fn get_name(&self) -> InterpretName;
|
||||
fn get_version(&self) -> Version;
|
||||
fn get_status(&self) -> InterpretStatus;
|
||||
fn get_children(&self) -> Vec<Id>;
|
||||
}
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct Outcome {
|
||||
pub status: InterpretStatus,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
pub fn noop() -> Self {
|
||||
Self {
|
||||
status: InterpretStatus::NOOP,
|
||||
message: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn success(message: String) -> Self {
|
||||
Self {
|
||||
status: InterpretStatus::SUCCESS,
|
||||
message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum InterpretStatus {
|
||||
SUCCESS,
|
||||
FAILURE,
|
||||
RUNNING,
|
||||
QUEUED,
|
||||
BLOCKED,
|
||||
NOOP,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for InterpretStatus {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let msg = match self {
|
||||
InterpretStatus::SUCCESS => "SUCCESS",
|
||||
InterpretStatus::FAILURE => "FAILURE",
|
||||
InterpretStatus::RUNNING => "RUNNING",
|
||||
InterpretStatus::QUEUED => "QUEUED",
|
||||
InterpretStatus::BLOCKED => "BLOCKED",
|
||||
InterpretStatus::NOOP => "NO_OP",
|
||||
};
|
||||
f.write_str(msg)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, new)]
|
||||
pub struct InterpretError {
|
||||
msg: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for InterpretError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.msg)
|
||||
}
|
||||
}
|
||||
impl Error for InterpretError {}
|
||||
|
||||
impl From<ExecutorError> for InterpretError {
|
||||
fn from(value: ExecutorError) -> Self {
|
||||
Self {
|
||||
msg: format!("InterpretError : {value}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<kube::Error> for InterpretError {
|
||||
fn from(value: kube::Error) -> Self {
|
||||
Self {
|
||||
msg: format!("InterpretError : {value}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct InventoryFilter {
|
||||
target: Vec<Filter>,
|
||||
}
|
||||
|
||||
pub struct InventorySlice;
|
||||
|
||||
impl InventoryFilter {
|
||||
pub fn apply(&self, _inventory: &Inventory) -> InventorySlice {
|
||||
info!("Applying inventory filter {:?}", self.target);
|
||||
todo!("TODO apply inventory filter, refactor as a slice")
|
||||
}
|
||||
}
|
||||
|
||||
use derive_new::new;
|
||||
use log::info;
|
||||
|
||||
use super::{
|
||||
filter::Filter,
|
||||
hardware::{FirewallGroup, HostGroup, Location, SwitchGroup},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Inventory {
|
||||
pub location: Location,
|
||||
pub switch: SwitchGroup,
|
||||
// Firewall is really just a host but with somewhat specialized hardware
|
||||
// I'm not entirely sure it belongs to its own category but it helps make things easier and
|
||||
// clearer for now so let's try it this way.
|
||||
pub firewall: FirewallGroup,
|
||||
pub worker_host: HostGroup,
|
||||
pub storage_host: HostGroup,
|
||||
pub control_plane_host: HostGroup,
|
||||
}
|
||||
|
||||
impl Inventory {
|
||||
pub fn autoload() -> Self {
|
||||
Self {
|
||||
location: Location::test_building(),
|
||||
switch: SwitchGroup::new(),
|
||||
firewall: FirewallGroup::new(),
|
||||
worker_host: HostGroup::new(),
|
||||
storage_host: HostGroup::new(),
|
||||
control_plane_host: HostGroup::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use log::info;
|
||||
|
||||
use super::{
|
||||
interpret::{Interpret, InterpretError, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
topology::HAClusterTopology,
|
||||
};
|
||||
|
||||
type ScoreVec = Vec<Box<dyn Score>>;
|
||||
|
||||
pub struct Maestro {
|
||||
inventory: Inventory,
|
||||
topology: HAClusterTopology,
|
||||
scores: Arc<RwLock<ScoreVec>>,
|
||||
}
|
||||
|
||||
impl Maestro {
|
||||
pub fn new(inventory: Inventory, topology: HAClusterTopology) -> Self {
|
||||
Self {
|
||||
inventory,
|
||||
topology,
|
||||
scores: Arc::new(RwLock::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(&mut self) {
|
||||
info!("Starting Maestro");
|
||||
}
|
||||
|
||||
pub fn register_all(&mut self, mut scores: ScoreVec) {
|
||||
let mut score_mut = self.scores.write().expect("Should acquire lock");
|
||||
score_mut.append(&mut scores);
|
||||
}
|
||||
|
||||
pub async fn interpret(&self, score: Box<dyn Score>) -> Result<Outcome, InterpretError> {
|
||||
info!("Running score {score:?}");
|
||||
let interpret = score.create_interpret();
|
||||
info!("Launching interpret {interpret:?}");
|
||||
let result = interpret.execute(&self.inventory, &self.topology).await;
|
||||
info!("Got result {result:?}");
|
||||
result
|
||||
}
|
||||
|
||||
pub fn scores(&self) -> Arc<RwLock<ScoreVec>> {
|
||||
self.scores.clone()
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
pub mod data;
|
||||
pub mod executors;
|
||||
pub mod filter;
|
||||
pub mod hardware;
|
||||
pub mod interpret;
|
||||
pub mod inventory;
|
||||
pub mod maestro;
|
||||
pub mod score;
|
||||
pub mod topology;
|
||||
@@ -1,7 +0,0 @@
|
||||
use super::interpret::Interpret;
|
||||
|
||||
pub trait Score: std::fmt::Debug + Send + Sync {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret>;
|
||||
fn name(&self) -> String;
|
||||
fn clone_box(&self) -> Box<dyn Score>;
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use harmony_macros::ip;
|
||||
use harmony_types::net::MacAddress;
|
||||
|
||||
use crate::executors::ExecutorError;
|
||||
|
||||
use super::DHCPStaticEntry;
|
||||
use super::DhcpServer;
|
||||
use super::DnsRecord;
|
||||
use super::DnsRecordType;
|
||||
use super::DnsServer;
|
||||
use super::Firewall;
|
||||
use super::HttpServer;
|
||||
use super::IpAddress;
|
||||
use super::LoadBalancer;
|
||||
use super::LoadBalancerService;
|
||||
use super::LogicalHost;
|
||||
use super::Router;
|
||||
use super::TftpServer;
|
||||
|
||||
use super::Url;
|
||||
use super::openshift::OpenshiftClient;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HAClusterTopology {
|
||||
pub domain_name: String,
|
||||
pub router: Arc<dyn Router>,
|
||||
pub load_balancer: Arc<dyn LoadBalancer>,
|
||||
pub firewall: Arc<dyn Firewall>,
|
||||
pub dhcp_server: Arc<dyn DhcpServer>,
|
||||
pub tftp_server: Arc<dyn TftpServer>,
|
||||
pub http_server: Arc<dyn HttpServer>,
|
||||
pub dns_server: Arc<dyn DnsServer>,
|
||||
pub bootstrap_host: LogicalHost,
|
||||
pub control_plane: Vec<LogicalHost>,
|
||||
pub workers: Vec<LogicalHost>,
|
||||
pub switch: Vec<LogicalHost>,
|
||||
}
|
||||
|
||||
impl HAClusterTopology {
|
||||
pub async fn oc_client(&self) -> Result<Arc<OpenshiftClient>, kube::Error> {
|
||||
Ok(Arc::new(OpenshiftClient::try_default().await?))
|
||||
}
|
||||
|
||||
pub fn autoload() -> Self {
|
||||
let dummy_infra = Arc::new(DummyInfra {});
|
||||
let dummy_host = LogicalHost {
|
||||
ip: ip!("0.0.0.0"),
|
||||
name: "dummyhost".to_string(),
|
||||
};
|
||||
|
||||
Self {
|
||||
domain_name: "DummyTopology".to_string(),
|
||||
router: dummy_infra.clone(),
|
||||
load_balancer: dummy_infra.clone(),
|
||||
firewall: dummy_infra.clone(),
|
||||
dhcp_server: dummy_infra.clone(),
|
||||
tftp_server: dummy_infra.clone(),
|
||||
http_server: dummy_infra.clone(),
|
||||
dns_server: dummy_infra.clone(),
|
||||
bootstrap_host: dummy_host,
|
||||
control_plane: vec![],
|
||||
workers: vec![],
|
||||
switch: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DummyInfra;
|
||||
|
||||
const UNIMPLEMENTED_DUMMY_INFRA: &str = "This is a dummy infrastructure, no operation is supported";
|
||||
|
||||
impl Router for DummyInfra {
|
||||
fn get_gateway(&self) -> super::IpAddress {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn get_cidr(&self) -> cidr::Ipv4Cidr {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
}
|
||||
|
||||
impl Firewall for DummyInfra {
|
||||
fn add_rule(
|
||||
&mut self,
|
||||
_rule: super::FirewallRule,
|
||||
) -> Result<(), crate::executors::ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn remove_rule(&mut self, _rule_id: &str) -> Result<(), crate::executors::ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn list_rules(&self) -> Vec<super::FirewallRule> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn get_ip(&self) -> super::IpAddress {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DhcpServer for DummyInfra {
|
||||
async fn add_static_mapping(&self, _entry: &DHCPStaticEntry) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn remove_static_mapping(&self, _mac: &MacAddress) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn list_static_mappings(&self) -> Vec<(MacAddress, IpAddress)> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn set_next_server(&self, _ip: IpAddress) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn set_boot_filename(&self, _boot_filename: &str) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl LoadBalancer for DummyInfra {
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn add_service(&self, _service: &LoadBalancerService) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn remove_service(&self, _service: &LoadBalancerService) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn list_services(&self) -> Vec<LoadBalancerService> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn ensure_initialized(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn reload_restart(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TftpServer for DummyInfra {
|
||||
async fn serve_files(&self, _url: &Url) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
|
||||
async fn set_ip(&self, _ip: IpAddress) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn ensure_initialized(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn reload_restart(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl HttpServer for DummyInfra {
|
||||
async fn serve_files(&self, _url: &Url) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn ensure_initialized(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn reload_restart(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DnsServer for DummyInfra {
|
||||
async fn register_dhcp_leases(&self, _register: bool) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn register_hosts(&self, _hosts: Vec<DnsRecord>) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn remove_record(
|
||||
&mut self,
|
||||
_name: &str,
|
||||
_record_type: DnsRecordType,
|
||||
) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn list_records(&self) -> Vec<DnsRecord> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
use derive_new::new;
|
||||
|
||||
use crate::hardware::PhysicalHost;
|
||||
|
||||
use super::LogicalHost;
|
||||
|
||||
/// Represents the binding between a LogicalHost and a PhysicalHost.
|
||||
///
|
||||
/// This is the only construct that directly maps a logical host to a physical host.
|
||||
/// It serves as a bridge between the logical cluster structure and the physical infrastructure.
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct HostBinding {
|
||||
/// Reference to the LogicalHost
|
||||
pub logical_host: LogicalHost,
|
||||
/// Reference to the PhysicalHost
|
||||
pub physical_host: PhysicalHost,
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
use crate::executors::ExecutorError;
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::{IpAddress, Url};
|
||||
|
||||
#[async_trait]
|
||||
pub trait HttpServer: Send + Sync {
|
||||
async fn serve_files(&self, url: &Url) -> Result<(), ExecutorError>;
|
||||
fn get_ip(&self) -> IpAddress;
|
||||
|
||||
// async fn set_ip(&self, ip: IpAddress) -> Result<(), ExecutorError>;
|
||||
async fn ensure_initialized(&self) -> Result<(), ExecutorError>;
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError>;
|
||||
async fn reload_restart(&self) -> Result<(), ExecutorError>;
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for dyn HttpServer {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!(
|
||||
"HttpServer serving files at {}",
|
||||
self.get_ip()
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
use std::{net::SocketAddr, str::FromStr};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use log::debug;
|
||||
|
||||
use super::{IpAddress, LogicalHost};
|
||||
use crate::executors::ExecutorError;
|
||||
|
||||
#[async_trait]
|
||||
pub trait LoadBalancer: Send + Sync {
|
||||
fn get_ip(&self) -> IpAddress;
|
||||
fn get_host(&self) -> LogicalHost;
|
||||
async fn add_service(&self, service: &LoadBalancerService) -> Result<(), ExecutorError>;
|
||||
async fn remove_service(&self, service: &LoadBalancerService) -> Result<(), ExecutorError>;
|
||||
async fn list_services(&self) -> Vec<LoadBalancerService>;
|
||||
async fn ensure_initialized(&self) -> Result<(), ExecutorError>;
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError>;
|
||||
async fn reload_restart(&self) -> Result<(), ExecutorError>;
|
||||
async fn ensure_service_exists(
|
||||
&self,
|
||||
service: &LoadBalancerService,
|
||||
) -> Result<(), ExecutorError> {
|
||||
debug!(
|
||||
"Listing LoadBalancer services {:?}",
|
||||
self.list_services().await
|
||||
);
|
||||
if !self.list_services().await.contains(service) {
|
||||
self.add_service(service).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for dyn LoadBalancer {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!("LoadBalancer {}", self.get_ip()))
|
||||
}
|
||||
}
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub struct LoadBalancerService {
|
||||
pub backend_servers: Vec<BackendServer>,
|
||||
pub listening_port: SocketAddr,
|
||||
pub health_check: Option<HealthCheck>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub struct BackendServer {
|
||||
pub address: String,
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum HttpMethod {
|
||||
GET,
|
||||
POST,
|
||||
PUT,
|
||||
PATCH,
|
||||
DELETE,
|
||||
}
|
||||
|
||||
impl From<String> for HttpMethod {
|
||||
fn from(value: String) -> Self {
|
||||
Self::from_str(&value).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for HttpMethod {
|
||||
type Err = String;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s.to_uppercase().as_str() {
|
||||
"GET" => Ok(HttpMethod::GET),
|
||||
"POST" => Ok(HttpMethod::POST),
|
||||
"PUT" => Ok(HttpMethod::PUT),
|
||||
"PATCH" => Ok(HttpMethod::PATCH),
|
||||
"DELETE" => Ok(HttpMethod::DELETE),
|
||||
_ => Err(format!("Invalid HTTP method: {}", s)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for HttpMethod {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
HttpMethod::GET => write!(f, "GET"),
|
||||
HttpMethod::POST => write!(f, "POST"),
|
||||
HttpMethod::PUT => write!(f, "PUT"),
|
||||
HttpMethod::PATCH => write!(f, "PATCH"),
|
||||
HttpMethod::DELETE => write!(f, "DELETE"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum HttpStatusCode {
|
||||
Success2xx,
|
||||
UserError4xx,
|
||||
ServerError5xx,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum HealthCheck {
|
||||
HTTP(String, HttpMethod, HttpStatusCode),
|
||||
TCP(Option<u16>),
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
mod ha_cluster;
|
||||
mod host_binding;
|
||||
mod http;
|
||||
mod load_balancer;
|
||||
pub mod openshift;
|
||||
mod router;
|
||||
mod tftp;
|
||||
pub use ha_cluster::*;
|
||||
pub use load_balancer::*;
|
||||
pub use router::*;
|
||||
mod network;
|
||||
pub use host_binding::*;
|
||||
pub use http::*;
|
||||
pub use network::*;
|
||||
pub use tftp::*;
|
||||
|
||||
use std::{net::IpAddr, sync::Arc};
|
||||
|
||||
pub type IpAddress = IpAddr;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Url {
|
||||
LocalFolder(String),
|
||||
Remote(url::Url),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Url {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Url::LocalFolder(path) => write!(f, "{}", path),
|
||||
Url::Remote(url) => write!(f, "{}", url),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a logical member of a cluster that provides one or more services.
|
||||
///
|
||||
/// A LogicalHost can represent various roles within the infrastructure, such as:
|
||||
/// - A firewall appliance hosting DHCP, DNS, PXE, and load balancer services
|
||||
/// - A Kubernetes worker node
|
||||
/// - A combined Kubernetes worker and Ceph storage node
|
||||
/// - A control plane node
|
||||
///
|
||||
/// This abstraction focuses on the logical role and services, independent of the physical hardware.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LogicalHost {
|
||||
/// The IP address of this logical host.
|
||||
pub ip: IpAddress,
|
||||
/// The name of this logical host.
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl LogicalHost {
|
||||
/// Creates a list of `LogicalHost` instances.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `number_hosts` - The number of logical hosts to create.
|
||||
/// * `start_ip` - The starting IP address. Each subsequent host's IP will be incremented.
|
||||
/// * `hostname_prefix` - The prefix for the host names. Host names will be in the form `prefix<index>`.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// A `Vec<LogicalHost>` containing the specified number of logical hosts, each with a unique IP and name.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if adding `number_hosts` to `start_ip` exceeds the valid range of IP addresses.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use std::str::FromStr;
|
||||
/// use harmony::topology::{IpAddress, LogicalHost};
|
||||
///
|
||||
/// let start_ip = IpAddress::from_str("192.168.0.20").unwrap();
|
||||
/// let hosts = LogicalHost::create_hosts(3, start_ip, "worker");
|
||||
///
|
||||
/// assert_eq!(hosts.len(), 3);
|
||||
/// assert_eq!(hosts[0].ip, IpAddress::from_str("192.168.0.20").unwrap());
|
||||
/// assert_eq!(hosts[0].name, "worker0");
|
||||
/// assert_eq!(hosts[1].ip, IpAddress::from_str("192.168.0.21").unwrap());
|
||||
/// assert_eq!(hosts[1].name, "worker1");
|
||||
/// assert_eq!(hosts[2].ip, IpAddress::from_str("192.168.0.22").unwrap());
|
||||
/// assert_eq!(hosts[2].name, "worker2");
|
||||
/// ```
|
||||
pub fn create_hosts(
|
||||
number_hosts: u32,
|
||||
start_ip: IpAddress,
|
||||
hostname_prefix: &str,
|
||||
) -> Vec<LogicalHost> {
|
||||
let mut hosts = Vec::with_capacity(number_hosts.try_into().unwrap());
|
||||
for i in 0..number_hosts {
|
||||
let new_ip = increment_ip(start_ip, i).expect("IP address overflow");
|
||||
let name = format!("{}{}", hostname_prefix, i);
|
||||
hosts.push(LogicalHost { ip: new_ip, name });
|
||||
}
|
||||
hosts
|
||||
}
|
||||
}
|
||||
|
||||
/// Increments an IP address by a given value.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `ip` - The starting IP address.
|
||||
/// * `increment` - The amount to add to the IP address.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// A new `IpAddress` that is the result of incrementing the original by `increment`.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function panics if the resulting IP address exceeds the valid range.
|
||||
fn increment_ip(ip: IpAddress, increment: u32) -> Option<IpAddress> {
|
||||
match ip {
|
||||
IpAddress::V4(ipv4) => {
|
||||
let new_ip = u32::from(ipv4) + increment;
|
||||
Some(IpAddress::V4(new_ip.into()))
|
||||
}
|
||||
IpAddress::V6(_) => {
|
||||
todo!("Ipv6 not supported yet")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,296 +0,0 @@
|
||||
use std::{net::Ipv4Addr, str::FromStr};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use harmony_types::net::MacAddress;
|
||||
|
||||
use crate::executors::ExecutorError;
|
||||
|
||||
use super::{IpAddress, LogicalHost};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DHCPStaticEntry {
|
||||
pub name: String,
|
||||
pub mac: MacAddress,
|
||||
pub ip: Ipv4Addr,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for DHCPStaticEntry {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!(
|
||||
"DHCPStaticEntry : name {}, mac {}, ip {}",
|
||||
self.name, self.mac, self.ip
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Firewall: Send + Sync {
|
||||
fn add_rule(&mut self, rule: FirewallRule) -> Result<(), ExecutorError>;
|
||||
fn remove_rule(&mut self, rule_id: &str) -> Result<(), ExecutorError>;
|
||||
fn list_rules(&self) -> Vec<FirewallRule>;
|
||||
fn get_ip(&self) -> IpAddress;
|
||||
fn get_host(&self) -> LogicalHost;
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for dyn Firewall {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!("Firewall {}", self.get_ip()))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NetworkDomain {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait DhcpServer: Send + Sync {
|
||||
async fn add_static_mapping(&self, entry: &DHCPStaticEntry) -> Result<(), ExecutorError>;
|
||||
async fn remove_static_mapping(&self, mac: &MacAddress) -> Result<(), ExecutorError>;
|
||||
async fn list_static_mappings(&self) -> Vec<(MacAddress, IpAddress)>;
|
||||
async fn set_next_server(&self, ip: IpAddress) -> Result<(), ExecutorError>;
|
||||
async fn set_boot_filename(&self, boot_filename: &str) -> Result<(), ExecutorError>;
|
||||
fn get_ip(&self) -> IpAddress;
|
||||
fn get_host(&self) -> LogicalHost;
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError>;
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for dyn DhcpServer {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!("DhcpServer {}", self.get_ip()))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait DnsServer: Send + Sync {
|
||||
async fn register_dhcp_leases(&self, register: bool) -> Result<(), ExecutorError>;
|
||||
async fn register_hosts(&self, hosts: Vec<DnsRecord>) -> Result<(), ExecutorError>;
|
||||
fn remove_record(
|
||||
&mut self,
|
||||
name: &str,
|
||||
record_type: DnsRecordType,
|
||||
) -> Result<(), ExecutorError>;
|
||||
async fn list_records(&self) -> Vec<DnsRecord>;
|
||||
fn get_ip(&self) -> IpAddress;
|
||||
fn get_host(&self) -> LogicalHost;
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError>;
|
||||
async fn ensure_hosts_registered(&self, hosts: Vec<DnsRecord>) -> Result<(), ExecutorError> {
|
||||
let current_hosts = self.list_records().await;
|
||||
let mut hosts_to_register = vec![];
|
||||
|
||||
for host in hosts {
|
||||
if !current_hosts.iter().any(|h| h == &host) {
|
||||
hosts_to_register.push(host);
|
||||
}
|
||||
}
|
||||
|
||||
if !hosts_to_register.is_empty() {
|
||||
self.register_hosts(hosts_to_register).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for dyn DnsServer {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!("DnsServer {}", self.get_ip()))
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FirewallRule {
|
||||
pub id: String,
|
||||
pub source: IpAddress,
|
||||
pub destination: IpAddress,
|
||||
pub port: u16,
|
||||
pub protocol: Protocol,
|
||||
pub action: Action,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Protocol {
|
||||
TCP,
|
||||
UDP,
|
||||
ICMP,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Action {
|
||||
Allow,
|
||||
Deny,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum DnsRecordType {
|
||||
A,
|
||||
AAAA,
|
||||
CNAME,
|
||||
MX,
|
||||
TXT,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for DnsRecordType {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
DnsRecordType::A => write!(f, "A"),
|
||||
DnsRecordType::AAAA => write!(f, "AAAA"),
|
||||
DnsRecordType::CNAME => write!(f, "CNAME"),
|
||||
DnsRecordType::MX => write!(f, "MX"),
|
||||
DnsRecordType::TXT => write!(f, "TXT"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct DnsRecord {
|
||||
pub host: String,
|
||||
pub domain: String,
|
||||
pub record_type: DnsRecordType,
|
||||
pub value: IpAddress,
|
||||
}
|
||||
|
||||
impl FromStr for DnsRecordType {
|
||||
type Err = String;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"A" => Ok(DnsRecordType::A),
|
||||
"AAAA" => Ok(DnsRecordType::AAAA),
|
||||
"CNAME" => Ok(DnsRecordType::CNAME),
|
||||
"MX" => Ok(DnsRecordType::MX),
|
||||
"TXT" => Ok(DnsRecordType::TXT),
|
||||
_ => Err(format!("Unknown DNSRecordType {s}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_ensure_hosts_registered_no_new_hosts() {
|
||||
let server = DummyDnsServer::default();
|
||||
let existing_host = DnsRecord {
|
||||
host: "existing".to_string(),
|
||||
domain: "example.com".to_string(),
|
||||
record_type: DnsRecordType::A,
|
||||
value: IpAddress::V4(Ipv4Addr::new(192, 168, 1, 2)),
|
||||
};
|
||||
|
||||
server
|
||||
.register_hosts(vec![existing_host.clone()])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let new_hosts = vec![
|
||||
existing_host, // already exists
|
||||
];
|
||||
|
||||
server.ensure_hosts_registered(new_hosts).await.unwrap();
|
||||
assert_eq!(server.list_records().await.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_ensure_hosts_registered_with_new_hosts() {
|
||||
let server = DummyDnsServer::default();
|
||||
|
||||
let existing_host = DnsRecord {
|
||||
host: "existing".to_string(),
|
||||
domain: "example.com".to_string(),
|
||||
record_type: DnsRecordType::A,
|
||||
value: IpAddress::V4(Ipv4Addr::new(192, 168, 1, 2)),
|
||||
};
|
||||
|
||||
server
|
||||
.register_hosts(vec![existing_host.clone()])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let new_hosts = vec![
|
||||
existing_host.clone(), // already exists
|
||||
DnsRecord {
|
||||
host: "new".to_string(),
|
||||
domain: "example.com".to_string(),
|
||||
record_type: DnsRecordType::A,
|
||||
value: IpAddress::V4(Ipv4Addr::new(192, 168, 1, 3)),
|
||||
},
|
||||
];
|
||||
|
||||
server.ensure_hosts_registered(new_hosts).await.unwrap();
|
||||
assert_eq!(server.list_records().await.len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_ensure_hosts_registered_no_hosts() {
|
||||
let server = DummyDnsServer::default();
|
||||
|
||||
let new_hosts = vec![];
|
||||
|
||||
server.ensure_hosts_registered(new_hosts).await.unwrap();
|
||||
assert_eq!(server.list_records().await.len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_ensure_existing_host_kept_no_new_host() {
|
||||
let server = DummyDnsServer::default();
|
||||
|
||||
let new_hosts = vec![];
|
||||
|
||||
server.ensure_hosts_registered(new_hosts).await.unwrap();
|
||||
assert_eq!(server.list_records().await.len(), 0);
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl DnsServer for DummyDnsServer {
|
||||
async fn register_dhcp_leases(&self, _register: bool) -> Result<(), ExecutorError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn register_hosts(&self, hosts: Vec<DnsRecord>) -> Result<(), ExecutorError> {
|
||||
self.hosts.write().await.extend(hosts);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_record(
|
||||
&mut self,
|
||||
_name: &str,
|
||||
_record_type: DnsRecordType,
|
||||
) -> Result<(), ExecutorError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list_records(&self) -> Vec<DnsRecord> {
|
||||
self.hosts.read().await.clone()
|
||||
}
|
||||
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
IpAddress::V4(Ipv4Addr::new(192, 168, 0, 1))
|
||||
}
|
||||
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
LogicalHost {
|
||||
ip: self.get_ip(),
|
||||
name: "dummy-host".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct DummyDnsServer {
|
||||
hosts: Arc<RwLock<Vec<DnsRecord>>>,
|
||||
}
|
||||
|
||||
impl Default for DummyDnsServer {
|
||||
fn default() -> Self {
|
||||
DummyDnsServer {
|
||||
hosts: Arc::new(RwLock::new(vec![])),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
use k8s_openapi::NamespaceResourceScope;
|
||||
use kube::{Api, Client, Error, Resource, api::PostParams};
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
pub struct OpenshiftClient {
|
||||
client: Client,
|
||||
}
|
||||
|
||||
impl OpenshiftClient {
|
||||
pub async fn try_default() -> Result<Self, Error> {
|
||||
Ok(Self {
|
||||
client: Client::try_default().await?,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn apply_all<
|
||||
K: Resource<Scope = NamespaceResourceScope>
|
||||
+ std::fmt::Debug
|
||||
+ Sync
|
||||
+ DeserializeOwned
|
||||
+ Default
|
||||
+ serde::Serialize
|
||||
+ Clone,
|
||||
>(
|
||||
&self,
|
||||
resource: &Vec<K>,
|
||||
) -> Result<Vec<K>, kube::Error>
|
||||
where
|
||||
<K as kube::Resource>::DynamicType: Default,
|
||||
{
|
||||
let mut result = vec![];
|
||||
for r in resource.iter() {
|
||||
let api: Api<K> = Api::all(self.client.clone());
|
||||
result.push(api.create(&PostParams::default(), &r).await?);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub async fn apply_namespaced<K>(&self, resource: &Vec<K>) -> Result<K, Error>
|
||||
where
|
||||
K: Resource<Scope = NamespaceResourceScope>
|
||||
+ Clone
|
||||
+ std::fmt::Debug
|
||||
+ DeserializeOwned
|
||||
+ serde::Serialize
|
||||
+ Default,
|
||||
<K as kube::Resource>::DynamicType: Default,
|
||||
{
|
||||
for r in resource.iter() {
|
||||
let api: Api<K> = Api::default_namespaced(self.client.clone());
|
||||
api.create(&PostParams::default(), &r).await?;
|
||||
}
|
||||
todo!("")
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
use cidr::Ipv4Cidr;
|
||||
use derive_new::new;
|
||||
|
||||
use super::{IpAddress, LogicalHost};
|
||||
|
||||
pub trait Router: Send + Sync {
|
||||
fn get_gateway(&self) -> IpAddress;
|
||||
fn get_cidr(&self) -> Ipv4Cidr;
|
||||
fn get_host(&self) -> LogicalHost;
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for dyn Router {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!(
|
||||
"Router Gateway : {}, CIDR : {}",
|
||||
self.get_gateway(),
|
||||
self.get_cidr()
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(new)]
|
||||
pub struct UnmanagedRouter {
|
||||
gateway: IpAddress,
|
||||
cidr: Ipv4Cidr,
|
||||
}
|
||||
|
||||
impl Router for UnmanagedRouter {
|
||||
fn get_gateway(&self) -> IpAddress {
|
||||
self.gateway.clone()
|
||||
}
|
||||
|
||||
fn get_cidr(&self) -> Ipv4Cidr {
|
||||
self.cidr.clone()
|
||||
}
|
||||
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
use crate::executors::ExecutorError;
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::{IpAddress, Url};
|
||||
|
||||
#[async_trait]
|
||||
pub trait TftpServer: Send + Sync {
|
||||
async fn serve_files(&self, url: &Url) -> Result<(), ExecutorError>;
|
||||
fn get_ip(&self) -> IpAddress;
|
||||
|
||||
async fn set_ip(&self, ip: IpAddress) -> Result<(), ExecutorError>;
|
||||
async fn ensure_initialized(&self) -> Result<(), ExecutorError>;
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError>;
|
||||
async fn reload_restart(&self) -> Result<(), ExecutorError>;
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for dyn TftpServer {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!(
|
||||
"TftpServer serving files at {}",
|
||||
self.get_ip()
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
pub mod russh;
|
||||
@@ -1,58 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use std::sync::Arc;
|
||||
|
||||
use russh::{client, keys::key};
|
||||
|
||||
use crate::{
|
||||
domain::executors::{ExecutorError, SshClient},
|
||||
topology::IpAddress,
|
||||
};
|
||||
|
||||
pub struct RusshClient;
|
||||
|
||||
#[async_trait]
|
||||
impl SshClient for RusshClient {
|
||||
async fn test_connection(
|
||||
&self,
|
||||
address: IpAddress,
|
||||
_username: &str,
|
||||
_password: &str,
|
||||
) -> Result<(), crate::domain::executors::ExecutorError> {
|
||||
let config = client::Config::default();
|
||||
let c = Client {};
|
||||
let mut client = client::connect(Arc::new(config), (address, 22), c).await?;
|
||||
match client
|
||||
.authenticate_password("nationtech", "opnsense")
|
||||
.await?
|
||||
{
|
||||
true => Ok(()),
|
||||
false => Err(ExecutorError::AuthenticationError(
|
||||
"ssh authentication failed".to_string(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Client {}
|
||||
|
||||
// More SSH event handlers
|
||||
// can be defined in this trait
|
||||
// In this example, we're only using Channel, so these aren't needed.
|
||||
#[async_trait]
|
||||
impl client::Handler for Client {
|
||||
type Error = ExecutorError;
|
||||
|
||||
async fn check_server_key(
|
||||
&mut self,
|
||||
_server_public_key: &key::PublicKey,
|
||||
) -> Result<bool, Self::Error> {
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<russh::Error> for ExecutorError {
|
||||
fn from(_value: russh::Error) -> Self {
|
||||
// TODO handle various russh errors properly
|
||||
ExecutorError::NetworkError("Russh client error".to_string())
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
use crate::hardware::ManagementInterface;
|
||||
use crate::topology::IpAddress;
|
||||
use derive_new::new;
|
||||
use harmony_types::net::MacAddress;
|
||||
use log::info;
|
||||
|
||||
#[derive(new)]
|
||||
pub struct HPIlo {
|
||||
ip_address: Option<IpAddress>,
|
||||
mac_address: Option<MacAddress>,
|
||||
}
|
||||
|
||||
impl ManagementInterface for HPIlo {
|
||||
fn boot_to_pxe(&self) {
|
||||
info!(
|
||||
"Launching boot to pxe for ip {} mac address {}",
|
||||
&self.ip_address.map_or(String::new(), |i| i.to_string()),
|
||||
&self.mac_address.map_or(String::new(), |m| m.to_string()),
|
||||
);
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_supported_protocol_names(&self) -> String {
|
||||
"ipmi,redfish".to_string()
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
use crate::hardware::ManagementInterface;
|
||||
use derive_new::new;
|
||||
use harmony_types::net::MacAddress;
|
||||
use log::info;
|
||||
|
||||
#[derive(new)]
|
||||
pub struct IntelAmtManagement {
|
||||
mac_address: MacAddress,
|
||||
}
|
||||
|
||||
impl ManagementInterface for IntelAmtManagement {
|
||||
fn boot_to_pxe(&self) {
|
||||
info!("Launching boot to pxe for mac address {}", self.mac_address);
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_supported_protocol_names(&self) -> String {
|
||||
"IntelAMT".to_string()
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
pub mod executors;
|
||||
pub mod hp_ilo;
|
||||
pub mod intel_amt;
|
||||
pub mod opnsense;
|
||||
@@ -1,72 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use harmony_types::net::MacAddress;
|
||||
use log::debug;
|
||||
|
||||
use crate::{
|
||||
executors::ExecutorError,
|
||||
topology::{DHCPStaticEntry, DhcpServer, IpAddress, LogicalHost},
|
||||
};
|
||||
|
||||
use super::OPNSenseFirewall;
|
||||
|
||||
#[async_trait]
|
||||
impl DhcpServer for OPNSenseFirewall {
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
OPNSenseFirewall::commit_config(self).await
|
||||
}
|
||||
|
||||
async fn add_static_mapping(&self, entry: &DHCPStaticEntry) -> Result<(), ExecutorError> {
|
||||
let mac: String = String::from(&entry.mac);
|
||||
|
||||
{
|
||||
let mut writable_opnsense = self.opnsense_config.write().await;
|
||||
writable_opnsense
|
||||
.dhcp()
|
||||
.add_static_mapping(&mac, entry.ip, &entry.name)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
debug!("Registered {:?}", entry);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn remove_static_mapping(&self, _mac: &MacAddress) -> Result<(), ExecutorError> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn list_static_mappings(&self) -> Vec<(MacAddress, IpAddress)> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
OPNSenseFirewall::get_ip(self)
|
||||
}
|
||||
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
self.host.clone()
|
||||
}
|
||||
|
||||
async fn set_next_server(&self, ip: IpAddress) -> Result<(), ExecutorError> {
|
||||
let ipv4 = match ip {
|
||||
std::net::IpAddr::V4(ipv4_addr) => ipv4_addr,
|
||||
std::net::IpAddr::V6(_) => todo!("ipv6 not supported yet"),
|
||||
};
|
||||
{
|
||||
let mut writable_opnsense = self.opnsense_config.write().await;
|
||||
writable_opnsense.dhcp().set_next_server(ipv4);
|
||||
debug!("OPNsense dhcp server set next server {ipv4}");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_boot_filename(&self, boot_filename: &str) -> Result<(), ExecutorError> {
|
||||
{
|
||||
let mut writable_opnsense = self.opnsense_config.write().await;
|
||||
writable_opnsense.dhcp().set_boot_filename(boot_filename);
|
||||
debug!("OPNsense dhcp server set boot filename {boot_filename}");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
use crate::infra::opnsense::Host;
|
||||
use crate::infra::opnsense::IpAddress;
|
||||
use crate::infra::opnsense::LogicalHost;
|
||||
use crate::{
|
||||
executors::ExecutorError,
|
||||
topology::{DnsRecord, DnsServer},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::OPNSenseFirewall;
|
||||
|
||||
#[async_trait]
|
||||
impl DnsServer for OPNSenseFirewall {
|
||||
async fn register_hosts(&self, hosts: Vec<DnsRecord>) -> Result<(), ExecutorError> {
|
||||
let mut writable_opnsense = self.opnsense_config.write().await;
|
||||
let mut dns = writable_opnsense.dns();
|
||||
let hosts = hosts
|
||||
.iter()
|
||||
.map(|h| {
|
||||
Host::new(
|
||||
h.host.clone(),
|
||||
h.domain.clone(),
|
||||
h.record_type.to_string(),
|
||||
h.value.to_string(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
dns.register_hosts(hosts);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_record(
|
||||
&mut self,
|
||||
_name: &str,
|
||||
_record_type: crate::topology::DnsRecordType,
|
||||
) -> Result<(), ExecutorError> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn list_records(&self) -> Vec<crate::topology::DnsRecord> {
|
||||
self.opnsense_config
|
||||
.write()
|
||||
.await
|
||||
.dns()
|
||||
.get_hosts()
|
||||
.iter()
|
||||
.map(|h| DnsRecord {
|
||||
host: h.hostname.clone(),
|
||||
domain: h.domain.clone(),
|
||||
record_type: h
|
||||
.rr
|
||||
.parse()
|
||||
.expect("received invalid record type {h.rr} from opnsense"),
|
||||
value: h
|
||||
.server
|
||||
.parse()
|
||||
.expect("received invalid ipv4 record from opnsense {h.server}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
OPNSenseFirewall::get_ip(&self)
|
||||
}
|
||||
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
self.host.clone()
|
||||
}
|
||||
|
||||
async fn register_dhcp_leases(&self, register: bool) -> Result<(), ExecutorError> {
|
||||
let mut writable_opnsense = self.opnsense_config.write().await;
|
||||
let mut dns = writable_opnsense.dns();
|
||||
dns.register_dhcp_leases(register);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
let opnsense = self.opnsense_config.read().await;
|
||||
|
||||
opnsense
|
||||
.save()
|
||||
.await
|
||||
.map_err(|e| ExecutorError::UnexpectedError(e.to_string()))?;
|
||||
|
||||
opnsense
|
||||
.restart_dns()
|
||||
.await
|
||||
.map_err(|e| ExecutorError::UnexpectedError(e.to_string()))
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
use crate::{
|
||||
executors::ExecutorError,
|
||||
topology::{Firewall, FirewallRule, IpAddress, LogicalHost},
|
||||
};
|
||||
|
||||
use super::OPNSenseFirewall;
|
||||
|
||||
impl Firewall for OPNSenseFirewall {
|
||||
fn add_rule(&mut self, _rule: FirewallRule) -> Result<(), ExecutorError> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn remove_rule(&mut self, _rule_id: &str) -> Result<(), ExecutorError> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn list_rules(&self) -> Vec<FirewallRule> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
OPNSenseFirewall::get_ip(self)
|
||||
}
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
self.host.clone()
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use log::info;
|
||||
|
||||
use crate::{
|
||||
executors::ExecutorError,
|
||||
topology::{HttpServer, IpAddress, Url},
|
||||
};
|
||||
|
||||
use super::OPNSenseFirewall;
|
||||
|
||||
#[async_trait]
|
||||
impl HttpServer for OPNSenseFirewall {
|
||||
async fn serve_files(&self, url: &Url) -> Result<(), ExecutorError> {
|
||||
let http_root_path = "/usr/local/http";
|
||||
|
||||
let config = self.opnsense_config.read().await;
|
||||
info!("Uploading files from url {url} to {http_root_path}");
|
||||
match url {
|
||||
Url::LocalFolder(path) => {
|
||||
config
|
||||
.upload_files(path, http_root_path)
|
||||
.await
|
||||
.map_err(|e| ExecutorError::UnexpectedError(e.to_string()))?;
|
||||
}
|
||||
Url::Remote(_url) => todo!(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
todo!();
|
||||
}
|
||||
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
OPNSenseFirewall::commit_config(self).await
|
||||
}
|
||||
|
||||
async fn reload_restart(&self) -> Result<(), ExecutorError> {
|
||||
self.opnsense_config
|
||||
.write()
|
||||
.await
|
||||
.caddy()
|
||||
.reload_restart()
|
||||
.await
|
||||
.map_err(|e| ExecutorError::UnexpectedError(e.to_string()))
|
||||
}
|
||||
|
||||
async fn ensure_initialized(&self) -> Result<(), ExecutorError> {
|
||||
let mut config = self.opnsense_config.write().await;
|
||||
let caddy = config.caddy();
|
||||
if let None = caddy.get_full_config() {
|
||||
info!("Http config not available in opnsense config, installing package");
|
||||
config.install_package("os-caddy").await.map_err(|e| {
|
||||
ExecutorError::UnexpectedError(format!(
|
||||
"Executor failed when trying to install os-caddy package with error {e:?}"
|
||||
))
|
||||
})?;
|
||||
} else {
|
||||
info!("Http config available in opnsense config, assuming it is already installed");
|
||||
}
|
||||
info!("Adding custom caddy config files");
|
||||
config
|
||||
.upload_files(
|
||||
"../../../watchguard/caddy_config",
|
||||
"/usr/local/etc/caddy/caddy.d/",
|
||||
)
|
||||
.await
|
||||
.map_err(|e| ExecutorError::UnexpectedError(e.to_string()))?;
|
||||
|
||||
info!("Enabling http server");
|
||||
config.caddy().enable(true);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,444 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use log::{debug, info, warn};
|
||||
use opnsense_config_xml::{Frontend, HAProxy, HAProxyBackend, HAProxyHealthCheck, HAProxyServer};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
executors::ExecutorError,
|
||||
topology::{
|
||||
BackendServer, HealthCheck, HttpMethod, HttpStatusCode, IpAddress, LoadBalancer,
|
||||
LoadBalancerService, LogicalHost,
|
||||
},
|
||||
};
|
||||
|
||||
use super::OPNSenseFirewall;
|
||||
|
||||
#[async_trait]
|
||||
impl LoadBalancer for OPNSenseFirewall {
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
OPNSenseFirewall::get_ip(self)
|
||||
}
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
self.host.clone()
|
||||
}
|
||||
|
||||
async fn add_service(&self, service: &LoadBalancerService) -> Result<(), ExecutorError> {
|
||||
warn!(
|
||||
"TODO : the current implementation does not check / cleanup / merge with existing haproxy services properly. Make sure to manually verify that the configuration is correct after executing any operation here"
|
||||
);
|
||||
let mut config = self.opnsense_config.write().await;
|
||||
let (frontend, backend, servers, healthcheck) =
|
||||
harmony_load_balancer_service_to_haproxy_xml(service);
|
||||
let mut load_balancer = config.load_balancer();
|
||||
load_balancer.add_backend(backend);
|
||||
load_balancer.add_frontend(frontend);
|
||||
load_balancer.add_servers(servers);
|
||||
if let Some(healthcheck) = healthcheck {
|
||||
load_balancer.add_healthcheck(healthcheck);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn remove_service(&self, service: &LoadBalancerService) -> Result<(), ExecutorError> {
|
||||
todo!("Remove service not implemented yet {service:?}")
|
||||
}
|
||||
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
OPNSenseFirewall::commit_config(self).await
|
||||
}
|
||||
|
||||
async fn reload_restart(&self) -> Result<(), ExecutorError> {
|
||||
self.opnsense_config
|
||||
.write()
|
||||
.await
|
||||
.load_balancer()
|
||||
.reload_restart()
|
||||
.await
|
||||
.map_err(|e| ExecutorError::UnexpectedError(e.to_string()))
|
||||
}
|
||||
|
||||
async fn ensure_initialized(&self) -> Result<(), ExecutorError> {
|
||||
let mut config = self.opnsense_config.write().await;
|
||||
let load_balancer = config.load_balancer();
|
||||
if let Some(config) = load_balancer.get_full_config() {
|
||||
debug!(
|
||||
"HAProxy config available in opnsense config, assuming it is already installed, {config:?}"
|
||||
);
|
||||
} else {
|
||||
config.install_package("os-haproxy").await.map_err(|e| {
|
||||
ExecutorError::UnexpectedError(format!(
|
||||
"Executor failed when trying to install os-haproxy package with error {e:?}"
|
||||
))
|
||||
})?;
|
||||
}
|
||||
|
||||
config.load_balancer().enable(true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list_services(&self) -> Vec<LoadBalancerService> {
|
||||
let mut config = self.opnsense_config.write().await;
|
||||
let load_balancer = config.load_balancer();
|
||||
let haproxy_xml_config = load_balancer.get_full_config();
|
||||
haproxy_xml_config_to_harmony_loadbalancer(haproxy_xml_config)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn haproxy_xml_config_to_harmony_loadbalancer(
|
||||
haproxy: &Option<HAProxy>,
|
||||
) -> Vec<LoadBalancerService> {
|
||||
let haproxy = match haproxy {
|
||||
Some(haproxy) => haproxy,
|
||||
None => return vec![],
|
||||
};
|
||||
|
||||
haproxy
|
||||
.frontends
|
||||
.frontend
|
||||
.iter()
|
||||
.map(|frontend| {
|
||||
let mut backend_servers = vec![];
|
||||
let matching_backend = haproxy
|
||||
.backends
|
||||
.backends
|
||||
.iter()
|
||||
.find(|b| b.uuid == frontend.default_backend);
|
||||
|
||||
let mut health_check = None;
|
||||
match matching_backend {
|
||||
Some(backend) => {
|
||||
backend_servers.append(&mut get_servers_for_backend(backend, haproxy));
|
||||
health_check = get_health_check_for_backend(backend, haproxy);
|
||||
}
|
||||
None => {
|
||||
warn!(
|
||||
"HAProxy config could not find a matching backend for frontend {:?}",
|
||||
frontend
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
LoadBalancerService {
|
||||
backend_servers,
|
||||
listening_port: frontend.bind.parse().expect(&format!(
|
||||
"HAProxy frontend address should be a valid SocketAddr, got {}",
|
||||
frontend.bind
|
||||
)),
|
||||
health_check,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn get_servers_for_backend(
|
||||
backend: &HAProxyBackend,
|
||||
haproxy: &HAProxy,
|
||||
) -> Vec<BackendServer> {
|
||||
let backend_servers: Vec<&str> = match &backend.linked_servers.content {
|
||||
Some(linked_servers) => linked_servers.split(',').collect(),
|
||||
None => {
|
||||
info!("No server defined for HAProxy backend {:?}", backend);
|
||||
return vec![];
|
||||
}
|
||||
};
|
||||
haproxy
|
||||
.servers
|
||||
.servers
|
||||
.iter()
|
||||
.filter_map(|server| {
|
||||
if backend_servers.contains(&server.uuid.as_str()) {
|
||||
return Some(BackendServer {
|
||||
address: server.address.clone(),
|
||||
port: server.port,
|
||||
});
|
||||
}
|
||||
None
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn get_health_check_for_backend(
|
||||
backend: &HAProxyBackend,
|
||||
haproxy: &HAProxy,
|
||||
) -> Option<HealthCheck> {
|
||||
let health_check_uuid = match &backend.health_check.content {
|
||||
Some(uuid) => uuid,
|
||||
None => return None,
|
||||
};
|
||||
|
||||
let haproxy_health_check = match haproxy
|
||||
.healthchecks
|
||||
.healthchecks
|
||||
.iter()
|
||||
.find(|h| &h.uuid == health_check_uuid)
|
||||
{
|
||||
Some(health_check) => health_check,
|
||||
None => return None,
|
||||
};
|
||||
|
||||
let binding = haproxy_health_check.health_check_type.to_uppercase();
|
||||
let uppercase = binding.as_str();
|
||||
match uppercase {
|
||||
"TCP" => {
|
||||
if let Some(checkport) = haproxy_health_check.checkport.content.as_ref() {
|
||||
if checkport.len() > 0 {
|
||||
return Some(HealthCheck::TCP(Some(checkport.parse().expect(&format!(
|
||||
"HAProxy check port should be a valid port number, got {checkport}"
|
||||
)))));
|
||||
}
|
||||
}
|
||||
return Some(HealthCheck::TCP(None));
|
||||
}
|
||||
"HTTP" => {
|
||||
let path: String = haproxy_health_check
|
||||
.http_uri
|
||||
.content
|
||||
.clone()
|
||||
.unwrap_or_default();
|
||||
let method: HttpMethod = haproxy_health_check
|
||||
.http_method
|
||||
.content
|
||||
.clone()
|
||||
.unwrap_or_default()
|
||||
.into();
|
||||
let status_code: HttpStatusCode = HttpStatusCode::Success2xx;
|
||||
Some(HealthCheck::HTTP(path, method, status_code))
|
||||
}
|
||||
_ => panic!("Received unsupported health check type {}", uppercase),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn harmony_load_balancer_service_to_haproxy_xml(
|
||||
service: &LoadBalancerService,
|
||||
) -> (
|
||||
Frontend,
|
||||
HAProxyBackend,
|
||||
Vec<HAProxyServer>,
|
||||
Option<HAProxyHealthCheck>,
|
||||
) {
|
||||
// Here we have to build :
|
||||
// One frontend
|
||||
// One backend
|
||||
// One Option<healthcheck>
|
||||
// Vec of servers
|
||||
//
|
||||
// Then merge then with haproxy config individually
|
||||
//
|
||||
// We also have to take into account that it is entirely possible that a backe uses a server
|
||||
// with the same definition as in another backend. So when creating a new backend, we must not
|
||||
// blindly create new servers because the backend does not exist yet. Even if it is a new
|
||||
// backend, it may very well reuse existing servers
|
||||
//
|
||||
// Also we need to support router integration for port forwarding on WAN as a strategy to
|
||||
// handle dyndns
|
||||
// server is standalone
|
||||
// backend points on server
|
||||
// backend points to health check
|
||||
// frontend points to backend
|
||||
let healthcheck = if let Some(health_check) = &service.health_check {
|
||||
match health_check {
|
||||
HealthCheck::HTTP(path, http_method, _http_status_code) => {
|
||||
let haproxy_check = HAProxyHealthCheck {
|
||||
name: format!("HTTP_{http_method}_{path}"),
|
||||
uuid: Uuid::new_v4().to_string(),
|
||||
http_method: http_method.to_string().into(),
|
||||
health_check_type: "http".to_string(),
|
||||
http_uri: path.clone().into(),
|
||||
interval: "2s".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
Some(haproxy_check)
|
||||
}
|
||||
HealthCheck::TCP(port) => {
|
||||
let (port, port_name) = match port {
|
||||
Some(port) => (Some(port.to_string()), port.to_string()),
|
||||
None => (None, "serverport".to_string()),
|
||||
};
|
||||
|
||||
let haproxy_check = HAProxyHealthCheck {
|
||||
name: format!("TCP_{port_name}"),
|
||||
uuid: Uuid::new_v4().to_string(),
|
||||
health_check_type: "tcp".to_string(),
|
||||
checkport: port.into(),
|
||||
interval: "2s".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
Some(haproxy_check)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
debug!("Built healthcheck {healthcheck:?}");
|
||||
|
||||
let servers: Vec<HAProxyServer> = service
|
||||
.backend_servers
|
||||
.iter()
|
||||
.map(server_to_haproxy_server)
|
||||
.collect();
|
||||
debug!("Built servers {servers:?}");
|
||||
|
||||
let mut backend = HAProxyBackend {
|
||||
uuid: Uuid::new_v4().to_string(),
|
||||
enabled: 1,
|
||||
name: format!("backend_{}", service.listening_port),
|
||||
algorithm: "roundrobin".to_string(),
|
||||
random_draws: Some(2),
|
||||
stickiness_expire: "30m".to_string(),
|
||||
stickiness_size: "50k".to_string(),
|
||||
stickiness_conn_rate_period: "10s".to_string(),
|
||||
stickiness_sess_rate_period: "10s".to_string(),
|
||||
stickiness_http_req_rate_period: "10s".to_string(),
|
||||
stickiness_http_err_rate_period: "10s".to_string(),
|
||||
stickiness_bytes_in_rate_period: "1m".to_string(),
|
||||
stickiness_bytes_out_rate_period: "1m".to_string(),
|
||||
mode: "tcp".to_string(), // TODO do not depend on health check here
|
||||
..Default::default()
|
||||
};
|
||||
info!("HAPRoxy backend algorithm is currently hardcoded to roundrobin");
|
||||
|
||||
if let Some(hcheck) = &healthcheck {
|
||||
backend.health_check_enabled = 1;
|
||||
backend.health_check = hcheck.uuid.clone().into();
|
||||
}
|
||||
|
||||
backend.linked_servers = servers
|
||||
.iter()
|
||||
.map(|s| s.uuid.as_str())
|
||||
.collect::<Vec<&str>>()
|
||||
.join(",")
|
||||
.into();
|
||||
debug!("Built backend {backend:?}");
|
||||
|
||||
let frontend = Frontend {
|
||||
uuid: uuid::Uuid::new_v4().to_string(),
|
||||
enabled: 1,
|
||||
name: format!("frontend_{}", service.listening_port),
|
||||
bind: service.listening_port.to_string(),
|
||||
mode: "tcp".to_string(), // TODO do not depend on health check here
|
||||
default_backend: backend.uuid.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
info!("HAPRoxy frontend and backend mode currently hardcoded to tcp");
|
||||
|
||||
debug!("Built frontend {frontend:?}");
|
||||
(frontend, backend, servers, healthcheck)
|
||||
}
|
||||
|
||||
fn server_to_haproxy_server(server: &BackendServer) -> HAProxyServer {
|
||||
HAProxyServer {
|
||||
uuid: Uuid::new_v4().to_string(),
|
||||
name: format!("{}_{}", &server.address, &server.port),
|
||||
enabled: 1,
|
||||
address: server.address.clone(),
|
||||
port: server.port,
|
||||
mode: "active".to_string(),
|
||||
server_type: "static".to_string(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use opnsense_config_xml::HAProxyServer;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_get_servers_for_backend_with_linked_servers() {
|
||||
// Create a backend with linked servers
|
||||
let mut backend = HAProxyBackend::default();
|
||||
backend.linked_servers.content = Some("server1,server2".to_string());
|
||||
|
||||
// Create an HAProxy instance with servers
|
||||
let mut haproxy = HAProxy::default();
|
||||
let mut server = HAProxyServer::default();
|
||||
server.uuid = "server1".to_string();
|
||||
server.address = "192.168.1.1".to_string();
|
||||
server.port = 80;
|
||||
|
||||
haproxy.servers.servers.push(server);
|
||||
let mut server = HAProxyServer::default();
|
||||
server.uuid = "server3".to_string();
|
||||
server.address = "192.168.1.3".to_string();
|
||||
server.port = 8080;
|
||||
|
||||
// Call the function
|
||||
let result = get_servers_for_backend(&backend, &haproxy);
|
||||
|
||||
// Check the result
|
||||
assert_eq!(result, vec![BackendServer {
|
||||
address: "192.168.1.1".to_string(),
|
||||
port: 80,
|
||||
},]);
|
||||
}
|
||||
#[test]
|
||||
fn test_get_servers_for_backend_no_linked_servers() {
|
||||
// Create a backend with no linked servers
|
||||
let backend = HAProxyBackend::default();
|
||||
// Create an HAProxy instance with servers
|
||||
let mut haproxy = HAProxy::default();
|
||||
let mut server = HAProxyServer::default();
|
||||
server.uuid = "server1".to_string();
|
||||
server.address = "192.168.1.1".to_string();
|
||||
server.port = 80;
|
||||
haproxy.servers.servers.push(server);
|
||||
// Call the function
|
||||
let result = get_servers_for_backend(&backend, &haproxy);
|
||||
// Check the result
|
||||
assert_eq!(result, vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_servers_for_backend_no_matching_servers() {
|
||||
// Create a backend with linked servers that do not match any in HAProxy
|
||||
let mut backend = HAProxyBackend::default();
|
||||
backend.linked_servers.content = Some("server4,server5".to_string());
|
||||
// Create an HAProxy instance with servers
|
||||
let mut haproxy = HAProxy::default();
|
||||
let mut server = HAProxyServer::default();
|
||||
server.uuid = "server1".to_string();
|
||||
server.address = "192.168.1.1".to_string();
|
||||
server.port = 80;
|
||||
haproxy.servers.servers.push(server);
|
||||
// Call the function
|
||||
let result = get_servers_for_backend(&backend, &haproxy);
|
||||
// Check the result
|
||||
assert_eq!(result, vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_servers_for_backend_multiple_linked_servers() {
|
||||
// Create a backend with multiple linked servers
|
||||
let mut backend = HAProxyBackend::default();
|
||||
backend.linked_servers.content = Some("server1,server2".to_string());
|
||||
// Create an HAProxy instance with matching servers
|
||||
let mut haproxy = HAProxy::default();
|
||||
let mut server = HAProxyServer::default();
|
||||
server.uuid = "server1".to_string();
|
||||
server.address = "some-hostname.test.mcd".to_string();
|
||||
server.port = 80;
|
||||
haproxy.servers.servers.push(server);
|
||||
let mut server = HAProxyServer::default();
|
||||
server.uuid = "server2".to_string();
|
||||
server.address = "192.168.1.2".to_string();
|
||||
server.port = 8080;
|
||||
haproxy.servers.servers.push(server);
|
||||
// Call the function
|
||||
let result = get_servers_for_backend(&backend, &haproxy);
|
||||
// Check the result
|
||||
assert_eq!(result, vec![
|
||||
BackendServer {
|
||||
address: "some-hostname.test.mcd".to_string(),
|
||||
port: 80,
|
||||
},
|
||||
BackendServer {
|
||||
address: "192.168.1.2".to_string(),
|
||||
port: 8080,
|
||||
},
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
use crate::hardware::ManagementInterface;
|
||||
use derive_new::new;
|
||||
|
||||
#[derive(new)]
|
||||
pub struct OPNSenseManagementInterface {}
|
||||
|
||||
impl ManagementInterface for OPNSenseManagementInterface {
|
||||
fn boot_to_pxe(&self) {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_supported_protocol_names(&self) -> String {
|
||||
"OPNSenseSSH".to_string()
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
mod dhcp;
|
||||
mod dns;
|
||||
mod firewall;
|
||||
mod http;
|
||||
mod load_balancer;
|
||||
mod management;
|
||||
mod tftp;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use management::*;
|
||||
use opnsense_config_xml::Host;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::{
|
||||
executors::ExecutorError,
|
||||
topology::{IpAddress, LogicalHost},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OPNSenseFirewall {
|
||||
opnsense_config: Arc<RwLock<opnsense_config::Config>>,
|
||||
host: LogicalHost,
|
||||
}
|
||||
|
||||
impl OPNSenseFirewall {
|
||||
pub fn get_ip(&self) -> IpAddress {
|
||||
self.host.ip
|
||||
}
|
||||
|
||||
pub async fn new(host: LogicalHost, port: Option<u16>, username: &str, password: &str) -> Self {
|
||||
Self {
|
||||
opnsense_config: Arc::new(RwLock::new(
|
||||
opnsense_config::Config::from_credentials(host.ip, port, username, password).await,
|
||||
)),
|
||||
host,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_opnsense_config(&self) -> Arc<RwLock<opnsense_config::Config>> {
|
||||
self.opnsense_config.clone()
|
||||
}
|
||||
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
self.opnsense_config
|
||||
.read()
|
||||
.await
|
||||
.apply()
|
||||
.await
|
||||
.map_err(|e| ExecutorError::UnexpectedError(e.to_string()))
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use log::info;
|
||||
|
||||
use crate::{
|
||||
executors::ExecutorError,
|
||||
topology::{IpAddress, TftpServer, Url},
|
||||
};
|
||||
|
||||
use super::OPNSenseFirewall;
|
||||
|
||||
#[async_trait]
|
||||
impl TftpServer for OPNSenseFirewall {
|
||||
async fn serve_files(&self, url: &Url) -> Result<(), ExecutorError> {
|
||||
let tftp_root_path = "/usr/local/tftp";
|
||||
|
||||
let config = self.opnsense_config.read().await;
|
||||
info!("Uploading files from url {url} to {tftp_root_path}");
|
||||
match url {
|
||||
Url::LocalFolder(path) => {
|
||||
config
|
||||
.upload_files(path, tftp_root_path)
|
||||
.await
|
||||
.map_err(|e| ExecutorError::UnexpectedError(e.to_string()))?;
|
||||
}
|
||||
Url::Remote(url) => todo!("This url is not supported yet {url}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn set_ip(&self, ip: IpAddress) -> Result<(), ExecutorError> {
|
||||
info!("Setting listen_ip to {}", &ip);
|
||||
self.opnsense_config
|
||||
.write()
|
||||
.await
|
||||
.tftp()
|
||||
.listen_ip(&ip.to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
OPNSenseFirewall::commit_config(self).await
|
||||
}
|
||||
|
||||
async fn reload_restart(&self) -> Result<(), ExecutorError> {
|
||||
self.opnsense_config
|
||||
.write()
|
||||
.await
|
||||
.tftp()
|
||||
.reload_restart()
|
||||
.await
|
||||
.map_err(|e| ExecutorError::UnexpectedError(e.to_string()))
|
||||
}
|
||||
|
||||
async fn ensure_initialized(&self) -> Result<(), ExecutorError> {
|
||||
let mut config = self.opnsense_config.write().await;
|
||||
let tftp = config.tftp();
|
||||
if let None = tftp.get_full_config() {
|
||||
info!("Tftp config not available in opnsense config, installing package");
|
||||
config.install_package("os-tftp").await.map_err(|e| {
|
||||
ExecutorError::UnexpectedError(format!(
|
||||
"Executor failed when trying to install os-tftp package with error {e:?}"
|
||||
))
|
||||
})?;
|
||||
} else {
|
||||
info!("Tftp config available in opnsense config, assuming it is already installed");
|
||||
}
|
||||
|
||||
info!("Enabling tftp server");
|
||||
config.tftp().enable(true);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
mod domain;
|
||||
pub use domain::*;
|
||||
pub mod infra;
|
||||
pub mod modules;
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {}
|
||||
@@ -1,16 +0,0 @@
|
||||
use rust_ipmi::{IPMIClient, NetFn};
|
||||
fn main() {
|
||||
let connection_string = "192.168.11.132:443";
|
||||
println!("Hello, world! {}", connection_string);
|
||||
let mut client: IPMIClient = IPMIClient::new(connection_string).expect("Failed to create ipmi client");
|
||||
|
||||
client.establish_connection("root", "YOUR_PASSWORD")
|
||||
.expect("Failed to establish connection with the BMC");
|
||||
|
||||
let response = client.send_raw_request(NetFn::App, 0x3b, Some(vec![0x04]));
|
||||
|
||||
match response {
|
||||
Ok(response) => println!("{}", response),
|
||||
Err(err) => println!("Got error {:?}", err),
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
use libredfish::{Config, Redfish};
|
||||
use reqwest::blocking::Client;
|
||||
|
||||
pub fn main() {
|
||||
let client = Client::builder().danger_accept_invalid_certs(true).build().expect("Failed to build reqwest client");
|
||||
let redfish = Redfish::new(
|
||||
client,
|
||||
Config {
|
||||
user: Some(String::from("Administrator")),
|
||||
endpoint: String::from("10.10.8.104/redfish/v1"),
|
||||
// password: Some(String::from("YOUR_PASSWORD")),
|
||||
password: Some(String::from("wrongpass")),
|
||||
port: None,
|
||||
},
|
||||
);
|
||||
|
||||
let response = redfish.get_power_status().expect("Failed redfish request");
|
||||
|
||||
println!("Got power {:?}", response);
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use derive_new::new;
|
||||
use log::info;
|
||||
|
||||
use crate::{
|
||||
domain::{data::Version, interpret::InterpretStatus},
|
||||
interpret::{Interpret, InterpretError, InterpretName, Outcome},
|
||||
inventory::Inventory,
|
||||
topology::{DHCPStaticEntry, HAClusterTopology, HostBinding, IpAddress},
|
||||
};
|
||||
|
||||
use crate::domain::score::Score;
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct DhcpScore {
|
||||
pub host_binding: Vec<HostBinding>,
|
||||
pub next_server: Option<IpAddress>,
|
||||
pub boot_filename: Option<String>,
|
||||
}
|
||||
|
||||
impl Score for DhcpScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret> {
|
||||
Box::new(DhcpInterpret::new(self.clone()))
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"DhcpScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
// https://docs.opnsense.org/manual/dhcp.html#advanced-settings
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DhcpInterpret {
|
||||
score: DhcpScore,
|
||||
version: Version,
|
||||
status: InterpretStatus,
|
||||
}
|
||||
|
||||
impl DhcpInterpret {
|
||||
pub fn new(score: DhcpScore) -> Self {
|
||||
let version = Version::from("1.0.0").expect("Version should be valid");
|
||||
|
||||
Self {
|
||||
version,
|
||||
score,
|
||||
status: InterpretStatus::QUEUED,
|
||||
}
|
||||
}
|
||||
async fn add_static_entries(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let dhcp_entries: Vec<DHCPStaticEntry> = self
|
||||
.score
|
||||
.host_binding
|
||||
.iter()
|
||||
.map(|binding| {
|
||||
let ip = match binding.logical_host.ip {
|
||||
std::net::IpAddr::V4(ipv4) => ipv4,
|
||||
std::net::IpAddr::V6(_) => {
|
||||
unimplemented!("DHCPStaticEntry only supports ipv4 at the moment")
|
||||
}
|
||||
};
|
||||
|
||||
DHCPStaticEntry {
|
||||
name: binding.logical_host.name.clone(),
|
||||
mac: binding.physical_host.cluster_mac(),
|
||||
ip,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
info!("DHCPStaticEntry : {:?}", dhcp_entries);
|
||||
|
||||
let dhcp_server = Arc::new(topology.dhcp_server.clone());
|
||||
info!("DHCP server : {:?}", dhcp_server);
|
||||
|
||||
let number_new_entries = dhcp_entries.len();
|
||||
|
||||
for entry in dhcp_entries.into_iter() {
|
||||
match dhcp_server.add_static_mapping(&entry).await {
|
||||
Ok(_) => info!("Successfully registered DHCPStaticEntry {}", entry),
|
||||
Err(_) => todo!(),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Outcome::new(
|
||||
InterpretStatus::SUCCESS,
|
||||
format!("Dhcp Interpret registered {} entries", number_new_entries),
|
||||
))
|
||||
}
|
||||
|
||||
async fn set_pxe_options(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let next_server_outcome = match self.score.next_server {
|
||||
Some(next_server) => {
|
||||
let dhcp_server = Arc::new(topology.dhcp_server.clone());
|
||||
dhcp_server.set_next_server(next_server).await?;
|
||||
Outcome::new(
|
||||
InterpretStatus::SUCCESS,
|
||||
format!("Dhcp Interpret Set next boot to {next_server}"),
|
||||
)
|
||||
}
|
||||
None => Outcome::noop(),
|
||||
};
|
||||
|
||||
let boot_filename_outcome = match &self.score.boot_filename {
|
||||
Some(boot_filename) => {
|
||||
let dhcp_server = Arc::new(topology.dhcp_server.clone());
|
||||
dhcp_server.set_boot_filename(&boot_filename).await?;
|
||||
Outcome::new(
|
||||
InterpretStatus::SUCCESS,
|
||||
format!("Dhcp Interpret Set boot filename to {boot_filename}"),
|
||||
)
|
||||
}
|
||||
None => Outcome::noop(),
|
||||
};
|
||||
|
||||
if next_server_outcome.status == InterpretStatus::NOOP
|
||||
&& boot_filename_outcome.status == InterpretStatus::NOOP
|
||||
{
|
||||
return Ok(Outcome::noop());
|
||||
}
|
||||
|
||||
Ok(Outcome::new(
|
||||
InterpretStatus::SUCCESS,
|
||||
format!(
|
||||
"Dhcp Interpret Set next boot to {:?} and boot_filename to {:?}",
|
||||
self.score.boot_filename, self.score.boot_filename
|
||||
),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Interpret for DhcpInterpret {
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::OPNSenseDHCP
|
||||
}
|
||||
|
||||
fn get_version(&self) -> crate::domain::data::Version {
|
||||
self.version.clone()
|
||||
}
|
||||
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
self.status.clone()
|
||||
}
|
||||
|
||||
fn get_children(&self) -> Vec<crate::domain::data::Id> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn execute(
|
||||
&self,
|
||||
inventory: &Inventory,
|
||||
topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
info!("Executing {} on inventory {inventory:?}", self.get_name());
|
||||
|
||||
self.set_pxe_options(inventory, topology).await?;
|
||||
|
||||
self.add_static_entries(inventory, topology).await?;
|
||||
|
||||
topology.dhcp_server.commit_config().await?;
|
||||
|
||||
Ok(Outcome::new(
|
||||
InterpretStatus::SUCCESS,
|
||||
format!("Dhcp Interpret execution successful"),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use derive_new::new;
|
||||
use log::info;
|
||||
|
||||
use crate::{
|
||||
data::Version,
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
topology::{DnsRecord, HAClusterTopology},
|
||||
};
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct DnsScore {
|
||||
dns_entries: Vec<DnsRecord>,
|
||||
register_dhcp_leases: Option<bool>,
|
||||
}
|
||||
|
||||
impl Score for DnsScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret> {
|
||||
Box::new(DnsInterpret::new(self.clone()))
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"DnsScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
// https://docs.opnsense.org/manual/dhcp.html#advanced-settings
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DnsInterpret {
|
||||
score: DnsScore,
|
||||
version: Version,
|
||||
status: InterpretStatus,
|
||||
}
|
||||
|
||||
impl DnsInterpret {
|
||||
pub fn new(score: DnsScore) -> Self {
|
||||
let version = Version::from("1.0.0").expect("Version should be valid");
|
||||
|
||||
Self {
|
||||
version,
|
||||
score,
|
||||
status: InterpretStatus::QUEUED,
|
||||
}
|
||||
}
|
||||
async fn serve_dhcp_entries(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let dns = topology.dns_server.clone();
|
||||
if let Some(register) = self.score.register_dhcp_leases {
|
||||
dns.register_dhcp_leases(register).await?;
|
||||
}
|
||||
|
||||
Ok(Outcome::new(
|
||||
InterpretStatus::SUCCESS,
|
||||
"DNS Interpret execution successfull".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn ensure_hosts_registered(
|
||||
&self,
|
||||
topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let entries = &self.score.dns_entries;
|
||||
topology
|
||||
.dns_server
|
||||
.ensure_hosts_registered(entries.clone())
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::new(
|
||||
InterpretStatus::SUCCESS,
|
||||
format!(
|
||||
"DnsInterpret registered {} hosts successfully",
|
||||
entries.len()
|
||||
),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Interpret for DnsInterpret {
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::OPNSenseDns
|
||||
}
|
||||
|
||||
fn get_version(&self) -> crate::domain::data::Version {
|
||||
self.version.clone()
|
||||
}
|
||||
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
self.status.clone()
|
||||
}
|
||||
|
||||
fn get_children(&self) -> Vec<crate::domain::data::Id> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn execute(
|
||||
&self,
|
||||
inventory: &Inventory,
|
||||
topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
info!("Executing {} on inventory {inventory:?}", self.get_name());
|
||||
|
||||
self.serve_dhcp_entries(inventory, topology).await?;
|
||||
self.ensure_hosts_registered(&topology).await?;
|
||||
|
||||
topology.dns_server.commit_config().await?;
|
||||
|
||||
Ok(Outcome::new(
|
||||
InterpretStatus::SUCCESS,
|
||||
format!("Dns Interpret execution successful"),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::{
|
||||
data::Version,
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
topology::HAClusterTopology,
|
||||
};
|
||||
|
||||
/// Score that always errors. This is only useful for development/testing purposes. It does nothing
|
||||
/// except returning Err(InterpretError) when interpreted.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ErrorScore;
|
||||
|
||||
impl Score for ErrorScore {
|
||||
fn create_interpret(&self) -> Box<dyn crate::interpret::Interpret> {
|
||||
Box::new(DummyInterpret {
|
||||
result: Err(InterpretError::new("Error Score default error".to_string())),
|
||||
status: InterpretStatus::QUEUED,
|
||||
})
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"ErrorScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Score that always succeeds. This is only useful for development/testing purposes. It does nothing
|
||||
/// except returning Ok(Outcome::success) when interpreted.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SuccessScore;
|
||||
|
||||
impl Score for SuccessScore {
|
||||
fn create_interpret(&self) -> Box<dyn crate::interpret::Interpret> {
|
||||
Box::new(DummyInterpret {
|
||||
result: Ok(Outcome::success("SuccessScore default success".to_string())),
|
||||
status: InterpretStatus::QUEUED,
|
||||
})
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"SuccessScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// An interpret that only returns the result it is given when built. It does nothing else. Only
|
||||
/// useful for development/testing purposes.
|
||||
#[derive(Debug)]
|
||||
struct DummyInterpret {
|
||||
status: InterpretStatus,
|
||||
result: Result<Outcome, InterpretError>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Interpret for DummyInterpret {
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::Dummy
|
||||
}
|
||||
|
||||
fn get_version(&self) -> Version {
|
||||
Version::from("1.0.0").unwrap()
|
||||
}
|
||||
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
self.status.clone()
|
||||
}
|
||||
|
||||
fn get_children(&self) -> Vec<crate::domain::data::Id> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn execute(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
_topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
self.result.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Score that always panics. This is only useful for development/testing purposes. It does nothing
|
||||
/// except panic! with an error message when interpreted
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PanicScore;
|
||||
|
||||
impl Score for PanicScore {
|
||||
fn create_interpret(&self) -> Box<dyn crate::interpret::Interpret> {
|
||||
Box::new(PanicInterpret {})
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"PanicScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// An interpret that always panics when executed. Useful for development/testing purposes.
|
||||
#[derive(Debug)]
|
||||
struct PanicInterpret;
|
||||
|
||||
#[async_trait]
|
||||
impl Interpret for PanicInterpret {
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::Panic
|
||||
}
|
||||
|
||||
fn get_version(&self) -> Version {
|
||||
Version::from("1.0.0").unwrap()
|
||||
}
|
||||
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
InterpretStatus::QUEUED
|
||||
}
|
||||
|
||||
fn get_children(&self) -> Vec<crate::domain::data::Id> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn execute(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
_topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
panic!("Panic interpret always panics when executed")
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use derive_new::new;
|
||||
|
||||
use crate::{
|
||||
data::{Id, Version},
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
topology::{HAClusterTopology, Url},
|
||||
};
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct HttpScore {
|
||||
files_to_serve: Url,
|
||||
}
|
||||
|
||||
impl Score for HttpScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret> {
|
||||
Box::new(HttpInterpret::new(self.clone()))
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"HttpScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct HttpInterpret {
|
||||
score: HttpScore,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Interpret for HttpInterpret {
|
||||
async fn execute(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let http_server = &topology.http_server;
|
||||
http_server.ensure_initialized().await?;
|
||||
// http_server.set_ip(topology.router.get_gateway()).await?;
|
||||
http_server.serve_files(&self.score.files_to_serve).await?;
|
||||
http_server.commit_config().await?;
|
||||
http_server.reload_restart().await?;
|
||||
Ok(Outcome::success(format!(
|
||||
"Http Server running and serving files from {}",
|
||||
self.score.files_to_serve
|
||||
)))
|
||||
}
|
||||
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::Http
|
||||
}
|
||||
|
||||
fn get_version(&self) -> Version {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_children(&self) -> Vec<Id> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
use k8s_openapi::api::apps::v1::Deployment;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{interpret::Interpret, score::Score};
|
||||
|
||||
use super::resource::{K8sResourceInterpret, K8sResourceScore};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct K8sDeploymentScore {
|
||||
pub name: String,
|
||||
pub image: String,
|
||||
}
|
||||
|
||||
impl Score for K8sDeploymentScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret> {
|
||||
let deployment: Deployment = serde_json::from_value(json!(
|
||||
{
|
||||
"metadata": {
|
||||
"name": self.name
|
||||
},
|
||||
"spec": {
|
||||
"selector": {
|
||||
"matchLabels": {
|
||||
"app": self.name
|
||||
},
|
||||
},
|
||||
"template": {
|
||||
"metadata": {
|
||||
"labels": {
|
||||
"app": self.name
|
||||
},
|
||||
},
|
||||
"spec": {
|
||||
"containers": [
|
||||
{
|
||||
"image": self.image,
|
||||
"name": self.image
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
))
|
||||
.unwrap();
|
||||
Box::new(K8sResourceInterpret {
|
||||
score: K8sResourceScore::single(deployment.clone()),
|
||||
})
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"K8sDeploymentScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
pub mod deployment;
|
||||
pub mod resource;
|
||||
@@ -1,101 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use k8s_openapi::NamespaceResourceScope;
|
||||
use kube::Resource;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::{
|
||||
data::{Id, Version},
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
topology::HAClusterTopology,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct K8sResourceScore<K: Resource + std::fmt::Debug> {
|
||||
pub resource: Vec<K>,
|
||||
}
|
||||
|
||||
impl<K: Resource + std::fmt::Debug> K8sResourceScore<K> {
|
||||
pub fn single(resource: K) -> Self {
|
||||
Self {
|
||||
resource: vec![resource],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<
|
||||
K: Resource<Scope = NamespaceResourceScope>
|
||||
+ std::fmt::Debug
|
||||
+ Sync
|
||||
+ DeserializeOwned
|
||||
+ Default
|
||||
+ serde::Serialize
|
||||
+ 'static
|
||||
+ Send
|
||||
+ Clone,
|
||||
> Score for K8sResourceScore<K>
|
||||
where
|
||||
<K as kube::Resource>::DynamicType: Default,
|
||||
{
|
||||
fn create_interpret(&self) -> Box<dyn Interpret> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"K8sResourceScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct K8sResourceInterpret<K: Resource + std::fmt::Debug + Sync + Send> {
|
||||
pub score: K8sResourceScore<K>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<
|
||||
K: Resource<Scope = NamespaceResourceScope>
|
||||
+ Clone
|
||||
+ std::fmt::Debug
|
||||
+ DeserializeOwned
|
||||
+ serde::Serialize
|
||||
+ Default
|
||||
+ Send
|
||||
+ Sync,
|
||||
> Interpret for K8sResourceInterpret<K>
|
||||
where
|
||||
<K as kube::Resource>::DynamicType: Default,
|
||||
{
|
||||
async fn execute(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
topology
|
||||
.oc_client()
|
||||
.await
|
||||
.expect("Environment should provide enough information to instanciate a client")
|
||||
.apply_namespaced(&self.score.resource)
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::success(
|
||||
"Successfully applied resource".to_string(),
|
||||
))
|
||||
}
|
||||
fn get_name(&self) -> InterpretName {
|
||||
todo!()
|
||||
}
|
||||
fn get_version(&self) -> Version {
|
||||
todo!()
|
||||
}
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
todo!()
|
||||
}
|
||||
fn get_children(&self) -> Vec<Id> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use log::info;
|
||||
|
||||
use crate::{
|
||||
data::{Id, Version},
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
topology::{HAClusterTopology, LoadBalancerService},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LoadBalancerScore {
|
||||
pub public_services: Vec<LoadBalancerService>,
|
||||
pub private_services: Vec<LoadBalancerService>,
|
||||
// TODO public and private services are likely wrong, should be a single list of
|
||||
// (listen_interface, LoadBalancerService) tuples or something like that
|
||||
// I am not sure what to use as listen_interface, should it be interface name, ip address,
|
||||
// uuid?
|
||||
}
|
||||
|
||||
impl Score for LoadBalancerScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret> {
|
||||
Box::new(LoadBalancerInterpret::new(self.clone()))
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"LoadBalancerScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LoadBalancerInterpret {
|
||||
version: Version,
|
||||
status: InterpretStatus,
|
||||
score: LoadBalancerScore,
|
||||
}
|
||||
|
||||
impl LoadBalancerInterpret {
|
||||
pub fn new(score: LoadBalancerScore) -> Self {
|
||||
Self {
|
||||
version: Version::from("1.0.0").expect("Version should be valid"),
|
||||
status: InterpretStatus::QUEUED,
|
||||
score,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Interpret for LoadBalancerInterpret {
|
||||
async fn execute(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
info!(
|
||||
"Making sure Load Balancer is initialized: {:?}",
|
||||
topology.load_balancer.ensure_initialized().await?
|
||||
);
|
||||
|
||||
for service in self.score.public_services.iter() {
|
||||
info!("Ensuring service exists {service:?}");
|
||||
topology
|
||||
.load_balancer
|
||||
.ensure_service_exists(service)
|
||||
.await?;
|
||||
}
|
||||
|
||||
for service in self.score.private_services.iter() {
|
||||
info!("Ensuring private service exists {service:?}");
|
||||
topology
|
||||
.load_balancer
|
||||
.ensure_service_exists(service)
|
||||
.await?;
|
||||
}
|
||||
|
||||
info!("Applying load balancer configuration");
|
||||
topology.load_balancer.commit_config().await?;
|
||||
info!("Making a full reload and restart of haproxy");
|
||||
topology.load_balancer.reload_restart().await?;
|
||||
Ok(Outcome::success(format!(
|
||||
"Load balancer successfully configured {} services",
|
||||
self.score.public_services.len() + self.score.private_services.len()
|
||||
)))
|
||||
}
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::LoadBalancer
|
||||
}
|
||||
fn get_version(&self) -> Version {
|
||||
self.version.clone()
|
||||
}
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
self.status.clone()
|
||||
}
|
||||
|
||||
fn get_children(&self) -> Vec<Id> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
pub mod dhcp;
|
||||
pub mod dns;
|
||||
pub mod dummy;
|
||||
pub mod http;
|
||||
pub mod k8s;
|
||||
pub mod load_balancer;
|
||||
pub mod okd;
|
||||
pub mod opnsense;
|
||||
pub mod tftp;
|
||||
@@ -1,61 +0,0 @@
|
||||
use crate::{
|
||||
interpret::Interpret,
|
||||
inventory::Inventory,
|
||||
modules::dhcp::DhcpScore,
|
||||
score::Score,
|
||||
topology::{HAClusterTopology, HostBinding},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OKDBootstrapDhcpScore {
|
||||
dhcp_score: DhcpScore,
|
||||
}
|
||||
|
||||
impl OKDBootstrapDhcpScore {
|
||||
pub fn new(topology: &HAClusterTopology, inventory: &Inventory) -> Self {
|
||||
let mut host_binding: Vec<_> = topology
|
||||
.control_plane
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, topology_entry)| HostBinding {
|
||||
logical_host: topology_entry.clone(),
|
||||
physical_host: inventory
|
||||
.control_plane_host
|
||||
.get(index)
|
||||
.expect("Iventory should contain at least as many physical hosts as topology")
|
||||
.clone(),
|
||||
})
|
||||
.collect();
|
||||
host_binding.push(HostBinding {
|
||||
logical_host: topology.bootstrap_host.clone(),
|
||||
physical_host: inventory
|
||||
.worker_host
|
||||
.get(0)
|
||||
.expect("Should have at least one worker to be used as bootstrap node")
|
||||
.clone(),
|
||||
});
|
||||
Self {
|
||||
dhcp_score: DhcpScore::new(
|
||||
host_binding,
|
||||
// TODO : we should add a tftp server to the topology instead of relying on the
|
||||
// router address, this is leaking implementation details
|
||||
Some(topology.router.get_gateway()),
|
||||
Some("bootx64.efi".to_string()),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Score for OKDBootstrapDhcpScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret> {
|
||||
self.dhcp_score.create_interpret()
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"OKDBootstrapDhcpScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use crate::{
|
||||
interpret::Interpret,
|
||||
modules::load_balancer::LoadBalancerScore,
|
||||
score::Score,
|
||||
topology::{
|
||||
BackendServer, HAClusterTopology, HealthCheck, HttpMethod, HttpStatusCode,
|
||||
LoadBalancerService,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OKDBootstrapLoadBalancerScore {
|
||||
load_balancer_score: LoadBalancerScore,
|
||||
}
|
||||
|
||||
impl OKDBootstrapLoadBalancerScore {
|
||||
pub fn new(topology: &HAClusterTopology) -> Self {
|
||||
let private_ip = topology.router.get_gateway();
|
||||
|
||||
let private_services = vec![
|
||||
LoadBalancerService {
|
||||
backend_servers: Self::topology_to_backend_server(topology, 80),
|
||||
listening_port: SocketAddr::new(private_ip, 80),
|
||||
health_check: Some(HealthCheck::TCP(None)),
|
||||
},
|
||||
LoadBalancerService {
|
||||
backend_servers: Self::topology_to_backend_server(topology, 443),
|
||||
listening_port: SocketAddr::new(private_ip, 443),
|
||||
health_check: Some(HealthCheck::TCP(None)),
|
||||
},
|
||||
LoadBalancerService {
|
||||
backend_servers: Self::topology_to_backend_server(topology, 22623),
|
||||
listening_port: SocketAddr::new(private_ip, 22623),
|
||||
health_check: Some(HealthCheck::TCP(None)),
|
||||
},
|
||||
LoadBalancerService {
|
||||
backend_servers: Self::topology_to_backend_server(topology, 6443),
|
||||
listening_port: SocketAddr::new(private_ip, 6443),
|
||||
health_check: Some(HealthCheck::HTTP(
|
||||
"/readyz".to_string(),
|
||||
HttpMethod::GET,
|
||||
HttpStatusCode::Success2xx,
|
||||
)),
|
||||
},
|
||||
];
|
||||
Self {
|
||||
load_balancer_score: LoadBalancerScore {
|
||||
public_services: vec![],
|
||||
private_services,
|
||||
},
|
||||
}
|
||||
}
|
||||
fn topology_to_backend_server(topology: &HAClusterTopology, port: u16) -> Vec<BackendServer> {
|
||||
let mut backend: Vec<_> = topology
|
||||
.control_plane
|
||||
.iter()
|
||||
.map(|cp| BackendServer {
|
||||
address: cp.ip.to_string(),
|
||||
port,
|
||||
})
|
||||
.collect();
|
||||
backend.push(BackendServer {
|
||||
address: topology.bootstrap_host.ip.to_string(),
|
||||
port,
|
||||
});
|
||||
backend
|
||||
}
|
||||
}
|
||||
|
||||
impl Score for OKDBootstrapLoadBalancerScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret> {
|
||||
self.load_balancer_score.create_interpret()
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"OKDBootstrapLoadBalancerScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
use crate::{
|
||||
interpret::Interpret,
|
||||
inventory::Inventory,
|
||||
modules::dhcp::DhcpScore,
|
||||
score::Score,
|
||||
topology::{HAClusterTopology, HostBinding},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OKDDhcpScore {
|
||||
dhcp_score: DhcpScore,
|
||||
}
|
||||
|
||||
impl OKDDhcpScore {
|
||||
pub fn new(topology: &HAClusterTopology, inventory: &Inventory) -> Self {
|
||||
let host_binding = topology
|
||||
.control_plane
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, topology_entry)| HostBinding {
|
||||
logical_host: topology_entry.clone(),
|
||||
physical_host: inventory
|
||||
.control_plane_host
|
||||
.get(index)
|
||||
.expect("Iventory should contain at least as many physical hosts as topology")
|
||||
.clone(),
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
// TODO : we should add a tftp server to the topology instead of relying on the
|
||||
// router address, this is leaking implementation details
|
||||
dhcp_score: DhcpScore {
|
||||
host_binding,
|
||||
next_server: Some(topology.router.get_gateway()),
|
||||
boot_filename: Some("bootx64.efi".to_string()),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Score for OKDDhcpScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret> {
|
||||
self.dhcp_score.create_interpret()
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"OKDDhcpScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
use crate::{
|
||||
interpret::Interpret,
|
||||
modules::dns::DnsScore,
|
||||
score::Score,
|
||||
topology::{DnsRecord, DnsRecordType, HAClusterTopology},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OKDDnsScore {
|
||||
dns_score: DnsScore,
|
||||
}
|
||||
|
||||
impl OKDDnsScore {
|
||||
pub fn new(topology: &HAClusterTopology) -> Self {
|
||||
let cluster_domain_name = &topology.domain_name;
|
||||
let dns_entries = vec![
|
||||
DnsRecord {
|
||||
host: "api".to_string(),
|
||||
domain: cluster_domain_name.clone(),
|
||||
record_type: DnsRecordType::A,
|
||||
value: topology.dns_server.get_ip(),
|
||||
},
|
||||
DnsRecord {
|
||||
host: "api-int".to_string(),
|
||||
domain: cluster_domain_name.clone(),
|
||||
record_type: DnsRecordType::A,
|
||||
value: topology.dns_server.get_ip(),
|
||||
},
|
||||
DnsRecord {
|
||||
host: "*".to_string(),
|
||||
domain: format!("apps.{}", cluster_domain_name),
|
||||
record_type: DnsRecordType::A,
|
||||
value: topology.dns_server.get_ip(),
|
||||
},
|
||||
];
|
||||
|
||||
Self {
|
||||
dns_score: DnsScore::new(dns_entries, Some(true)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Score for OKDDnsScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret> {
|
||||
self.dns_score.create_interpret()
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"OKDDnsScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use crate::{
|
||||
interpret::Interpret,
|
||||
modules::load_balancer::LoadBalancerScore,
|
||||
score::Score,
|
||||
topology::{
|
||||
BackendServer, HAClusterTopology, HealthCheck, HttpMethod, HttpStatusCode,
|
||||
LoadBalancerService,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OKDLoadBalancerScore {
|
||||
load_balancer_score: LoadBalancerScore,
|
||||
}
|
||||
|
||||
impl OKDLoadBalancerScore {
|
||||
pub fn new(topology: &HAClusterTopology) -> Self {
|
||||
let public_ip = topology.router.get_gateway();
|
||||
let public_services = vec![
|
||||
LoadBalancerService {
|
||||
backend_servers: Self::control_plane_to_backend_server(topology, 80),
|
||||
listening_port: SocketAddr::new(public_ip, 80),
|
||||
health_check: Some(HealthCheck::TCP(None)),
|
||||
},
|
||||
LoadBalancerService {
|
||||
backend_servers: Self::control_plane_to_backend_server(topology, 443),
|
||||
listening_port: SocketAddr::new(public_ip, 443),
|
||||
health_check: Some(HealthCheck::TCP(None)),
|
||||
},
|
||||
];
|
||||
|
||||
let private_services = vec![
|
||||
LoadBalancerService {
|
||||
backend_servers: Self::control_plane_to_backend_server(topology, 80),
|
||||
listening_port: SocketAddr::new(public_ip, 80),
|
||||
health_check: Some(HealthCheck::TCP(None)),
|
||||
},
|
||||
LoadBalancerService {
|
||||
backend_servers: Self::control_plane_to_backend_server(topology, 443),
|
||||
listening_port: SocketAddr::new(public_ip, 443),
|
||||
health_check: Some(HealthCheck::TCP(None)),
|
||||
},
|
||||
LoadBalancerService {
|
||||
backend_servers: Self::control_plane_to_backend_server(topology, 22623),
|
||||
listening_port: SocketAddr::new(public_ip, 22623),
|
||||
health_check: Some(HealthCheck::TCP(None)),
|
||||
},
|
||||
LoadBalancerService {
|
||||
backend_servers: Self::control_plane_to_backend_server(topology, 6443),
|
||||
listening_port: SocketAddr::new(public_ip, 6443),
|
||||
health_check: Some(HealthCheck::HTTP(
|
||||
"/readyz".to_string(),
|
||||
HttpMethod::GET,
|
||||
HttpStatusCode::Success2xx,
|
||||
)),
|
||||
},
|
||||
];
|
||||
Self {
|
||||
load_balancer_score: LoadBalancerScore {
|
||||
public_services,
|
||||
private_services,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn control_plane_to_backend_server(
|
||||
topology: &HAClusterTopology,
|
||||
port: u16,
|
||||
) -> Vec<BackendServer> {
|
||||
topology
|
||||
.control_plane
|
||||
.iter()
|
||||
.map(|cp| BackendServer {
|
||||
address: cp.ip.to_string(),
|
||||
port,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Score for OKDLoadBalancerScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret> {
|
||||
self.load_balancer_score.create_interpret()
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"OKDLoadBalancerScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
pub mod bootstrap_dhcp;
|
||||
pub mod bootstrap_load_balancer;
|
||||
pub mod dhcp;
|
||||
pub mod dns;
|
||||
pub mod load_balancer;
|
||||
pub mod upgrade;
|
||||
@@ -1,35 +0,0 @@
|
||||
use crate::{data::Version, score::Score};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OKDUpgradeScore {
|
||||
current_version: Version,
|
||||
target_version: Version,
|
||||
}
|
||||
|
||||
impl OKDUpgradeScore {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
current_version: Version::from("4.17.0-okd-scos.0").unwrap(),
|
||||
target_version: Version::from("").unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// impl Score for OKDUpgradeScore {
|
||||
// fn create_interpret(self) -> Box<dyn Interpret> {
|
||||
// // Should this be a specialized interpret for OKD upgrades or rather a set of interprets
|
||||
// // such as :
|
||||
// //
|
||||
// // MultiStageInterpret :
|
||||
// // stages : vec![
|
||||
// // vec![CheckOperatorsUpgraded, CheckClusterHealthy, CheckOtherPrecondition],
|
||||
// // vec![PerformUpgrade],
|
||||
// // vec![VerifyUpgrade, CheckClusterHealth],
|
||||
// // ]
|
||||
// todo!()
|
||||
// }
|
||||
//
|
||||
// fn name(&self) -> String {
|
||||
// "OKDUpgradeScore".to_string()
|
||||
// }
|
||||
// }
|
||||
@@ -1,85 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::{
|
||||
data::{Id, Version},
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
topology::HAClusterTopology,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OPNSenseShellCommandScore {
|
||||
pub opnsense: Arc<RwLock<opnsense_config::Config>>,
|
||||
pub command: String,
|
||||
}
|
||||
|
||||
impl Score for OPNSenseShellCommandScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret> {
|
||||
Box::new(OPNsenseInterpret {
|
||||
status: InterpretStatus::QUEUED,
|
||||
score: self.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"OPNSenseShellCommandScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct OPNsenseInterpret {
|
||||
status: InterpretStatus,
|
||||
score: OPNSenseShellCommandScore,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Interpret for OPNsenseInterpret {
|
||||
async fn execute(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
_topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let output = self
|
||||
.score
|
||||
.opnsense
|
||||
.read()
|
||||
.await
|
||||
.run_command(&self.score.command)
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::success(format!(
|
||||
"Command execution successful : {}\n\n{output}",
|
||||
self.score.command
|
||||
)))
|
||||
}
|
||||
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::OPNSense
|
||||
}
|
||||
|
||||
fn get_version(&self) -> Version {
|
||||
Version::from("1.0.0").unwrap()
|
||||
}
|
||||
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
self.status.clone()
|
||||
}
|
||||
|
||||
fn get_children(&self) -> Vec<Id> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<opnsense_config::Error> for InterpretError {
|
||||
fn from(value: opnsense_config::Error) -> Self {
|
||||
Self::new(format!("opnsense_config::Error {value:?}"))
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use derive_new::new;
|
||||
|
||||
use crate::{
|
||||
data::{Id, Version},
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
topology::{HAClusterTopology, Url},
|
||||
};
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct TftpScore {
|
||||
files_to_serve: Url,
|
||||
}
|
||||
|
||||
impl Score for TftpScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret> {
|
||||
Box::new(TftpInterpret::new(self.clone()))
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"TftpScore".to_string()
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn Score> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct TftpInterpret {
|
||||
score: TftpScore,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Interpret for TftpInterpret {
|
||||
async fn execute(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let tftp_server = &topology.tftp_server;
|
||||
tftp_server.ensure_initialized().await?;
|
||||
tftp_server.set_ip(topology.router.get_gateway()).await?;
|
||||
tftp_server.serve_files(&self.score.files_to_serve).await?;
|
||||
tftp_server.commit_config().await?;
|
||||
tftp_server.reload_restart().await?;
|
||||
Ok(Outcome::success(format!(
|
||||
"TFTP Server running and serving files from {}",
|
||||
self.score.files_to_serve
|
||||
)))
|
||||
}
|
||||
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::Tftp
|
||||
}
|
||||
|
||||
fn get_version(&self) -> Version {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_children(&self) -> Vec<Id> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
46
harmony-rs/harmony_macros/Cargo.lock
generated
46
harmony-rs/harmony_macros/Cargo.lock
generated
@@ -1,46 +0,0 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "harmony_macros"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.92"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.37"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.90"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83"
|
||||
@@ -1,19 +0,0 @@
|
||||
[package]
|
||||
name = "harmony_macros"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
harmony_types = { path = "../harmony_types" }
|
||||
quote = "1.0.37"
|
||||
serde = "1.0.217"
|
||||
serde_yaml = "0.9.34"
|
||||
syn = "2.0.90"
|
||||
|
||||
[dev-dependencies]
|
||||
serde = { version = "1.0.217", features = ["derive"] }
|
||||
@@ -1,118 +0,0 @@
|
||||
extern crate proc_macro;
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use serde_yaml::Value;
|
||||
use syn::LitStr;
|
||||
use syn::parse_macro_input;
|
||||
|
||||
#[proc_macro]
|
||||
pub fn ip(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as LitStr);
|
||||
let ip_str = input.value();
|
||||
|
||||
if let Ok(_) = ip_str.parse::<std::net::Ipv4Addr>() {
|
||||
let expanded =
|
||||
quote! { std::net::IpAddr::V4(#ip_str.parse::<std::net::Ipv4Addr>().unwrap()) };
|
||||
return TokenStream::from(expanded);
|
||||
}
|
||||
|
||||
if let Ok(_) = ip_str.parse::<std::net::Ipv6Addr>() {
|
||||
let expanded =
|
||||
quote! { std::net::IpAddr::V6(#ip_str.parse::<std::net::Ipv6Addr>().unwrap()) };
|
||||
return TokenStream::from(expanded);
|
||||
}
|
||||
|
||||
panic!("Invalid IP address: {}", ip_str);
|
||||
}
|
||||
|
||||
#[proc_macro]
|
||||
pub fn ipv4(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as LitStr);
|
||||
let ip_str = input.value();
|
||||
|
||||
if let Ok(_) = ip_str.parse::<std::net::Ipv4Addr>() {
|
||||
let expanded = quote! { #ip_str.parse::<std::net::Ipv4Addr>().unwrap() };
|
||||
return TokenStream::from(expanded);
|
||||
}
|
||||
|
||||
panic!("Invalid IPv4 address: {}", ip_str);
|
||||
}
|
||||
|
||||
#[proc_macro]
|
||||
pub fn mac_address(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as LitStr);
|
||||
let mac_str = input.value();
|
||||
|
||||
match parse_mac_address(&mac_str) {
|
||||
Ok(bytes) => {
|
||||
let b0 = bytes[0];
|
||||
let b1 = bytes[1];
|
||||
let b2 = bytes[2];
|
||||
let b3 = bytes[3];
|
||||
let b4 = bytes[4];
|
||||
let b5 = bytes[5];
|
||||
|
||||
quote! {
|
||||
harmony_types::net::MacAddress( [#b0, #b1, #b2, #b3, #b4, #b5] )
|
||||
}
|
||||
.into()
|
||||
}
|
||||
Err(err) => syn::Error::new(input.span(), err).to_compile_error().into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_mac_address(mac: &str) -> Result<[u8; 6], String> {
|
||||
let parts: Vec<&str> = mac.split(':').collect();
|
||||
if parts.len() != 6 {
|
||||
return Err("MAC address must contain exactly six octets separated by colons".to_string());
|
||||
}
|
||||
|
||||
let mut bytes = [0u8; 6];
|
||||
for (i, part) in parts.iter().enumerate() {
|
||||
match u8::from_str_radix(part, 16) {
|
||||
Ok(byte) => bytes[i] = byte,
|
||||
Err(_) => return Err(format!("Invalid MAC address octet: {}", part)),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Verify that input is valid yaml by trying to deserialize it using
|
||||
/// serde_yaml::from_str::<serde_yaml::value::Value>(input)
|
||||
///
|
||||
/// panics: If yaml is not valid
|
||||
#[proc_macro]
|
||||
pub fn yaml(input: TokenStream) -> TokenStream {
|
||||
// TODO, accept a second argument that is the type to be deserialized to and validate at
|
||||
// compile-time that deserialization is possible
|
||||
//
|
||||
// It does not seem to be doable with the way macros are designed : we may pass an ident to the
|
||||
// macro, but the macro only has access to the ident, not the type itself.
|
||||
//
|
||||
// I also tried to create a restricted version of this macro, but this time serde got in the
|
||||
// way : my use case is to make sure that the yaml I am given can deserialize strictly (with
|
||||
// deny_unknown_attributes option on) to k8s-openapi types. But the k8s-openapi types are not
|
||||
// annotated with deny_unknown_attributes and there does not seem to be a way to tell serde to
|
||||
// deserialize in "strict mode" when calling the deserialization function itself. I tried
|
||||
// wrapping the types in something like :
|
||||
//
|
||||
// ```rust
|
||||
// #[derive(Deserialize, Debug)]
|
||||
// #[serde(deny_unknown_fields)]
|
||||
// struct Strict<T>(pub T);
|
||||
// ```
|
||||
//
|
||||
// But it still does actually deserialize T strictly. I gave up for now at this point. Will
|
||||
// find a solution some day!
|
||||
|
||||
let yaml = parse_macro_input!(input as LitStr);
|
||||
|
||||
serde_yaml::from_str::<Value>(yaml.value().as_str()).expect("Should be valid yaml");
|
||||
|
||||
quote! {
|
||||
serde_yaml::from_str(#yaml)
|
||||
}
|
||||
.into()
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
[package]
|
||||
name = "harmony_tui"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
harmony = { path = "../harmony" }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
ratatui = "0.29.0"
|
||||
crossterm = { version = "0.28.1", features = [ "event-stream" ] }
|
||||
color-eyre = "0.6.3"
|
||||
tokio-stream = "0.1.17"
|
||||
tui-logger = "0.14.1"
|
||||
log-panics = "2.1.0"
|
||||
@@ -1,205 +0,0 @@
|
||||
mod ratatui_utils;
|
||||
mod widget;
|
||||
|
||||
use log::{debug, error, info};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_stream::StreamExt;
|
||||
use tui_logger::{TuiWidgetEvent, TuiWidgetState};
|
||||
use widget::{help::HelpWidget, score::ScoreListWidget};
|
||||
|
||||
use std::{panic, sync::Arc, time::Duration};
|
||||
|
||||
use crossterm::event::{Event, EventStream, KeyCode, KeyEventKind};
|
||||
use harmony::{maestro::Maestro, score::Score};
|
||||
use ratatui::{
|
||||
self, Frame,
|
||||
layout::{Constraint, Layout, Position},
|
||||
style::{Color, Style},
|
||||
widgets::{Block, Borders, ListItem},
|
||||
};
|
||||
|
||||
pub mod tui {
|
||||
// Export any necessary modules or types from the internal tui module
|
||||
}
|
||||
|
||||
/// Initializes the terminal UI with the provided Maestro instance.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `maestro` - A reference to the Maestro instance containing registered scores.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use harmony;
|
||||
/// use harmony_tui::init;
|
||||
///
|
||||
/// #[harmony::main]
|
||||
/// pub async fn main(maestro: harmony::Maestro) {
|
||||
/// maestro.register(DeploymentScore::new("nginx-test", "nginx"));
|
||||
/// maestro.register(OKDLoadBalancerScore::new(&maestro.inventory, &maestro.topology));
|
||||
/// // Register other scores as needed
|
||||
///
|
||||
/// init(maestro).await.unwrap();
|
||||
/// }
|
||||
/// ```
|
||||
pub async fn init(maestro: Maestro) -> Result<(), Box<dyn std::error::Error>> {
|
||||
HarmonyTUI::new(maestro).init().await
|
||||
}
|
||||
|
||||
pub struct HarmonyTUI {
|
||||
score: ScoreListWidget,
|
||||
should_quit: bool,
|
||||
tui_state: TuiWidgetState,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum HarmonyTuiEvent {
|
||||
LaunchScore(ScoreItem),
|
||||
}
|
||||
|
||||
impl HarmonyTUI {
|
||||
pub fn new(maestro: Maestro) -> Self {
|
||||
let maestro = Arc::new(maestro);
|
||||
let (_handle, sender) = Self::start_channel(maestro.clone());
|
||||
let score = ScoreListWidget::new(Self::scores_list(&maestro), sender);
|
||||
|
||||
HarmonyTUI {
|
||||
should_quit: false,
|
||||
score,
|
||||
tui_state: TuiWidgetState::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn start_channel(
|
||||
maestro: Arc<Maestro>,
|
||||
) -> (tokio::task::JoinHandle<()>, mpsc::Sender<HarmonyTuiEvent>) {
|
||||
let (sender, mut receiver) = mpsc::channel::<HarmonyTuiEvent>(32);
|
||||
let handle = tokio::spawn(async move {
|
||||
info!("Starting message channel receiver loop");
|
||||
while let Some(event) = receiver.recv().await {
|
||||
info!("Received event {event:#?}");
|
||||
match event {
|
||||
HarmonyTuiEvent::LaunchScore(score_item) => {
|
||||
let maestro = maestro.clone();
|
||||
|
||||
let joinhandle_result =
|
||||
tokio::spawn(async move { maestro.interpret(score_item.0).await })
|
||||
.await;
|
||||
|
||||
match joinhandle_result {
|
||||
Ok(interpretation_result) => match interpretation_result {
|
||||
Ok(success) => info!("Score execution successful {success:?}"),
|
||||
Err(error) => error!("Score failed {error:?}"),
|
||||
},
|
||||
Err(joinhandle_failure) => {
|
||||
error!("Score execution TASK FAILED! {:#?}", joinhandle_failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
info!("STOPPING message channel receiver loop");
|
||||
});
|
||||
|
||||
(handle, sender)
|
||||
}
|
||||
|
||||
pub async fn init(mut self) -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Set max_log_level to Trace
|
||||
tui_logger::init_logger(log::LevelFilter::Info).unwrap();
|
||||
// Set default level for unknown targets to Trace
|
||||
tui_logger::set_default_level(log::LevelFilter::Info);
|
||||
tui_logger::set_log_file("harmony.log").unwrap();
|
||||
|
||||
color_eyre::install()?;
|
||||
let mut terminal = ratatui::init();
|
||||
log_panics::init();
|
||||
terminal.hide_cursor()?;
|
||||
|
||||
// TODO improve performance here
|
||||
// Refreshing the entire terminal 10 times a second does not seem very smart
|
||||
let period = Duration::from_secs_f32(1.0 / 10.0);
|
||||
let mut interval = tokio::time::interval(period);
|
||||
let mut events = EventStream::new();
|
||||
|
||||
while !self.should_quit {
|
||||
tokio::select! {
|
||||
_ = interval.tick() => { terminal.draw(|frame| self.render(frame))?; },
|
||||
Some(Ok(event)) = events.next() => self.handle_event(&event).await,
|
||||
}
|
||||
}
|
||||
|
||||
ratatui::restore();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn render(&self, frame: &mut Frame) {
|
||||
let size = frame.area();
|
||||
frame.set_cursor_position(Position::new(size.x / 2, size.y / 2));
|
||||
|
||||
let [app_area, help_area] =
|
||||
Layout::vertical([Constraint::Percentage(100), Constraint::Min(4)]).areas(frame.area());
|
||||
|
||||
let help_block = Block::default().borders(Borders::TOP);
|
||||
frame.render_widget(&help_block, help_area);
|
||||
frame.render_widget(HelpWidget::new(), help_block.inner(help_area));
|
||||
|
||||
let [list_area, output_area] =
|
||||
Layout::horizontal([Constraint::Min(30), Constraint::Percentage(100)]).areas(app_area);
|
||||
|
||||
let block = Block::default().borders(Borders::RIGHT);
|
||||
frame.render_widget(&block, list_area);
|
||||
self.score.render(list_area, frame);
|
||||
let tui_logger = tui_logger::TuiLoggerWidget::default()
|
||||
.style_error(Style::default().fg(Color::Red))
|
||||
.style_warn(Style::default().fg(Color::LightRed))
|
||||
.style_info(Style::default().fg(Color::LightGreen))
|
||||
.style_debug(Style::default().fg(Color::Gray))
|
||||
.style_trace(Style::default().fg(Color::Gray))
|
||||
.state(&self.tui_state);
|
||||
frame.render_widget(tui_logger, output_area)
|
||||
}
|
||||
|
||||
fn scores_list(maestro: &Maestro) -> Vec<ScoreItem> {
|
||||
let scores = maestro.scores();
|
||||
let scores_read = scores.read().expect("Should be able to read scores");
|
||||
scores_read
|
||||
.iter()
|
||||
.map(|s| ScoreItem(s.clone_box()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn handle_event(&mut self, event: &Event) {
|
||||
debug!("Got event {event:?}");
|
||||
if let Event::Key(key) = event {
|
||||
if key.kind == KeyEventKind::Press {
|
||||
match key.code {
|
||||
KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true,
|
||||
KeyCode::PageUp => self.tui_state.transition(TuiWidgetEvent::PrevPageKey),
|
||||
KeyCode::PageDown => self.tui_state.transition(TuiWidgetEvent::NextPageKey),
|
||||
KeyCode::Char('G') | KeyCode::End => {
|
||||
self.tui_state.transition(TuiWidgetEvent::EscapeKey)
|
||||
}
|
||||
_ => self.score.handle_event(event).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ScoreItem(Box<dyn Score>);
|
||||
|
||||
impl ScoreItem {
|
||||
pub fn clone(&self) -> Self {
|
||||
Self(self.0.clone_box())
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<ListItem<'_>> for &ScoreItem {
|
||||
fn into(self) -> ListItem<'static> {
|
||||
ListItem::new(self.0.name())
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
use ratatui::layout::{Constraint, Flex, Layout, Rect};
|
||||
|
||||
/// Centers a [`Rect`] within another [`Rect`] using the provided [`Constraint`]s.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// use ratatui::layout::{Constraint, Rect};
|
||||
///
|
||||
/// let area = Rect::new(0, 0, 100, 100);
|
||||
/// let horizontal = Constraint::Percentage(20);
|
||||
/// let vertical = Constraint::Percentage(30);
|
||||
///
|
||||
/// let centered = center(area, horizontal, vertical);
|
||||
/// ```
|
||||
pub(crate) fn center(area: Rect, horizontal: Constraint, vertical: Constraint) -> Rect {
|
||||
let [area] = Layout::horizontal([horizontal])
|
||||
.flex(Flex::Center)
|
||||
.areas(area);
|
||||
let [area] = Layout::vertical([vertical]).flex(Flex::Center).areas(area);
|
||||
area
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
use ratatui::widgets::{Paragraph, Widget, Wrap};
|
||||
|
||||
pub(crate) struct HelpWidget;
|
||||
impl HelpWidget {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for HelpWidget {
|
||||
fn render(self, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer)
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
let text = Paragraph::new("Usage => q/Esc: Quit | j/↑ :Select UP | k/↓: Select Down | Enter: Launch Score\nPageUp/PageDown: Scroll Logs | Shift+G/End: Logs bottom")
|
||||
.centered()
|
||||
.wrap(Wrap { trim: false });
|
||||
|
||||
Widget::render(text, area, buf)
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
pub mod help;
|
||||
pub mod score;
|
||||
@@ -1,138 +0,0 @@
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use crossterm::event::{Event, KeyCode, KeyEventKind};
|
||||
use log::{info, warn};
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::Rect,
|
||||
style::{Style, Stylize},
|
||||
widgets::{List, ListState, StatefulWidget, Widget},
|
||||
};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::{HarmonyTuiEvent, ScoreItem};
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ExecutionState {
|
||||
INITIATED,
|
||||
RUNNING,
|
||||
CANCELED,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Execution {
|
||||
state: ExecutionState,
|
||||
score: ScoreItem,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ScoreListWidget {
|
||||
list_state: Arc<RwLock<ListState>>,
|
||||
scores: Vec<ScoreItem>,
|
||||
execution: Option<Execution>,
|
||||
execution_history: Vec<Execution>,
|
||||
sender: mpsc::Sender<HarmonyTuiEvent>,
|
||||
}
|
||||
|
||||
impl ScoreListWidget {
|
||||
pub(crate) fn new(scores: Vec<ScoreItem>, sender: mpsc::Sender<HarmonyTuiEvent>) -> Self {
|
||||
let mut list_state = ListState::default();
|
||||
list_state.select_first();
|
||||
let list_state = Arc::new(RwLock::new(list_state));
|
||||
Self {
|
||||
scores,
|
||||
list_state,
|
||||
execution: None,
|
||||
execution_history: vec![],
|
||||
sender,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn launch_execution(&mut self) {
|
||||
let list_read = self.list_state.read().unwrap();
|
||||
if let Some(index) = list_read.selected() {
|
||||
let score = self
|
||||
.scores
|
||||
.get(index)
|
||||
.expect("List state should always match with internal Vec");
|
||||
|
||||
self.execution = Some(Execution {
|
||||
state: ExecutionState::INITIATED,
|
||||
score: score.clone(),
|
||||
});
|
||||
info!("{:#?}\n\nConfirm Execution (Press y/n)", score.0);
|
||||
} else {
|
||||
warn!("No Score selected, nothing to launch");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn scroll_down(&self) {
|
||||
self.list_state.write().unwrap().scroll_down_by(1);
|
||||
}
|
||||
|
||||
pub(crate) fn scroll_up(&self) {
|
||||
self.list_state.write().unwrap().scroll_up_by(1);
|
||||
}
|
||||
|
||||
pub(crate) fn render(&self, area: Rect, frame: &mut Frame) {
|
||||
frame.render_widget(self, area);
|
||||
}
|
||||
|
||||
fn clear_execution(&mut self) {
|
||||
match self.execution.take() {
|
||||
Some(execution) => {
|
||||
self.execution_history.push(execution);
|
||||
}
|
||||
None => warn!("Should never clear execution when no execution exists"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn confirm(&mut self, confirm: bool) {
|
||||
if let Some(execution) = &mut self.execution {
|
||||
match confirm {
|
||||
true => {
|
||||
execution.state = ExecutionState::RUNNING;
|
||||
info!("Launch execution {:?}", execution);
|
||||
self.sender
|
||||
.send(HarmonyTuiEvent::LaunchScore(execution.score.clone()))
|
||||
.await
|
||||
.expect("Should be able to send message");
|
||||
}
|
||||
false => {
|
||||
execution.state = ExecutionState::CANCELED;
|
||||
info!("Execution cancelled");
|
||||
self.clear_execution();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn handle_event(&mut self, event: &Event) {
|
||||
if let Event::Key(key) = event {
|
||||
if key.kind == KeyEventKind::Press {
|
||||
match key.code {
|
||||
KeyCode::Char('j') | KeyCode::Down => self.scroll_down(),
|
||||
KeyCode::Char('k') | KeyCode::Up => self.scroll_up(),
|
||||
KeyCode::Enter => self.launch_execution(),
|
||||
KeyCode::Char('y') => self.confirm(true).await,
|
||||
KeyCode::Char('n') => self.confirm(false).await,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for &ScoreListWidget {
|
||||
fn render(self, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer)
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
let mut list_state = self.list_state.write().unwrap();
|
||||
let list = List::new(&self.scores)
|
||||
.highlight_style(Style::new().bold().italic())
|
||||
.highlight_symbol("🠊 ");
|
||||
|
||||
StatefulWidget::render(list, area, buf, &mut list_state)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
[package]
|
||||
name = "harmony_types"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
@@ -1,26 +0,0 @@
|
||||
pub mod net {
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct MacAddress(pub [u8; 6]);
|
||||
|
||||
impl MacAddress {
|
||||
#[cfg(test)]
|
||||
pub fn dummy() -> Self {
|
||||
Self([0, 0, 0, 0, 0, 0])
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&MacAddress> for String {
|
||||
fn from(value: &MacAddress) -> Self {
|
||||
format!(
|
||||
"{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
|
||||
value.0[0], value.0[1], value.0[2], value.0[3], value.0[4], value.0[5]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for MacAddress {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!("MacAddress {}", String::from(self)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
[package]
|
||||
name = "opnsense-config-xml"
|
||||
edition = "2021"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0.123", features = [ "derive" ] }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
yaserde = { git = "https://github.com/jggc/yaserde.git" }
|
||||
yaserde_derive = { git = "https://github.com/jggc/yaserde.git" }
|
||||
xml-rs = "0.8"
|
||||
thiserror = "1.0"
|
||||
async-trait = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
uuid = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = "1.4.1"
|
||||
@@ -1,85 +0,0 @@
|
||||
use yaserde::MaybeString;
|
||||
use yaserde_derive::{YaDeserialize, YaSerialize};
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct Pischem {
|
||||
pub caddy: Caddy,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct Caddy {
|
||||
pub general: CaddyGeneral,
|
||||
pub reverseproxy: MaybeString,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct CaddyGeneral {
|
||||
pub enabled: u8,
|
||||
#[yaserde(rename = "EnableLayer4")]
|
||||
pub enable_layer4: Option<u8>,
|
||||
#[yaserde(rename = "HttpPort")]
|
||||
pub http_port: Option<u16>,
|
||||
#[yaserde(rename = "HttpsPort")]
|
||||
pub https_port: Option<u16>,
|
||||
#[yaserde(rename = "TlsEmail")]
|
||||
pub tls_email: MaybeString,
|
||||
#[yaserde(rename = "TlsAutoHttps")]
|
||||
pub tls_auto_https: MaybeString,
|
||||
#[yaserde(rename = "TlsDnsProvider")]
|
||||
pub tls_dns_provider: MaybeString,
|
||||
#[yaserde(rename = "TlsDnsApiKey")]
|
||||
pub tls_dns_api_key: MaybeString,
|
||||
#[yaserde(rename = "TlsDnsSecretApiKey")]
|
||||
pub tls_dns_secret_api_key: MaybeString,
|
||||
#[yaserde(rename = "TlsDnsOptionalField1")]
|
||||
pub tls_dns_optional_field1: MaybeString,
|
||||
#[yaserde(rename = "TlsDnsOptionalField2")]
|
||||
pub tls_dns_optional_field2: MaybeString,
|
||||
#[yaserde(rename = "TlsDnsOptionalField3")]
|
||||
pub tls_dns_optional_field3: MaybeString,
|
||||
#[yaserde(rename = "TlsDnsOptionalField4")]
|
||||
pub tls_dns_optional_field4: MaybeString,
|
||||
#[yaserde(rename = "TlsDnsPropagationTimeout")]
|
||||
pub tls_dns_propagation_timeout: MaybeString,
|
||||
#[yaserde(rename = "TlsDnsPropagationResolvers")]
|
||||
pub tls_dns_propagation_resolvers: MaybeString,
|
||||
pub accesslist: MaybeString,
|
||||
#[yaserde(rename = "DisableSuperuser")]
|
||||
pub disable_superuser: Option<i32>,
|
||||
#[yaserde(rename = "GracePeriod")]
|
||||
pub grace_period: Option<u16>,
|
||||
#[yaserde(rename = "HttpVersion")]
|
||||
pub http_version: Option<MaybeString>,
|
||||
#[yaserde(rename = "HttpVersions")]
|
||||
pub http_versions: Option<MaybeString>,
|
||||
#[yaserde(rename = "LogCredentials")]
|
||||
pub log_credentials: MaybeString,
|
||||
#[yaserde(rename = "LogAccessPlain")]
|
||||
pub log_access_plain: MaybeString,
|
||||
#[yaserde(rename = "LogAccessPlainKeep")]
|
||||
pub log_access_plain_keep: Option<u16>,
|
||||
#[yaserde(rename = "LogLevel")]
|
||||
pub log_level: MaybeString,
|
||||
#[yaserde(rename = "DynDnsSimpleHttp")]
|
||||
pub dyn_dns_simple_http: MaybeString,
|
||||
#[yaserde(rename = "DynDnsInterface")]
|
||||
pub dyn_dns_interface: MaybeString,
|
||||
#[yaserde(rename = "DynDnsInterval")]
|
||||
pub dyn_dns_interval: MaybeString,
|
||||
#[yaserde(rename = "DynDnsIpVersions")]
|
||||
pub dyn_dns_ip_versions: MaybeString,
|
||||
#[yaserde(rename = "DynDnsTtl")]
|
||||
pub dyn_dns_ttl: MaybeString,
|
||||
#[yaserde(rename = "DynDnsUpdateOnly")]
|
||||
pub dyn_dns_update_only: MaybeString,
|
||||
#[yaserde(rename = "AuthProvider")]
|
||||
pub auth_provider: MaybeString,
|
||||
#[yaserde(rename = "AuthToDomain")]
|
||||
pub auth_to_domain: MaybeString,
|
||||
#[yaserde(rename = "AuthToPort")]
|
||||
pub auth_to_port: MaybeString,
|
||||
#[yaserde(rename = "AuthToTls")]
|
||||
pub auth_to_tls: Option<i32>,
|
||||
#[yaserde(rename = "AuthToUri")]
|
||||
pub auth_to_uri: MaybeString,
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
use yaserde_derive::{YaDeserialize, YaSerialize};
|
||||
|
||||
use yaserde::MaybeString;
|
||||
|
||||
use super::opnsense::{NumberOption, Range, StaticMap};
|
||||
|
||||
// #[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
// #[yaserde(rename = "dhcpd")]
|
||||
// pub struct Dhcpd {
|
||||
// #[yaserde(rename = "lan")]
|
||||
// pub lan: DhcpInterface,
|
||||
// }
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct DhcpInterface {
|
||||
pub enable: Option<MaybeString>,
|
||||
pub gateway: Option<MaybeString>,
|
||||
pub domain: Option<MaybeString>,
|
||||
pub tftp: Option<String>,
|
||||
pub bootfilename: Option<String>,
|
||||
pub netboot: Option<u32>,
|
||||
pub nextserver: Option<String>,
|
||||
pub filename64: Option<String>,
|
||||
#[yaserde(rename = "ddnsdomainalgorithm")]
|
||||
pub ddns_domain_algorithm: Option<MaybeString>,
|
||||
#[yaserde(rename = "numberoptions")]
|
||||
pub number_options: Vec<NumberOption>,
|
||||
#[yaserde(rename = "range")]
|
||||
pub range: Range,
|
||||
pub winsserver: Option<MaybeString>,
|
||||
pub dnsserver: Option<MaybeString>,
|
||||
pub ntpserver: Option<MaybeString>,
|
||||
#[yaserde(rename = "staticmap")]
|
||||
pub staticmaps: Vec<StaticMap>,
|
||||
pub pool: Option<MaybeString>,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct DhcpRange {
|
||||
#[yaserde(rename = "from")]
|
||||
pub from: String,
|
||||
#[yaserde(rename = "to")]
|
||||
pub to: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::xml_utils::to_xml_str;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn dhcpd_should_deserialize_serialize_identical() {
|
||||
let dhcpd: Dhcpd =
|
||||
yaserde::de::from_str(SERIALIZED_DHCPD).expect("Deserialize Dhcpd failed");
|
||||
|
||||
assert_eq!(
|
||||
to_xml_str(&dhcpd).expect("Serialize Dhcpd failed"),
|
||||
SERIALIZED_DHCPD
|
||||
);
|
||||
}
|
||||
|
||||
const SERIALIZED_DHCPD: &str = "<?xml version=\"1.0\"?>
|
||||
<dhcpd>
|
||||
<lan>
|
||||
<enable>1</enable>
|
||||
<gateway>192.168.20.1</gateway>
|
||||
<domain>somedomain.yourlocal.mcd</domain>
|
||||
<ddnsdomainalgorithm>hmac-md5</ddnsdomainalgorithm>
|
||||
<numberoptions>
|
||||
<item/>
|
||||
</numberoptions>
|
||||
<range>
|
||||
<from>192.168.20.50</from>
|
||||
<to>192.168.20.200</to>
|
||||
</range>
|
||||
<winsserver/>
|
||||
<dnsserver>192.168.20.1</dnsserver>
|
||||
<ntpserver/>
|
||||
<staticmap>
|
||||
<mac>55:55:55:55:55:1c</mac>
|
||||
<ipaddr>192.168.20.160</ipaddr>
|
||||
<hostname>somehost983</hostname>
|
||||
<descr>someservire8</descr>
|
||||
<winsserver/>
|
||||
<dnsserver/>
|
||||
<ntpserver/>
|
||||
</staticmap>
|
||||
<staticmap>
|
||||
<mac>55:55:55:55:55:1c</mac>
|
||||
<ipaddr>192.168.20.155</ipaddr>
|
||||
<hostname>somehost893</hostname>
|
||||
<winsserver/>
|
||||
<dnsserver/>
|
||||
<ntpserver/>
|
||||
</staticmap>
|
||||
<staticmap>
|
||||
<mac>55:55:55:55:55:1c</mac>
|
||||
<ipaddr>192.168.20.165</ipaddr>
|
||||
<hostname>somehost893</hostname>
|
||||
<descr/>
|
||||
<winsserver/>
|
||||
<dnsserver/>
|
||||
<ntpserver/>
|
||||
</staticmap>
|
||||
<staticmap>
|
||||
<mac>55:55:55:55:55:1c</mac>
|
||||
<ipaddr>192.168.20.50</ipaddr>
|
||||
<hostname>hostswitch2</hostname>
|
||||
<descr>switch-2 (bottom)</descr>
|
||||
<winsserver/>
|
||||
<dnsserver/>
|
||||
<ntpserver/>
|
||||
</staticmap>
|
||||
<pool/>
|
||||
</lan>
|
||||
</dhcpd>\n";
|
||||
}
|
||||
@@ -1,637 +0,0 @@
|
||||
use rand;
|
||||
use rand::Rng;
|
||||
use xml::reader::XmlEvent as ReadEvent;
|
||||
use xml::writer::XmlEvent as WriteEvent;
|
||||
use yaserde::MaybeString;
|
||||
use yaserde::{YaDeserialize as YaDeserializeTrait, YaSerialize as YaSerializeTrait};
|
||||
use yaserde_derive::{YaDeserialize, YaSerialize};
|
||||
|
||||
impl YaDeserializeTrait for HAProxyId {
|
||||
fn deserialize<R: std::io::Read>(
|
||||
reader: &mut yaserde::de::Deserializer<R>,
|
||||
) -> Result<Self, String> {
|
||||
let _field_name = match reader.peek()? {
|
||||
ReadEvent::StartElement {
|
||||
name, attributes, ..
|
||||
} => {
|
||||
if attributes.len() > 0 {
|
||||
return Err(String::from(
|
||||
"Attributes not currently supported by HAProxyId",
|
||||
));
|
||||
}
|
||||
|
||||
name.local_name.clone()
|
||||
}
|
||||
_ => return Err(String::from("Unsupporte ReadEvent type")),
|
||||
};
|
||||
reader.next_event()?;
|
||||
|
||||
let content = match reader.peek()? {
|
||||
ReadEvent::Characters(content) => content.clone(),
|
||||
ReadEvent::EndElement { name: _ } => String::new(),
|
||||
_ => return Err(String::from("Unsupporte ReadEvent type")),
|
||||
};
|
||||
|
||||
Ok(Self(content))
|
||||
}
|
||||
}
|
||||
|
||||
impl YaSerializeTrait for HAProxyId {
|
||||
fn serialize<W: std::io::Write>(
|
||||
&self,
|
||||
writer: &mut yaserde::ser::Serializer<W>,
|
||||
) -> Result<(), String> {
|
||||
let yaserde_label = writer.get_start_event_name();
|
||||
|
||||
match yaserde_label {
|
||||
Some(label) => {
|
||||
let struct_start_event = xml::writer::XmlEvent::start_element(label.as_ref());
|
||||
writer
|
||||
.write(struct_start_event)
|
||||
.map_err(|_e| format!("Start element {label:?} write failed"))?;
|
||||
}
|
||||
None => return Err("HAPRoxyId must have a label preset in the writer".to_string()),
|
||||
};
|
||||
|
||||
writer
|
||||
.write(WriteEvent::characters(&self.0))
|
||||
.expect("Writer failed");
|
||||
|
||||
writer
|
||||
.write(WriteEvent::end_element())
|
||||
.expect("Writer failed");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_attributes(
|
||||
&self,
|
||||
_attributes: Vec<xml::attribute::OwnedAttribute>,
|
||||
_namespace: xml::namespace::Namespace,
|
||||
) -> Result<
|
||||
(
|
||||
Vec<xml::attribute::OwnedAttribute>,
|
||||
xml::namespace::Namespace,
|
||||
),
|
||||
String,
|
||||
> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
pub struct HAProxyId(String);
|
||||
|
||||
impl Default for HAProxyId {
|
||||
fn default() -> Self {
|
||||
let mut rng = rand::thread_rng();
|
||||
Self(format!("{:x}.{:x}", rng.gen::<u64>(), rng.gen::<u32>()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
#[yaserde(rename = "HAProxy")]
|
||||
pub struct HAProxy {
|
||||
#[yaserde(attribute = true)]
|
||||
pub version: String,
|
||||
pub general: HaProxyGeneral,
|
||||
pub frontends: HAProxyFrontends,
|
||||
pub backends: HAProxyBackends,
|
||||
pub servers: HAProxyServers,
|
||||
pub healthchecks: HAProxyHealthChecks,
|
||||
pub acls: MaybeString,
|
||||
pub actions: MaybeString,
|
||||
pub luas: MaybeString,
|
||||
pub fcgis: MaybeString,
|
||||
pub errorfiles: MaybeString,
|
||||
pub mapfiles: MaybeString,
|
||||
pub groups: MaybeString,
|
||||
pub users: MaybeString,
|
||||
pub cpus: MaybeString,
|
||||
pub resolvers: MaybeString,
|
||||
pub mailers: MaybeString,
|
||||
pub maintenance: Maintenance,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct Maintenance {
|
||||
#[yaserde(rename = "cronjobs")]
|
||||
pub cronjobs: CronJobs,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct CronJobs {
|
||||
#[yaserde(rename = "syncCerts")]
|
||||
pub sync_certs: u32,
|
||||
#[yaserde(rename = "syncCertsCron")]
|
||||
pub sync_certs_cron: MaybeString,
|
||||
#[yaserde(rename = "updateOcsp")]
|
||||
pub update_ocsp: u32,
|
||||
#[yaserde(rename = "updateOcspCron")]
|
||||
pub update_ocsp_cron: MaybeString,
|
||||
#[yaserde(rename = "reloadService")]
|
||||
pub reload_service: u32,
|
||||
#[yaserde(rename = "reloadServiceCron")]
|
||||
pub reload_service_cron: MaybeString,
|
||||
#[yaserde(rename = "restartService")]
|
||||
pub restart_service: u32,
|
||||
#[yaserde(rename = "restartServiceCron")]
|
||||
pub restart_service_cron: MaybeString,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct HaProxyGeneral {
|
||||
pub enabled: i32,
|
||||
#[yaserde(rename = "gracefulStop")]
|
||||
pub graceful_stop: i32,
|
||||
#[yaserde(rename = "hardStopAfter")]
|
||||
pub hard_stop_after: String,
|
||||
#[yaserde(rename = "closeSpreadTime")]
|
||||
pub close_spread_time: MaybeString,
|
||||
#[yaserde(rename = "seamlessReload")]
|
||||
pub seamless_reload: i32,
|
||||
#[yaserde(rename = "storeOcsp")]
|
||||
pub store_ocsp: i32,
|
||||
#[yaserde(rename = "showIntro")]
|
||||
pub show_intro: i32,
|
||||
pub peers: Peers,
|
||||
pub tuning: Tuning,
|
||||
pub defaults: HaProxyDefaults,
|
||||
pub logging: HaProxyLogging,
|
||||
pub stats: Stats,
|
||||
pub cache: HaProxyCache,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct Peers {
|
||||
pub enabled: i32,
|
||||
pub name1: MaybeString,
|
||||
pub listen1: MaybeString,
|
||||
pub port1: i32,
|
||||
pub name2: MaybeString,
|
||||
pub listen2: MaybeString,
|
||||
pub port2: i32,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct Tuning {
|
||||
pub root: i32,
|
||||
#[yaserde(rename = "maxConnections")]
|
||||
pub max_connections: MaybeString,
|
||||
pub nbthread: i32,
|
||||
#[yaserde(rename = "resolversPrefer")]
|
||||
pub resolvers_prefer: String,
|
||||
#[yaserde(rename = "sslServerVerify")]
|
||||
pub ssl_server_verify: String,
|
||||
#[yaserde(rename = "maxDHSize")]
|
||||
pub max_dh_size: i32,
|
||||
#[yaserde(rename = "bufferSize")]
|
||||
pub buffer_size: i32,
|
||||
#[yaserde(rename = "spreadChecks")]
|
||||
pub spread_checks: i32,
|
||||
#[yaserde(rename = "bogusProxyEnabled")]
|
||||
pub bogus_proxy_enabled: i32,
|
||||
#[yaserde(rename = "luaMaxMem")]
|
||||
pub lua_max_mem: i32,
|
||||
#[yaserde(rename = "customOptions")]
|
||||
pub custom_options: MaybeString,
|
||||
#[yaserde(rename = "ocspUpdateEnabled")]
|
||||
pub ocs_update_enabled: MaybeString,
|
||||
#[yaserde(rename = "ocspUpdateMinDelay")]
|
||||
pub ocs_update_min_delay: MaybeString,
|
||||
#[yaserde(rename = "ocspUpdateMaxDelay")]
|
||||
pub ocs_update_max_delay: MaybeString,
|
||||
#[yaserde(rename = "ssl_defaultsEnabled")]
|
||||
pub ssl_defaults_enabled: i32,
|
||||
#[yaserde(rename = "ssl_bindOptions")]
|
||||
pub ssl_bind_options: MaybeString,
|
||||
#[yaserde(rename = "ssl_minVersion")]
|
||||
pub ssl_min_version: MaybeString,
|
||||
#[yaserde(rename = "ssl_maxVersion")]
|
||||
pub ssl_max_version: MaybeString,
|
||||
#[yaserde(rename = "ssl_cipherList")]
|
||||
pub ssl_cipher_list: MaybeString,
|
||||
#[yaserde(rename = "ssl_cipherSuites")]
|
||||
pub ssl_cipher_suites: MaybeString,
|
||||
#[yaserde(rename = "h2_initialWindowSize")]
|
||||
pub h2_initial_window_size: Option<MaybeString>,
|
||||
#[yaserde(rename = "h2_initialWindowSizeOutgoing")]
|
||||
pub h2_initial_window_size_outgoing: Option<MaybeString>,
|
||||
#[yaserde(rename = "h2_initialWindowSizeIncoming")]
|
||||
pub h2_initial_window_size_incoming: Option<MaybeString>,
|
||||
#[yaserde(rename = "h2_maxConcurrentStreams")]
|
||||
pub h2_max_concurrent_streams: Option<MaybeString>,
|
||||
#[yaserde(rename = "h2_maxConcurrentStreamsOutgoing")]
|
||||
pub h2_max_concurrent_streams_outgoing: Option<MaybeString>,
|
||||
#[yaserde(rename = "h2_maxConcurrentStreamsIncoming")]
|
||||
pub h2_max_concurrent_streams_incoming: Option<MaybeString>,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct HaProxyDefaults {
|
||||
#[yaserde(rename = "maxConnections")]
|
||||
pub max_connections: MaybeString,
|
||||
#[yaserde(rename = "maxConnectionsServers")]
|
||||
pub max_connections_servers: MaybeString,
|
||||
#[yaserde(rename = "timeoutClient")]
|
||||
pub timeout_client: String,
|
||||
#[yaserde(rename = "timeoutConnect")]
|
||||
pub timeout_connect: String,
|
||||
#[yaserde(rename = "timeoutCheck")]
|
||||
pub timeout_check: MaybeString,
|
||||
#[yaserde(rename = "timeoutServer")]
|
||||
pub timeout_server: String,
|
||||
pub retries: i32,
|
||||
pub redispatch: String,
|
||||
pub init_addr: String,
|
||||
#[yaserde(rename = "customOptions")]
|
||||
pub custom_options: MaybeString,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct HaProxyLogging {
|
||||
pub host: String,
|
||||
pub facility: String,
|
||||
pub level: String,
|
||||
pub length: MaybeString,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct Stats {
|
||||
pub enabled: i32,
|
||||
pub port: i32,
|
||||
#[yaserde(rename = "remoteEnabled")]
|
||||
pub remote_enabled: i32,
|
||||
#[yaserde(rename = "remoteBind")]
|
||||
pub remote_bind: MaybeString,
|
||||
#[yaserde(rename = "authEnabled")]
|
||||
pub auth_enabled: i32,
|
||||
#[yaserde(rename = "users")]
|
||||
pub users: MaybeString,
|
||||
#[yaserde(rename = "allowedUsers")]
|
||||
pub allowed_users: MaybeString,
|
||||
#[yaserde(rename = "allowedGroups")]
|
||||
pub allowed_groups: MaybeString,
|
||||
#[yaserde(rename = "customOptions")]
|
||||
pub custom_options: MaybeString,
|
||||
pub prometheus_enabled: i32,
|
||||
pub prometheus_bind: String,
|
||||
pub prometheus_path: String,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct HaProxyCache {
|
||||
pub enabled: i32,
|
||||
#[yaserde(rename = "totalMaxSize")]
|
||||
pub total_max_size: i32,
|
||||
#[yaserde(rename = "maxAge")]
|
||||
pub max_age: i32,
|
||||
#[yaserde(rename = "maxObjectSize")]
|
||||
pub max_object_size: MaybeString,
|
||||
#[yaserde(rename = "processVary")]
|
||||
pub process_vary: i32,
|
||||
#[yaserde(rename = "maxSecondaryEntries")]
|
||||
pub max_secondary_entries: i32,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct HAProxyFrontends {
|
||||
pub frontend: Vec<Frontend>,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct Frontend {
|
||||
#[yaserde(attribute = true)]
|
||||
pub uuid: String,
|
||||
pub id: HAProxyId,
|
||||
pub enabled: i32,
|
||||
pub name: String,
|
||||
pub description: MaybeString,
|
||||
pub bind: String,
|
||||
#[yaserde(rename = "bindOptions")]
|
||||
pub bind_options: MaybeString,
|
||||
pub mode: String,
|
||||
#[yaserde(rename = "defaultBackend")]
|
||||
pub default_backend: String,
|
||||
pub ssl_enabled: i32,
|
||||
pub ssl_certificates: MaybeString,
|
||||
pub ssl_default_certificate: MaybeString,
|
||||
#[yaserde(rename = "ssl_customOptions")]
|
||||
pub ssl_custom_options: MaybeString,
|
||||
#[yaserde(rename = "ssl_advancedEnabled")]
|
||||
pub ssl_advanced_enabled: i32,
|
||||
#[yaserde(rename = "ssl_bindOptions")]
|
||||
pub ssl_bind_options: MaybeString,
|
||||
#[yaserde(rename = "ssl_minVersion")]
|
||||
pub ssl_min_version: MaybeString,
|
||||
#[yaserde(rename = "ssl_maxVersion")]
|
||||
pub ssl_max_version: MaybeString,
|
||||
#[yaserde(rename = "ssl_cipherList")]
|
||||
pub ssl_cipher_list: MaybeString,
|
||||
#[yaserde(rename = "ssl_cipherSuites")]
|
||||
pub ssl_cipher_suites: MaybeString,
|
||||
#[yaserde(rename = "ssl_hstsEnabled")]
|
||||
pub ssl_hsts_enabled: i32,
|
||||
#[yaserde(rename = "ssl_hstsIncludeSubDomains")]
|
||||
pub ssl_hsts_include_sub_domains: i32,
|
||||
#[yaserde(rename = "ssl_hstsPreload")]
|
||||
pub ssl_hsts_preload: i32,
|
||||
#[yaserde(rename = "ssl_hstsMaxAge")]
|
||||
pub ssl_hsts_max_age: i32,
|
||||
#[yaserde(rename = "ssl_clientAuthEnabled")]
|
||||
pub ssl_client_auth_enabled: i32,
|
||||
#[yaserde(rename = "ssl_clientAuthVerify")]
|
||||
pub ssl_client_auth_verify: MaybeString,
|
||||
#[yaserde(rename = "ssl_clientAuthCAs")]
|
||||
pub ssl_client_auth_cas: MaybeString,
|
||||
#[yaserde(rename = "ssl_clientAuthCRLs")]
|
||||
pub ssl_client_auth_cr_ls: MaybeString,
|
||||
#[yaserde(rename = "basicAuthEnabled")]
|
||||
pub basic_auth_enabled: i32,
|
||||
#[yaserde(rename = "basicAuthUsers")]
|
||||
pub basic_auth_users: MaybeString,
|
||||
#[yaserde(rename = "basicAuthGroups")]
|
||||
pub basic_auth_groups: MaybeString,
|
||||
#[yaserde(rename = "tuning_maxConnections")]
|
||||
pub tuning_max_connections: MaybeString,
|
||||
#[yaserde(rename = "tuning_timeoutClient")]
|
||||
pub tuning_timeout_client: MaybeString,
|
||||
#[yaserde(rename = "tuning_timeoutHttpReq")]
|
||||
pub tuning_timeout_http_req: MaybeString,
|
||||
#[yaserde(rename = "tuning_timeoutHttpKeepAlive")]
|
||||
pub tuning_timeout_http_keep_alive: MaybeString,
|
||||
#[yaserde(rename = "linkedCpuAffinityRules")]
|
||||
pub linked_cpu_affinity_rules: MaybeString,
|
||||
pub tuning_shards: MaybeString,
|
||||
#[yaserde(rename = "logging_dontLogNull")]
|
||||
pub logging_dont_log_null: i32,
|
||||
#[yaserde(rename = "logging_dontLogNormal")]
|
||||
pub logging_dont_log_normal: i32,
|
||||
#[yaserde(rename = "logging_logSeparateErrors")]
|
||||
pub logging_log_separate_errors: i32,
|
||||
#[yaserde(rename = "logging_detailedLog")]
|
||||
pub logging_detailed_log: i32,
|
||||
#[yaserde(rename = "logging_socketStats")]
|
||||
pub logging_socket_stats: i32,
|
||||
pub stickiness_pattern: MaybeString,
|
||||
#[yaserde(rename = "stickiness_dataTypes")]
|
||||
pub stickiness_data_types: MaybeString,
|
||||
pub stickiness_expire: MaybeString,
|
||||
pub stickiness_size: MaybeString,
|
||||
pub stickiness_counter: i32,
|
||||
pub stickiness_counter_key: MaybeString,
|
||||
pub stickiness_length: MaybeString,
|
||||
#[yaserde(rename = "stickiness_connRatePeriod")]
|
||||
pub stickiness_conn_rate_period: MaybeString,
|
||||
#[yaserde(rename = "stickiness_sessRatePeriod")]
|
||||
pub stickiness_sess_rate_period: MaybeString,
|
||||
#[yaserde(rename = "stickiness_httpReqRatePeriod")]
|
||||
pub stickiness_http_req_rate_period: MaybeString,
|
||||
#[yaserde(rename = "stickiness_httpErrRatePeriod")]
|
||||
pub stickiness_http_err_rate_period: MaybeString,
|
||||
#[yaserde(rename = "stickiness_bytesInRatePeriod")]
|
||||
pub stickiness_bytes_in_rate_period: MaybeString,
|
||||
#[yaserde(rename = "stickiness_bytesOutRatePeriod")]
|
||||
pub stickiness_bytes_out_rate_period: MaybeString,
|
||||
#[yaserde(rename = "http2Enabled")]
|
||||
pub http2_enabled: i32,
|
||||
#[yaserde(rename = "http2Enabled_nontls")]
|
||||
pub http2_enabled_nontls: i32,
|
||||
pub advertised_protocols: MaybeString,
|
||||
#[yaserde(rename = "forwardFor")]
|
||||
pub forward_for: i32,
|
||||
pub prometheus_enabled: i32,
|
||||
pub prometheus_path: MaybeString,
|
||||
#[yaserde(rename = "connectionBehaviour")]
|
||||
pub connection_behaviour: MaybeString,
|
||||
#[yaserde(rename = "customOptions")]
|
||||
pub custom_options: MaybeString,
|
||||
#[yaserde(rename = "linkedActions")]
|
||||
pub linked_actions: MaybeString,
|
||||
#[yaserde(rename = "linkedErrorfiles")]
|
||||
pub linked_error_files: MaybeString,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct HAProxyBackends {
|
||||
#[yaserde(rename = "backend")]
|
||||
pub backends: Vec<HAProxyBackend>,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct HAProxyBackend {
|
||||
#[yaserde(attribute = true, rename = "uuid")]
|
||||
pub uuid: String,
|
||||
#[yaserde(rename = "id")]
|
||||
pub id: HAProxyId,
|
||||
#[yaserde(rename = "enabled")]
|
||||
pub enabled: u8,
|
||||
#[yaserde(rename = "name")]
|
||||
pub name: String,
|
||||
#[yaserde(rename = "description")]
|
||||
pub description: MaybeString,
|
||||
#[yaserde(rename = "mode")]
|
||||
pub mode: String,
|
||||
#[yaserde(rename = "algorithm")]
|
||||
pub algorithm: String,
|
||||
#[yaserde(rename = "random_draws")]
|
||||
pub random_draws: Option<u32>,
|
||||
#[yaserde(rename = "proxyProtocol")]
|
||||
pub proxy_protocol: MaybeString,
|
||||
#[yaserde(rename = "linkedServers")]
|
||||
pub linked_servers: MaybeString,
|
||||
#[yaserde(rename = "linkedFcgi")]
|
||||
pub linked_fcgi: MaybeString,
|
||||
#[yaserde(rename = "linkedResolver")]
|
||||
pub linked_resolver: MaybeString,
|
||||
#[yaserde(rename = "resolverOpts")]
|
||||
pub resolver_opts: MaybeString,
|
||||
#[yaserde(rename = "resolvePrefer")]
|
||||
pub resolve_prefer: MaybeString,
|
||||
#[yaserde(rename = "source")]
|
||||
pub source: MaybeString,
|
||||
#[yaserde(rename = "healthCheckEnabled")]
|
||||
pub health_check_enabled: u8,
|
||||
#[yaserde(rename = "healthCheck")]
|
||||
pub health_check: MaybeString,
|
||||
#[yaserde(rename = "healthCheckLogStatus")]
|
||||
pub health_check_log_status: u8,
|
||||
#[yaserde(rename = "checkInterval")]
|
||||
pub check_interval: MaybeString,
|
||||
#[yaserde(rename = "checkDownInterval")]
|
||||
pub check_down_interval: MaybeString,
|
||||
#[yaserde(rename = "healthCheckFall")]
|
||||
pub health_check_fall: MaybeString,
|
||||
#[yaserde(rename = "healthCheckRise")]
|
||||
pub health_check_rise: MaybeString,
|
||||
#[yaserde(rename = "linkedMailer")]
|
||||
pub linked_mailer: MaybeString,
|
||||
#[yaserde(rename = "http2Enabled")]
|
||||
pub http2_enabled: u8,
|
||||
#[yaserde(rename = "http2Enabled_nontls")]
|
||||
pub http2_enabled_nontls: u8,
|
||||
#[yaserde(rename = "ba_advertised_protocols")]
|
||||
pub ba_advertised_protocols: MaybeString,
|
||||
#[yaserde(rename = "forwardFor")]
|
||||
pub forward_for: Option<i32>,
|
||||
#[yaserde(rename = "forwardedHeader")]
|
||||
pub forwarded_header: Option<MaybeString>,
|
||||
#[yaserde(rename = "forwardedHeaderParameters")]
|
||||
pub forwarded_header_parameters: Option<MaybeString>,
|
||||
pub persistence: MaybeString,
|
||||
pub persistence_cookiemode: MaybeString,
|
||||
pub persistence_cookiename: MaybeString,
|
||||
pub persistence_stripquotes: u8,
|
||||
pub stickiness_pattern: MaybeString,
|
||||
#[yaserde(rename = "stickiness_dataTypes")]
|
||||
pub stickiness_data_types: MaybeString,
|
||||
pub stickiness_expire: String,
|
||||
pub stickiness_size: String,
|
||||
pub stickiness_cookiename: MaybeString,
|
||||
pub stickiness_cookielength: MaybeString,
|
||||
#[yaserde(rename = "stickiness_connRatePeriod")]
|
||||
pub stickiness_conn_rate_period: String,
|
||||
#[yaserde(rename = "stickiness_sessRatePeriod")]
|
||||
pub stickiness_sess_rate_period: String,
|
||||
#[yaserde(rename = "stickiness_httpReqRatePeriod")]
|
||||
pub stickiness_http_req_rate_period: String,
|
||||
#[yaserde(rename = "stickiness_httpErrRatePeriod")]
|
||||
pub stickiness_http_err_rate_period: String,
|
||||
#[yaserde(rename = "stickiness_bytesInRatePeriod")]
|
||||
pub stickiness_bytes_in_rate_period: String,
|
||||
#[yaserde(rename = "stickiness_bytesOutRatePeriod")]
|
||||
pub stickiness_bytes_out_rate_period: String,
|
||||
#[yaserde(rename = "basicAuthEnabled")]
|
||||
pub basic_auth_enabled: u8,
|
||||
#[yaserde(rename = "basicAuthUsers")]
|
||||
pub basic_auth_users: MaybeString,
|
||||
#[yaserde(rename = "basicAuthGroups")]
|
||||
pub basic_auth_groups: MaybeString,
|
||||
#[yaserde(rename = "tuning_timeoutConnect")]
|
||||
pub tuning_timeout_connect: MaybeString,
|
||||
#[yaserde(rename = "tuning_timeoutCheck")]
|
||||
pub tuning_timeout_check: MaybeString,
|
||||
#[yaserde(rename = "tuning_timeoutServer")]
|
||||
pub tuning_timeout_server: MaybeString,
|
||||
#[yaserde(rename = "tuning_retries")]
|
||||
pub tuning_retries: MaybeString,
|
||||
#[yaserde(rename = "customOptions")]
|
||||
pub custom_options: MaybeString,
|
||||
#[yaserde(rename = "tuning_defaultserver")]
|
||||
pub tuning_defaultserver: MaybeString,
|
||||
#[yaserde(rename = "tuning_noport")]
|
||||
pub tuning_noport: u8,
|
||||
#[yaserde(rename = "tuning_httpreuse")]
|
||||
pub tuning_httpreuse: MaybeString,
|
||||
#[yaserde(rename = "tuning_caching")]
|
||||
pub tuning_caching: u8,
|
||||
#[yaserde(rename = "linkedActions")]
|
||||
pub linked_actions: MaybeString,
|
||||
#[yaserde(rename = "linkedErrorfiles")]
|
||||
pub linked_errorfiles: MaybeString,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct HAProxyServers {
|
||||
#[yaserde(rename = "server")]
|
||||
pub servers: Vec<HAProxyServer>,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct HAProxyServer {
|
||||
#[yaserde(attribute = true, rename = "uuid")]
|
||||
pub uuid: String,
|
||||
pub id: HAProxyId,
|
||||
pub enabled: u8,
|
||||
pub name: String,
|
||||
pub description: MaybeString,
|
||||
pub address: String,
|
||||
pub port: u16,
|
||||
pub checkport: MaybeString,
|
||||
pub mode: String,
|
||||
pub multiplexer_protocol: MaybeString,
|
||||
#[yaserde(rename = "type")]
|
||||
pub server_type: String,
|
||||
#[yaserde(rename = "serviceName")]
|
||||
pub service_name: MaybeString,
|
||||
pub number: MaybeString,
|
||||
#[yaserde(rename = "linkedResolver")]
|
||||
pub linked_resolver: MaybeString,
|
||||
#[yaserde(rename = "resolverOpts")]
|
||||
pub resolver_opts: MaybeString,
|
||||
#[yaserde(rename = "resolvePrefer")]
|
||||
pub resolve_prefer: MaybeString,
|
||||
pub ssl: u8,
|
||||
#[yaserde(rename = "sslSNI")]
|
||||
pub ssl_sni: MaybeString,
|
||||
#[yaserde(rename = "sslVerify")]
|
||||
pub ssl_verify: u8,
|
||||
#[yaserde(rename = "sslCA")]
|
||||
pub ssl_ca: MaybeString,
|
||||
#[yaserde(rename = "sslCRL")]
|
||||
pub ssl_crl: MaybeString,
|
||||
#[yaserde(rename = "sslClientCertificate")]
|
||||
pub ssl_client_certificate: MaybeString,
|
||||
#[yaserde(rename = "maxConnections")]
|
||||
pub max_connections: MaybeString,
|
||||
pub weight: Option<u32>,
|
||||
#[yaserde(rename = "checkInterval")]
|
||||
pub check_interval: MaybeString,
|
||||
#[yaserde(rename = "checkDownInterval")]
|
||||
pub check_down_interval: MaybeString,
|
||||
pub source: MaybeString,
|
||||
pub advanced: MaybeString,
|
||||
#[yaserde(rename = "unix_socket")]
|
||||
pub unix_socket: MaybeString,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct HAProxyHealthChecks {
|
||||
#[yaserde(rename = "healthcheck")]
|
||||
pub healthchecks: Vec<HAProxyHealthCheck>,
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
|
||||
pub struct HAProxyHealthCheck {
|
||||
#[yaserde(attribute = true)]
|
||||
pub uuid: String,
|
||||
pub name: String,
|
||||
pub description: MaybeString,
|
||||
#[yaserde(rename = "type")]
|
||||
pub health_check_type: String,
|
||||
pub interval: String,
|
||||
pub ssl: MaybeString,
|
||||
#[yaserde(rename = "sslSNI")]
|
||||
pub ssl_sni: MaybeString,
|
||||
pub force_ssl: u8,
|
||||
pub checkport: MaybeString,
|
||||
pub http_method: MaybeString,
|
||||
pub http_uri: MaybeString,
|
||||
pub http_version: MaybeString,
|
||||
#[yaserde(rename = "http_host")]
|
||||
pub http_host: MaybeString,
|
||||
#[yaserde(rename = "http_expressionEnabled")]
|
||||
pub http_expression_enabled: Option<u8>,
|
||||
pub http_expression: MaybeString,
|
||||
pub http_negate: MaybeString,
|
||||
pub http_value: MaybeString,
|
||||
pub tcp_enabled: MaybeString,
|
||||
#[yaserde(rename = "tcp_sendValue")]
|
||||
pub tcp_send_value: MaybeString,
|
||||
#[yaserde(rename = "tcp_matchType")]
|
||||
pub tcp_match_type: MaybeString,
|
||||
pub tcp_negate: MaybeString,
|
||||
#[yaserde(rename = "tcp_matchValue")]
|
||||
pub tcp_match_value: MaybeString,
|
||||
pub agent_port: MaybeString,
|
||||
pub mysql_user: MaybeString,
|
||||
pub mysql_post41: MaybeString,
|
||||
pub pgsql_user: MaybeString,
|
||||
pub smtp_domain: MaybeString,
|
||||
pub esmtp_domain: MaybeString,
|
||||
#[yaserde(rename = "agentPort")]
|
||||
pub agent_port_uppercase: MaybeString,
|
||||
#[yaserde(rename = "dbUser")]
|
||||
pub db_user: MaybeString,
|
||||
#[yaserde(rename = "smtpDomain")]
|
||||
pub smtp_domain_uppercase: MaybeString,
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
use yaserde_derive::{YaDeserialize, YaSerialize};
|
||||
|
||||
use yaserde::MaybeString;
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct Interface {
|
||||
pub internal_dynamic: Option<MaybeString>,
|
||||
#[yaserde(rename = "if")]
|
||||
pub physical_interface_name: String,
|
||||
pub descr: Option<MaybeString>,
|
||||
pub enable: MaybeString,
|
||||
pub lock: Option<MaybeString>,
|
||||
#[yaserde(rename = "spoofmac")]
|
||||
pub spoof_mac: Option<MaybeString>,
|
||||
pub ipaddr: Option<MaybeString>,
|
||||
pub dhcphostname: Option<MaybeString>,
|
||||
#[yaserde(rename = "alias-address")]
|
||||
pub alias_address: Option<MaybeString>,
|
||||
#[yaserde(rename = "alias-subnet")]
|
||||
pub alias_subnet: Option<MaybeString>,
|
||||
#[yaserde(rename = "blockpriv")]
|
||||
pub block_priv: Option<MaybeString>,
|
||||
#[yaserde(rename = "blockbogons")]
|
||||
pub block_bogons: Option<MaybeString>,
|
||||
#[yaserde(rename = "type")]
|
||||
pub r#type: Option<MaybeString>,
|
||||
#[yaserde(rename = "virtual")]
|
||||
pub r#virtual: Option<MaybeString>,
|
||||
pub subnet: Option<MaybeString>,
|
||||
pub ipaddrv6: Option<MaybeString>,
|
||||
#[yaserde(rename = "dhcp6-ia-pd-len")]
|
||||
pub dhcp6_ia_pd_len: Option<MaybeString>,
|
||||
pub networks: Option<MaybeString>,
|
||||
pub subnetv6: Option<MaybeString>,
|
||||
pub gateway: Option<MaybeString>,
|
||||
pub gatewayv6: Option<MaybeString>,
|
||||
pub media: Option<MaybeString>,
|
||||
pub mediaopt: Option<MaybeString>,
|
||||
#[yaserde(rename = "track6-interface")]
|
||||
pub track6_interface: Option<MaybeString>,
|
||||
#[yaserde(rename = "track6-prefix-id")]
|
||||
pub track6_prefix_id: Option<MaybeString>,
|
||||
#[yaserde(rename = "dhcprejectfrom")]
|
||||
pub dhcprejectfrom: Option<MaybeString>,
|
||||
pub adv_dhcp6_interface_statement_send_options: Option<MaybeString>,
|
||||
pub adv_dhcp6_interface_statement_request_options: Option<MaybeString>,
|
||||
pub adv_dhcp6_interface_statement_information_only_enable: Option<MaybeString>,
|
||||
pub adv_dhcp6_interface_statement_script: Option<MaybeString>,
|
||||
pub adv_dhcp6_id_assoc_statement_address_enable: Option<MaybeString>,
|
||||
pub adv_dhcp6_id_assoc_statement_address: Option<MaybeString>,
|
||||
pub adv_dhcp6_id_assoc_statement_address_id: Option<MaybeString>,
|
||||
pub adv_dhcp6_id_assoc_statement_address_pltime: Option<MaybeString>,
|
||||
pub adv_dhcp6_id_assoc_statement_address_vltime: Option<MaybeString>,
|
||||
pub adv_dhcp6_id_assoc_statement_prefix_enable: Option<MaybeString>,
|
||||
pub adv_dhcp6_id_assoc_statement_prefix: Option<MaybeString>,
|
||||
pub adv_dhcp6_id_assoc_statement_prefix_id: Option<MaybeString>,
|
||||
pub adv_dhcp6_id_assoc_statement_prefix_pltime: Option<MaybeString>,
|
||||
pub adv_dhcp6_id_assoc_statement_prefix_vltime: Option<MaybeString>,
|
||||
pub adv_dhcp6_prefix_interface_statement_sla_len: Option<MaybeString>,
|
||||
pub adv_dhcp6_authentication_statement_authname: Option<MaybeString>,
|
||||
pub adv_dhcp6_authentication_statement_protocol: Option<MaybeString>,
|
||||
pub adv_dhcp6_authentication_statement_algorithm: Option<MaybeString>,
|
||||
pub adv_dhcp6_authentication_statement_rdm: Option<MaybeString>,
|
||||
pub adv_dhcp6_key_info_statement_keyname: Option<MaybeString>,
|
||||
pub adv_dhcp6_key_info_statement_realm: Option<MaybeString>,
|
||||
pub adv_dhcp6_key_info_statement_keyid: Option<MaybeString>,
|
||||
pub adv_dhcp6_key_info_statement_secret: Option<MaybeString>,
|
||||
pub adv_dhcp6_key_info_statement_expire: Option<MaybeString>,
|
||||
pub adv_dhcp6_config_advanced: Option<MaybeString>,
|
||||
pub adv_dhcp6_config_file_override: Option<MaybeString>,
|
||||
pub adv_dhcp6_config_file_override_path: Option<MaybeString>,
|
||||
pub adv_dhcp_pt_timeout: Option<MaybeString>,
|
||||
pub adv_dhcp_pt_retry: Option<MaybeString>,
|
||||
pub adv_dhcp_pt_select_timeout: Option<MaybeString>,
|
||||
pub adv_dhcp_pt_reboot: Option<MaybeString>,
|
||||
pub adv_dhcp_pt_backoff_cutoff: Option<MaybeString>,
|
||||
pub adv_dhcp_pt_initial_interval: Option<MaybeString>,
|
||||
pub adv_dhcp_pt_values: Option<MaybeString>,
|
||||
pub adv_dhcp_send_options: Option<MaybeString>,
|
||||
pub adv_dhcp_request_options: Option<MaybeString>,
|
||||
pub adv_dhcp_required_options: Option<MaybeString>,
|
||||
pub adv_dhcp_option_modifiers: Option<MaybeString>,
|
||||
pub adv_dhcp_config_advanced: Option<MaybeString>,
|
||||
pub adv_dhcp_config_file_override: Option<MaybeString>,
|
||||
pub adv_dhcp_config_file_override_path: Option<MaybeString>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::xml_utils::to_xml_str;
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use yaserde::NamedList;
|
||||
|
||||
#[derive(Default, PartialEq, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct InterfacesParent {
|
||||
foo: String,
|
||||
interfaces: NamedList<Interface>,
|
||||
bar: String,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_deserialize_interfaces() {
|
||||
let interfaces =
|
||||
yaserde::de::from_str::<NamedList<Interface>>(FULL_INTERFACES_XML).unwrap();
|
||||
assert_eq!(interfaces.elements.len(), 6)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_serialize_interfaces() {
|
||||
let named_list = NamedList {
|
||||
elements: vec![
|
||||
(String::from("paul"), Interface::default()),
|
||||
(String::from("anotherpaul"), Interface::default()),
|
||||
(String::from("thirdone"), Interface::default()),
|
||||
(String::from("andgofor4"), Interface::default()),
|
||||
],
|
||||
};
|
||||
|
||||
let parent = InterfacesParent {
|
||||
foo: String::from("foo"),
|
||||
interfaces: named_list,
|
||||
bar: String::from("foo"),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
&to_xml_str(&parent).unwrap(),
|
||||
r#"<?xml version="1.0"?>
|
||||
<InterfacesParent>
|
||||
<foo>foo</foo>
|
||||
<interfaces>
|
||||
<paul>
|
||||
<if></if>
|
||||
<descr></descr>
|
||||
<enable/>
|
||||
</paul>
|
||||
<anotherpaul>
|
||||
<if></if>
|
||||
<descr></descr>
|
||||
<enable/>
|
||||
</anotherpaul>
|
||||
<thirdone>
|
||||
<if></if>
|
||||
<descr></descr>
|
||||
<enable/>
|
||||
</thirdone>
|
||||
<andgofor4>
|
||||
<if></if>
|
||||
<descr></descr>
|
||||
<enable/>
|
||||
</andgofor4>
|
||||
</interfaces>
|
||||
<bar>foo</bar>
|
||||
</InterfacesParent>
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
const FULL_INTERFACES_XML: &str = "<interfaces>
|
||||
<lan>
|
||||
<if>em1</if>
|
||||
<descr>LAN</descr>
|
||||
<enable>1</enable>
|
||||
<spoofmac/>
|
||||
<media/>
|
||||
<mediaopt/>
|
||||
<ipaddr>192.168.20.1</ipaddr>
|
||||
<subnet>24</subnet>
|
||||
<ipaddrv6>track6</ipaddrv6>
|
||||
<track6-interface/>
|
||||
<track6-prefix-id>0</track6-prefix-id>
|
||||
</lan>
|
||||
<wan>
|
||||
<if>pppoe0</if>
|
||||
<descr>WAN</descr>
|
||||
<enable>1</enable>
|
||||
<lock>1</lock>
|
||||
<spoofmac/>
|
||||
<blockpriv>1</blockpriv>
|
||||
<blockbogons>1</blockbogons>
|
||||
<ipaddr>pppoe</ipaddr>
|
||||
</wan>
|
||||
<lo0>
|
||||
<internal_dynamic>1</internal_dynamic>
|
||||
<descr>Loopback</descr>
|
||||
<enable>1</enable>
|
||||
<if>lo0</if>
|
||||
<ipaddr>127.0.0.1</ipaddr>
|
||||
<ipaddrv6>::1</ipaddrv6>
|
||||
<subnet>8</subnet>
|
||||
<subnetv6>128</subnetv6>
|
||||
<type>none</type>
|
||||
<virtual>1</virtual>
|
||||
</lo0>
|
||||
<opt1>
|
||||
<if>em5</if>
|
||||
<descr>backup_sync</descr>
|
||||
<enable>1</enable>
|
||||
<lock>1</lock>
|
||||
<spoofmac/>
|
||||
<ipaddr>10.10.5.1</ipaddr>
|
||||
<subnet>24</subnet>
|
||||
</opt1>
|
||||
<wireguard>
|
||||
<internal_dynamic>1</internal_dynamic>
|
||||
<descr>WireGuard (Group)</descr>
|
||||
<if>wireguard</if>
|
||||
<virtual>1</virtual>
|
||||
<enable>1</enable>
|
||||
<type>group</type>
|
||||
<networks/>
|
||||
</wireguard>
|
||||
<openvpn>
|
||||
<internal_dynamic>1</internal_dynamic>
|
||||
<enable>1</enable>
|
||||
<if>openvpn</if>
|
||||
<descr>OpenVPN</descr>
|
||||
<type>group</type>
|
||||
<virtual>1</virtual>
|
||||
<networks/>
|
||||
</openvpn>
|
||||
</interfaces>";
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
mod caddy;
|
||||
mod dhcpd;
|
||||
mod haproxy;
|
||||
mod interfaces;
|
||||
mod opnsense;
|
||||
pub use caddy::*;
|
||||
pub use dhcpd::*;
|
||||
pub use haproxy::*;
|
||||
pub use interfaces::*;
|
||||
pub use opnsense::*;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +0,0 @@
|
||||
mod data;
|
||||
mod xml_utils;
|
||||
pub use data::*;
|
||||
pub use yaserde::MaybeString;
|
||||
@@ -1,20 +0,0 @@
|
||||
use yaserde::YaSerialize;
|
||||
|
||||
pub fn to_xml_str<T: YaSerialize>(model: &T) -> Result<String, String> {
|
||||
let yaserde_cfg = yaserde::ser::Config {
|
||||
perform_indent: true,
|
||||
write_document_declaration: false,
|
||||
pad_self_closing: false,
|
||||
..Default::default()
|
||||
};
|
||||
let serialized = yaserde::ser::to_string_with_config::<T>(model, &yaserde_cfg)?;
|
||||
|
||||
// Opnsense does not specify encoding in the document declaration
|
||||
//
|
||||
// yaserde / xml-rs does not allow disabling the encoding attribute in the
|
||||
// document declaration
|
||||
//
|
||||
// So here we just manually prefix the xml document with the exact document declaration
|
||||
// that opnsense uses
|
||||
Ok(format!("<?xml version=\"1.0\"?>\n{serialized}\n"))
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
[package]
|
||||
name = "opnsense-config"
|
||||
edition = "2021"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0.123", features = [ "derive" ] }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
russh = { workspace = true }
|
||||
russh-keys = { workspace = true }
|
||||
thiserror = "1.0"
|
||||
async-trait = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
opnsense-config-xml = { path = "../opnsense-config-xml" }
|
||||
chrono = "0.4.38"
|
||||
russh-sftp = "2.0.6"
|
||||
serde_json = "1.0.133"
|
||||
tokio-util = { version = "0.7.13", features = [ "codec" ] }
|
||||
tokio-stream = "0.1.17"
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = "1.4.1"
|
||||
@@ -1,38 +0,0 @@
|
||||
# Architecture Decision Record: Using yaserde for OPNsense Config Parsing
|
||||
|
||||
- Status : Proposed
|
||||
- Author : Jean-Gabriel Gill-Couture
|
||||
|
||||
## Context
|
||||
|
||||
We need to parse and manipulate the OPNsense config.xml file in our Rust crate. We considered several XML parsing libraries, including quick-xml, xml-dom, minidom and yaserde. Each library has its own strengths and trade-offs in terms of performance, ease of use, and robustness.
|
||||
|
||||
## Decision
|
||||
|
||||
We have decided to use yaserde for parsing and manipulating the OPNsense config.xml file.
|
||||
|
||||
## Rationale
|
||||
|
||||
1. Type Safety: yaserde allows us to define a complete Rust representation of the config.xml structure. This provides strong type safety and makes it easier to catch errors at compile-time rather than runtime.
|
||||
|
||||
2. Robustness: By mapping the entire config structure to Rust types, we ensure that our code interacts with the config in a well-defined manner. This reduces the risk of runtime errors due to unexpected XML structures.
|
||||
|
||||
3. Ease of Use: Working with native Rust types is more intuitive and less error-prone than manipulating XML directly. This can lead to more maintainable and readable code.
|
||||
|
||||
4. Memory Usage: While yaserde may use more memory than streaming parsers like quick-xml, the OPNsense config files are typically not large enough for this to be a significant concern. We prioritize robustness and ease of use over minimal memory usage in this context.
|
||||
|
||||
5. Serialization/Deserialization: yaserde provides both deserialization (XML to Rust structs) and serialization (Rust structs to XML) out of the box, which simplifies our implementation.
|
||||
|
||||
## Consequences
|
||||
|
||||
Positive:
|
||||
- Increased type safety and robustness in handling the config.xml structure.
|
||||
- More intuitive API for developers working with the config.
|
||||
- Easier to extend and maintain the code that interacts with different parts of the config.
|
||||
|
||||
Negative:
|
||||
- It will be harder to maintain when there are breaking changes in the config.xml format. Any structural changes in the XML will require corresponding updates to our Rust struct definitions.
|
||||
- Slightly higher memory usage compared to streaming parsers.
|
||||
- Initial development time may be longer due to the need to define the entire config structure upfront.
|
||||
|
||||
We accept the trade-off of potentially more difficult maintenance in the face of breaking config.xml changes, as we believe the benefits of increased robustness and type safety outweigh this drawback. When OPNsense releases updates that change the config.xml structure, we will need to update our Rust struct definitions accordingly.
|
||||
@@ -1,322 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
config::{SshConfigManager, SshCredentials, SshOPNSenseShell},
|
||||
error::Error,
|
||||
modules::{
|
||||
caddy::CaddyConfig, dhcp::DhcpConfig, dns::DnsConfig, load_balancer::LoadBalancerConfig,
|
||||
tftp::TftpConfig,
|
||||
},
|
||||
};
|
||||
use log::{debug, info, trace, warn};
|
||||
use opnsense_config_xml::OPNsense;
|
||||
use russh::client;
|
||||
|
||||
use super::{ConfigManager, OPNsenseShell};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Config {
|
||||
opnsense: OPNsense,
|
||||
repository: Arc<dyn ConfigManager>,
|
||||
shell: Arc<dyn OPNsenseShell>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub async fn new(
|
||||
repository: Arc<dyn ConfigManager>,
|
||||
shell: Arc<dyn OPNsenseShell>,
|
||||
) -> Result<Self, Error> {
|
||||
Ok(Self {
|
||||
opnsense: Self::get_opnsense_instance(repository.clone()).await?,
|
||||
repository,
|
||||
shell,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn dhcp(&mut self) -> DhcpConfig {
|
||||
DhcpConfig::new(&mut self.opnsense, self.shell.clone())
|
||||
}
|
||||
|
||||
pub fn dns(&mut self) -> DnsConfig {
|
||||
DnsConfig::new(&mut self.opnsense)
|
||||
}
|
||||
|
||||
pub fn tftp(&mut self) -> TftpConfig {
|
||||
TftpConfig::new(&mut self.opnsense, self.shell.clone())
|
||||
}
|
||||
|
||||
pub fn caddy(&mut self) -> CaddyConfig {
|
||||
CaddyConfig::new(&mut self.opnsense, self.shell.clone())
|
||||
}
|
||||
|
||||
pub fn load_balancer(&mut self) -> LoadBalancerConfig {
|
||||
LoadBalancerConfig::new(&mut self.opnsense, self.shell.clone())
|
||||
}
|
||||
|
||||
pub async fn upload_files(&self, source: &str, destination: &str) -> Result<String, Error> {
|
||||
self.shell.upload_folder(source, destination).await
|
||||
}
|
||||
|
||||
/// Checks in config file if system.firmware.plugins csv field contains the specified package
|
||||
/// name.
|
||||
///
|
||||
/// Given this
|
||||
/// ```xml
|
||||
/// <opnsense>
|
||||
/// <system>
|
||||
/// <firmware>
|
||||
/// <plugins>os-haproxy,os-iperf,os-cpu-microcode-intel</plugins>
|
||||
/// </firmware>
|
||||
/// </system>
|
||||
/// </opnsense>
|
||||
/// ```
|
||||
///
|
||||
/// is_package_installed("os-cpu"); // false
|
||||
/// is_package_installed("os-haproxy"); // true
|
||||
/// is_package_installed("os-cpu-microcode-intel"); // true
|
||||
pub fn is_package_installed(&self, package_name: &str) -> bool {
|
||||
match &self.opnsense.system.firmware.plugins.content {
|
||||
Some(plugins) => is_package_in_csv(plugins, package_name),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
// Here maybe we should take ownership of `mut self` instead of `&mut self`
|
||||
// I don't think there can be faulty pointers to previous versions of the config but I have a
|
||||
// hard time wrapping my head around it right now :
|
||||
// - the caller has a mutable reference to us
|
||||
// - caller gets a reference to a piece of configuration (.haproxy.general.servers[0])
|
||||
// - caller calls install_package wich reloads the config from remote
|
||||
// - haproxy.general.servers[0] does not exist anymore
|
||||
// - broken?
|
||||
//
|
||||
// Although I did not try explicitely the above workflow so maybe rust prevents taking a
|
||||
// read-only reference across the &mut call
|
||||
pub async fn install_package(&mut self, package_name: &str) -> Result<(), Error> {
|
||||
info!("Installing opnsense package {package_name}");
|
||||
self.check_pkg_opnsense_org_connection().await?;
|
||||
|
||||
let output = self.shell
|
||||
.exec(&format!("/bin/sh -c \"export LOCKFILE=/dev/stdout && /usr/local/opnsense/scripts/firmware/install.sh {package_name}\""))
|
||||
.await?;
|
||||
info!("Installation output {output}");
|
||||
|
||||
self.reload_config().await?;
|
||||
let is_installed = self.is_package_installed(package_name);
|
||||
debug!("Verifying package installed successfully {is_installed}");
|
||||
|
||||
if is_installed {
|
||||
info!("Installation successful for {package_name}");
|
||||
Ok(())
|
||||
} else {
|
||||
let msg = format!("Package installation failed for {package_name}, see above logs");
|
||||
warn!("{}", msg);
|
||||
Err(Error::Unexpected(msg))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn check_pkg_opnsense_org_connection(&mut self) -> Result<(), Error> {
|
||||
let pkg_url = "https://pkg.opnsense.org";
|
||||
info!("Verifying connection to {pkg_url}");
|
||||
let output = self
|
||||
.shell
|
||||
.exec(&format!("/bin/sh -c \"curl -v {pkg_url}\""))
|
||||
.await?;
|
||||
info!("{}", output);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn reload_config(&mut self) -> Result<(), Error> {
|
||||
info!("Reloading opnsense live config");
|
||||
self.opnsense = Self::get_opnsense_instance(self.repository.clone()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn restart_dns(&self) -> Result<(), Error> {
|
||||
self.shell.exec("configctl unbound restart").await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Save the config to the repository. This method is meant NOT to reload services, only save
|
||||
/// the config to the live file/database and perhaps take a backup when relevant.
|
||||
pub async fn save(&self) -> Result<(), Error> {
|
||||
self.repository.save_config(&self.opnsense.to_xml()).await
|
||||
}
|
||||
|
||||
/// Save the configuration and reload all services. Be careful with this one as it will cause
|
||||
/// downtime in many cases, such as a PPPoE renegociation
|
||||
pub async fn apply(&self) -> Result<(), Error> {
|
||||
self.repository
|
||||
.apply_new_config(&self.opnsense.to_xml())
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn from_credentials(
|
||||
ipaddr: std::net::IpAddr,
|
||||
port: Option<u16>,
|
||||
username: &str,
|
||||
password: &str,
|
||||
) -> Self {
|
||||
let config = Arc::new(client::Config {
|
||||
inactivity_timeout: None,
|
||||
..<_>::default()
|
||||
});
|
||||
|
||||
let credentials = SshCredentials::Password {
|
||||
username: String::from(username),
|
||||
password: String::from(password),
|
||||
};
|
||||
|
||||
let port = port.unwrap_or(22);
|
||||
|
||||
let shell = Arc::new(SshOPNSenseShell::new((ipaddr, port), credentials, config));
|
||||
let manager = Arc::new(SshConfigManager::new(shell.clone()));
|
||||
|
||||
Config::new(manager, shell).await.unwrap()
|
||||
}
|
||||
|
||||
async fn get_opnsense_instance(repository: Arc<dyn ConfigManager>) -> Result<OPNsense, Error> {
|
||||
let xml = repository.load_as_str().await?;
|
||||
trace!("xml {}", xml);
|
||||
|
||||
Ok(OPNsense::from(xml))
|
||||
}
|
||||
|
||||
pub async fn run_command(&self, command: &str) -> Result<String, Error> {
|
||||
self.shell.exec(command).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::config::{DummyOPNSenseShell, LocalFileConfigManager};
|
||||
use crate::modules::dhcp::DhcpConfig;
|
||||
use std::fs;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_load_config_from_local_file() {
|
||||
for path in vec![
|
||||
"src/tests/data/config-opnsense-25.1.xml",
|
||||
"src/tests/data/config-vm-test.xml",
|
||||
"src/tests/data/config-structure.xml",
|
||||
"src/tests/data/config-full-1.xml",
|
||||
] {
|
||||
let mut test_file_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
test_file_path.push(path);
|
||||
|
||||
let config_file_path = test_file_path.to_str().unwrap().to_string();
|
||||
println!("File path {config_file_path}");
|
||||
let repository = Arc::new(LocalFileConfigManager::new(config_file_path));
|
||||
let shell = Arc::new(DummyOPNSenseShell {});
|
||||
let config_file_str = repository.load_as_str().await.unwrap();
|
||||
let config = Config::new(repository, shell)
|
||||
.await
|
||||
.expect("Failed to load config");
|
||||
|
||||
println!("Config {:?}", config);
|
||||
|
||||
let serialized = config.opnsense.to_xml();
|
||||
|
||||
fs::write("/tmp/serialized.xml", &serialized).unwrap();
|
||||
|
||||
// Since the order of all fields is not always the same in opnsense config files
|
||||
// I think it is good enough to have exactly the same amount of the same lines
|
||||
let config_file_str_sorted = vec![config_file_str.lines().collect::<Vec<_>>()].sort();
|
||||
let serialized_sorted = vec![config_file_str.lines().collect::<Vec<_>>()].sort();
|
||||
assert_eq!(config_file_str_sorted, serialized_sorted);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_add_dhcpd_static_entry() {
|
||||
let mut test_file_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
test_file_path.push("src/tests/data/config-structure.xml");
|
||||
|
||||
let config_file_path = test_file_path.to_str().unwrap().to_string();
|
||||
println!("File path {config_file_path}");
|
||||
let repository = Arc::new(LocalFileConfigManager::new(config_file_path));
|
||||
let shell = Arc::new(DummyOPNSenseShell {});
|
||||
let mut config = Config::new(repository, shell.clone())
|
||||
.await
|
||||
.expect("Failed to load config");
|
||||
|
||||
println!("Config {:?}", config);
|
||||
|
||||
let mut dhcp_config = DhcpConfig::new(&mut config.opnsense, shell);
|
||||
dhcp_config
|
||||
.add_static_mapping(
|
||||
"00:00:00:00:00:00",
|
||||
Ipv4Addr::new(192, 168, 20, 100),
|
||||
"hostname",
|
||||
)
|
||||
.expect("Should add static mapping");
|
||||
|
||||
let serialized = config.opnsense.to_xml();
|
||||
|
||||
fs::write("/tmp/serialized.xml", &serialized).unwrap();
|
||||
|
||||
let mut test_file_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
test_file_path.push("src/tests/data/config-structure-with-dhcp-staticmap-entry.xml");
|
||||
|
||||
let config_file_path = test_file_path.to_str().unwrap().to_string();
|
||||
println!("File path {config_file_path}");
|
||||
let repository = Box::new(LocalFileConfigManager::new(config_file_path));
|
||||
let expected_config_file_str = repository.load_as_str().await.unwrap();
|
||||
assert_eq!(expected_config_file_str, serialized);
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if a given package name exists in a comma-separated list of packages.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `csv_string` - A string containing comma-separated package names.
|
||||
/// * `package_name` - The package name to search for.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `true` if the package name is found in the CSV string, `false` otherwise.
|
||||
fn is_package_in_csv(csv_string: &str, package_name: &str) -> bool {
|
||||
package_name.len() > 0 && csv_string.split(',').any(|pkg| pkg.trim() == package_name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_2 {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_is_package_in_csv() {
|
||||
let csv_string = "os-haproxy,os-iperf,os-cpu-microcode-intel";
|
||||
|
||||
assert!(is_package_in_csv(csv_string, "os-haproxy"));
|
||||
assert!(is_package_in_csv(csv_string, "os-iperf"));
|
||||
assert!(is_package_in_csv(csv_string, "os-cpu-microcode-intel"));
|
||||
|
||||
assert!(!is_package_in_csv(csv_string, "os-cpu"));
|
||||
assert!(!is_package_in_csv(csv_string, "non-existent-package"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_package_in_csv_empty() {
|
||||
let csv_string = "";
|
||||
|
||||
assert!(!is_package_in_csv(csv_string, "os-haproxy"));
|
||||
assert!(!is_package_in_csv(csv_string, ""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_package_in_csv_whitespace() {
|
||||
let csv_string = " os-haproxy , os-iperf , os-cpu-microcode-intel ";
|
||||
|
||||
assert!(is_package_in_csv(csv_string, "os-haproxy"));
|
||||
assert!(is_package_in_csv(csv_string, "os-iperf"));
|
||||
assert!(is_package_in_csv(csv_string, "os-cpu-microcode-intel"));
|
||||
|
||||
assert!(!is_package_in_csv(csv_string, " os-haproxy "));
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
use crate::config::manager::ConfigManager;
|
||||
use crate::error::Error;
|
||||
use async_trait::async_trait;
|
||||
use std::fs;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LocalFileConfigManager {
|
||||
file_path: String,
|
||||
}
|
||||
|
||||
impl LocalFileConfigManager {
|
||||
pub fn new(file_path: String) -> Self {
|
||||
Self { file_path }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ConfigManager for LocalFileConfigManager {
|
||||
async fn load_as_str(&self) -> Result<String, Error> {
|
||||
Ok(fs::read_to_string(&self.file_path)?)
|
||||
}
|
||||
|
||||
async fn save_config(&self, content: &str) -> Result<(), Error> {
|
||||
Ok(fs::write(&self.file_path, content)?)
|
||||
}
|
||||
|
||||
async fn apply_new_config(&self, content: &str) -> Result<(), Error> {
|
||||
self.save_config(content).await
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
mod local_file;
|
||||
mod ssh;
|
||||
use async_trait::async_trait;
|
||||
pub use local_file::*;
|
||||
pub use ssh::*;
|
||||
|
||||
use crate::Error;
|
||||
|
||||
#[async_trait]
|
||||
pub trait ConfigManager: std::fmt::Debug + Send + Sync {
|
||||
async fn load_as_str(&self) -> Result<String, Error>;
|
||||
async fn save_config(&self, content: &str) -> Result<(), Error>;
|
||||
async fn apply_new_config(&self, content: &str) -> Result<(), Error>;
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
use crate::config::{manager::ConfigManager, OPNsenseShell};
|
||||
use crate::error::Error;
|
||||
use async_trait::async_trait;
|
||||
use log::info;
|
||||
use russh_keys::key::KeyPair;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SshCredentials {
|
||||
SshKey { username: String, key: Arc<KeyPair> },
|
||||
Password { username: String, password: String },
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SshConfigManager {
|
||||
opnsense_shell: Arc<dyn OPNsenseShell>,
|
||||
}
|
||||
|
||||
impl SshConfigManager {
|
||||
pub fn new(opnsense_shell: Arc<dyn OPNsenseShell>) -> Self {
|
||||
Self { opnsense_shell }
|
||||
}
|
||||
}
|
||||
|
||||
impl SshConfigManager {
|
||||
async fn backup_config_remote(&self) -> Result<String, Error> {
|
||||
let ts = chrono::Utc::now();
|
||||
let backup_filename = format!("config-{}-harmony.xml", ts.format("%s%.3f"));
|
||||
|
||||
self.opnsense_shell
|
||||
.exec(&format!(
|
||||
"cp /conf/config.xml /conf/backup/{}",
|
||||
backup_filename
|
||||
))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn move_to_live_config(&self, new_config_path: &str) -> Result<String, Error> {
|
||||
info!("Overwriting OPNSense /conf/config.xml with {new_config_path}");
|
||||
self.opnsense_shell
|
||||
.exec(&format!("mv {new_config_path} /conf/config.xml"))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn reload_all_services(&self) -> Result<String, Error> {
|
||||
info!("Reloading all opnsense services");
|
||||
self.opnsense_shell
|
||||
.exec(&format!("configctl service reload all"))
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ConfigManager for SshConfigManager {
|
||||
async fn load_as_str(&self) -> Result<String, Error> {
|
||||
self.opnsense_shell.exec("cat /conf/config.xml").await
|
||||
}
|
||||
|
||||
async fn save_config(&self, content: &str) -> Result<(), Error> {
|
||||
let temp_filename = self
|
||||
.opnsense_shell
|
||||
.write_content_to_temp_file(content)
|
||||
.await?;
|
||||
self.backup_config_remote().await?;
|
||||
self.move_to_live_config(&temp_filename).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn apply_new_config(&self, content: &str) -> Result<(), Error> {
|
||||
self.save_config(content).await?;
|
||||
self.reload_all_services().await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user