This commit is contained in:
qing committed 2026-07-20 11:12:29 +08:00
commit 70d467d052
97 files changed
+10386

No files matched your search

+132
View File
@@ -0,0 +1,132 @@
#prj
users/
*.crt
*.key
*.pem
build/
build_*/
nidus
# ide
.vscode/
.arts/
# Prerequisites
*.d
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
# cangjie
build/
target/
output/
module-resolve.json
module-lock.json
cjpm.lock
.cjpm-history
*.macrocall
*.gcda
*.gcno
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
# 我加的
.env/
*.db
*.api_key
*.key
*.pem
pmcd
rzgs_2
crt
cert
# 其他
log/
report/
tmp/
*.cache
*.pyc
*.cython
#*.jpg
#*.png
*.pth
.eggs/
*.egg-info
.idea/
.vscode/
# nodejs
node_modules/
#python
__pycache__/
venv
# do not ignore the log folder by pmc-mgmt
!./mgmt/app/log/
# go
go.mod
go.sum
# VS
x64
.vs
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 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 General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<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 General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+88
View File
@@ -0,0 +1,88 @@
VERSION := 0.0.4
APP_NAME := nidus
INSTL_DIRS := /usr/local/bin
CONF_NAME := init.txt
CONF_DIR := /etc/Nidus
SRV_NAME := Nidus.service
SRV_DIR := /etc/systemd/system
CPP:= g++
INCS:= -I include/
MY_LIBS := -L/usr/lib -lus_th -lus_http
LIBS := -lpthread -lssl -lcrypto -lboost_program_options -lboost_json -lboost_thread -lboost_filesystem
CPPFLAGS := --std=c++20 -O3 -pipe #-Wall -Werror
BUILD_DIR = build
$(shell mkdir -p $(BUILD_DIR))
#--------
all: ${APP_NAME}.out
${APP_NAME}.out: $(BUILD_DIR)/main.o $(BUILD_DIR)/PPool.o $(BUILD_DIR)/ProcessTask.o $(BUILD_DIR)/HttpTask.o $(BUILD_DIR)/Tttask.o $(BUILD_DIR)/pmc_mtd.o $(BUILD_DIR)/subsys_call.o
$(CPP) $^ $(MY_LIBS) $(LIBS) -o $@
$(BUILD_DIR)/main.o: src/main.cpp
$(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
$(BUILD_DIR)/PPool.o: src/main/PPool.cpp
$(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
$(BUILD_DIR)/ProcessTask.o: src/main/ProcessTask.cpp
$(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
$(BUILD_DIR)/Tttask.o: src/main/Tttask.cpp
$(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
$(BUILD_DIR)/HttpTask.o: src/main/HttpTask.cpp
$(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
$(BUILD_DIR)/pmc_mtd.o: src/main/pmc_mtd.cpp
$(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
$(BUILD_DIR)/subsys_call.o: src/main/subsys_call.cpp
$(CPP) $(CPPFLAGS) -c $^ $(INCS) -o $@
install: $(APP_NAME).out
@echo "正在安装 $(APP_NAME) 到$(INSTL_DIRS)"
@
#@mkdir -p $(INSTL_DIRS)
@cp -f $(APP_NAME).out $(INSTL_DIRS)/$(APP_NAME)
#@chmod 755 $(INSTL_DIRS)/pmcd
@
@echo "正在配置 $(APP_NAME)"
@mkdir -p $(CONF_DIR)
@cp $(CONF_NAME) $(CONF_DIR)/$(CONF_NAME)
@cp $(SRV_NAME) $(SRV_DIR)/$(SRV_NAME)
@systemctl daemon-reload
@systemctl enable $(SRV_NAME)
@systemctl restart $(SRV_NAME)
@
@echo "安装完成!"
uninstall:
@echo "正在从 $(INSTL_DIRS) 卸载 $(APP_NAME)"
@
@rm -f $(INSTL_DIRS)/$(APP_NAME)
@rm -f $(CONF_DIRS)/$(CONF_NAME)
@rm -f -d ${CONF_DIRS}
@
@systemctl stop $(SRV_NAME)
@systemctl disable $(SRV_NAME)
@rm -f $(SRV_DIRS)/$(SRV_NAME)
@systemctl daemon-reload
@
@echo "卸载完成!"
clear:
@rm -rvf $(BUILD_DIR)
@rm -vf *.out
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=PMC Http Interfaces
After=network.target
[Service]
User=qing
Group=qing
ExecStart=nidus -i /etc/Nidus/init.txt --serve 5200
[Install]
WantedBy=multi-user.target
+56
View File
@@ -0,0 +1,56 @@
# 进程机器(PMC)
这是一个可以创建、管理子进程以及模块的程序。
## pmc是一个什么项目?
这是一个可扩展的模块,可以在文件夹下建立单独的模块,pmc核心模块可以托管运行这些模块。
## 为什么要做一个这样的项目?
2024年的时候,我想做一个树莓派机器人,准备用python来写控制程序,可是当时python的多线程能力较弱,所以想到使用子系统,就自己写了一个进程托管程序
## 项目的文件结构是怎样的?
users用户可以在目录下创建子模块,extra下面还有一些额外的模块。
请留意模块的README文件
## 如何托管外部模块
编辑启动列表程序,常为init.txt
## PMC的安装方式
``` bash
# 1.安装依赖
# 安装UniServe的libth包
git clone https://github.com/gopsc/UniServe_libth
cd UniServe_libth
sudo bash _set.sh
# 安装别的依赖
sudo apt update
sudo apt install git g++ make
sudo apt install libboost-all-dev
#sudo apt install libssl-dev
#sudo apt install libcurl4-openssl-dev
#sudo apt install libcurl4-gnutls-dev
# 2. 创建项目
git clone https://github.com/gopsc/UniServe_core
cd UniServe_core
make
sudo make install
```
## 加密通信机制(废弃)
PMC在启动时生成一个AES密钥,然后用一个RSA公钥将其加密发送给访问者。
然后访问者与客户端之间的交流全部用此AES密钥加密
## 如何使用并发机器运行程序
首先应该在模块中创建一个启动脚本,脚本中应该完成工作目录的切换、虚拟环境的激活,以及程序的启动。
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
cd "$(dirname "$0")" || exit
./nidus.out -i /etc/Nidus/init.txt --serve 5200
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
cd "$(dirname "$0")" || exit
make clear && make $@
make install
+177
View File
@@ -0,0 +1,177 @@
//作者:简单
//修改:qing
/*
* C++17支持了中文变量名,配合define预编译指令可以将代码中文化。
*
* 在C语言中,变量名只能由字母、数字或是下划线组成。
* 由于C++语言兼容C语言,最开始的C++是不能够使用多字节变量名的。
*
* */
#ifndef __中文模式
#define __中文模式
#include <stdint.h>
/*保留字*/
#define 使用 using
#define 命名空间 namespace
#define 取别名 typedef
#define 覆盖 override
#define 取内存大小 sizeof
#define 返回 return
#define 如果 if
#define 否则 else
#define 又或者 else if
#define 真 true
#define 假 false
//#define 且 and
//#define 或 or
#define 空类型 void
#define 常量 const
#define 有符号 signed
#define 无符号 unsigned
#define 文件 FILE
#define 文件结束 EOF
#define 类 class
#define 结构体 struct
#define 枚举类型 enum
#define 对象 this
#define 抛出异常 throw
#define 新建 new
//#define 新的 new
#define 删除 delete
#define 跳出 break
#define 继续 continue
#define 判断循环 while
#define 循环判断 do
#define 循环判断尾 while
#define 分支选择 switch
#define 支系 case
#define 缺省 default
#define 计次循环 for
#define 尝试 try
#define 获取异常 catch
#define 捕获异常 catch
#define 退出 exit
#define 公开的 public
#define 受保护的 protected
#define 私有的 private
#define 外部的 extern
#define 静态的 static
#define 虚拟的 virtual
#define 有号8位整 int8_t
#define 无号8位整 uint8_t
#define 有号16位整 int16_t
#define 无号16位整 uint16_t
#define 有号32位整 int32_t
#define 无号32位整 uint32_t
#define 有号64位整 int64_t
#define 无号64位整 uint64_t
#define 空的 NULL
#define 空指针 nullptr
#define 整数 int
#define 字符 char
#define 短整数 short
#define 长型 long
#define 超长型 long long
#define 单精度小数 float
#define 双精度小数 double
#define 长度单位 size_t
#define 布尔 bool
#define 逻辑型 bool
#define 可变类型 auto
#define 自动的 auto
#define 适应 auto
#define _文件 FILE
#define _文件结束 EOF
#define _读模式 "r"
#define _写模式 "w"
#define 模板 template
#define 类型名 typename
#define 默认的 default
#define 被删除 delete
#define 入口 main
#define 主函数 main
#define 或 ||
#define 或者 ||
#define 而且 &&
#define 且 &&
#define 等于 ==
#define 大于等于 >=
#define 小于等于 <=
#define 大于 >
#define 小于 <
#define 不报错的 noexcept
#define 不转换的 explicit
#define 纯函数的 consteval
#define 预求值的 constexpr
#define _加法重载 operator+
#define _取下标重载 operator[]
#define _开始 begin
#define _结束 end
//-----------------------------------------------------------
//-----------------------------------------------------------
//基本单元
#ifdef __cplusplus
#include <iostream>
命名空间 中文标准{
类 字符串 {
公开的:
/* 初始化为空字符串 */
字符串() {
对象->s = "";
}
/* 以字面量初始化 */
字符串(常量 字符* 源) {
对象->s = 源;
}
/* 访问器 */
常量 字符* 取值() {
返回 s.c_str();
}
/* */
字符串& _加法重载(常量 字符* 乙方) {
对象->s += 乙方;
返回 *对象;
}
/* 字符串之间的连接 */
字符串& _加法重载(字符串& 乙) {
对象->s += 乙.取值();
返回 *对象;
}
私有的:
std::string s;
};
类 标准输出{
公开的:
空类型 调试输出(常量 字符* 消息) {
std::cout << 消息;
}
空类型 调试输出(字符串& 信) {
std::cout<< 信.取值();
}
};
类 标准输入{
公开的:
字符串 取字符串(){
std::string s;
std::cin >> s;
返回 字符串(s.c_str());
}
整数 取整数() {
整数 数;
std::cin >> 数;
返回 数;
}
};
}
#endif //__cplusplus
#endif //__中文模式
+129
View File
@@ -0,0 +1,129 @@
#pragma once
#include "中文化.hpp"
#include "异常.hpp"
命名空间 中文标准 {
模板 <类型名 类型1>
类 向量{
公开的:
/* 注意:当长度单位为0时,内部指针是空的 */
向量() {
对象->指针 = 空指针;
对象->容量 = 0;
}
/* 专门用于处理花括号初始化列表 */
向量(常量 std::initializer_list<类型1>& init = {}) {
对象->指针 = 新建 类型1[init.size()] {空的};
对象->容量 = init.size();
长度单位 计数 = 0;
计次循环(适应 & 东西: init) {
对象->指针[计数++] = 东西;
}
}
~向量() {
删除 对象->指针;
对象->指针 = 空指针;
对象->容量 = 0;
}
/*----------访问器----------*/
长度单位 取容量() {
返回 对象->容量;
}
布尔 是否为空() {
返回 对象->容量 等于 0;
}
/*--------运算符重载--------*/
向量& _取下标重载( 常量 长度单位 下标 ) {
如果(下标 < 0 或 下标 >= 对象->容量)
抛出异常 下标越界{"向量", 对象->容量, 下标};
返回 对象->指针[下标];
}
/*--------可范围遍历--------*/
类型1* _开始() {
返回 对象->指针;
}
类型1* _结束() {
返回 对象->指针 + 对象->容量;
}
/*----------变异器----------*/
空类型 插入元素(常量 长度单位 位置, 常量 向量& 媒介) {
/* 越界检查 */
如果(位置 < 0 或 位置 > 对象->容量)
抛出异常 下标越界{"向量元素插入", 对象->容量+1, 位置};
适应 长度 = 取容量();
适应 新的 = 新建 类型1[长度 + 1] { 空的 };
/* 插入位置之前 */
计次循环(适应 计数 = 0; 计数 < 位置; ++计数)
新的[计数] = 对象->指针[计数];
/* 执行插入 */
新的[位置] = 媒介;
/* 插入位置之后 */
计次循环(适应 计数 = 位置 + 1; 计数 <= 长度; ++计数)
新的[计数] = 对象->指针[计数 - 1];
如果(对象->指针) 删除[] 对象->指针; /* 可能为空 */
对象->指针 = 新的;
}
空类型 追加元素(常量 向量& 媒介) {
适应 长度 = 取容量();
适应 新的 = 新建 类型1[长度 +1] {空的};
计次循环(适应 计数 = 0; 计数 < 长度; ++计数)
新的[计数] = 对象->指针[计数];
新的[长度] = 媒介;
如果(对象->指针) 删除[] 指针; /* 可能为空 */
对象->指针 = 新的;
}
空类型 删除元素(常量 长度单位 位置) {
/* 越界检查 */
如果(位置 < 0 或 位置 >= 对象->容量)
抛出异常 下标越界{"向量元素插入", 对象->容量 + 1, 位置};
适应 长度 = 取容量();
适应 新的 = (长度 等于 1)
? 空指针 : 新建 类型1[长度 - 1] { 空的 };
/* 目标位置之前 */
计次循环(适应 计数 = 0; 计数 < 位置; ++计数)
新的[计数] = 对象->指针[计数];
/* 目标位置之后 */
计次循环(适应 计数 = 位置; 计数 < 长度; ++计数)
新的[计数] = 对象->指针[计数 + 1];
删除[] 对象->指针;
对象->指针 = 新的;
}
/*----------------*/
//类 迭代器{
//公开的:
// 迭代器(常量 std::vector<类型1>::iterator& it) {
// this->it = it;
// }
//私有的:
// std::vector<类型1>::iterator it;
//};
/*----------------*/
私有的:
类型1 *指针;
长度单位 容量;
};
}
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include "中文化.hpp"
命名空间 中文标准 {
类 标准异常 : 公开的 std::exception {
公开的:
不转换的 标准异常(常量 字符* 信息): 信息(信息) {}
常量 字符* what() 常量 不报错的 覆盖 {
返回 信息;
}
私有的:
常量 字符* 信息;
};
类 下标越界 : 公开的 标准异常{
公开的:
下标越界(常量 字符 * 提示, 常量 长度单位 标准值, 常量 长度单位 目前值)
: 标准异常(提示), 标准值(标准值), 目前值(目前值) {
};
长度单位 取标准值() { 返回 标准值; }
长度单位 取目前值() { 返回 目前值; }
私有的:
长度单位 标准值, 目前值;
};
}
+97
View File
@@ -0,0 +1,97 @@
#pragma once
#include "中文化.hpp"
#include "异常.hpp"
#include "顺序表.hpp"
命名空间 中文标准 {
模板 <类型名 类型1, 长度单位 节点大小 = 64>
类 链串 {
公开的:
/* 初始化为空链串 */
链串() {
对象->长度 = 0;
对象->下一个 = 空指针;
对象->上一个 = 空指针;
对象->头 = 对象; /* 每一个子节点都记录同一个头结点 */
对象->尾 = 对象; /* 为了方便,只有头结点记录尾节点 */
}
链串 (常量 std::initializer_list<类型1>& init = {})
{
计次循环(适应 & 东西: init) {
插入(东西);
}
}
/*
* 链式析构
*
* 析构时,会递归析构所有节点。
*/
~链串() {
删除[] 对象->下一个;
}
空类型 插入(常量 类型1& 元素) {
链串 *暂时 = 对象->尾;
如果(暂时->长度 等于 节点大小)
_推();
暂时->存储[暂时->长度++] = 元素;
}
长度单位 统计() {
长度单位 总数 = 0;
链串 *暂时 = 对象->头;
判断循环(暂时 != 空指针) {
总数 += 暂时->长度;
暂时 = 暂时->下一个;
}
返回 总数;
}
/*
* 链串重组
*
* 将链串重组为顺序表W
*/
顺序表<类型1> 重组() {
顺序表<类型1> 结果(统计());
链串 *暂时 = 对象->头;
长度单位 计数 = 0;
判断循环(暂时 != 空指针) {
计次循环(适应 索引 = 0; 索引 < 暂时->长度; ++索引) {
结果[计数++] = 暂时->存储[索引];
}
暂时 = 暂时->下一个;
}
返回 结果;
}
类 链串异常: 公开的 标准异常{
公开的:
链串异常(常量 字符* 消息) : 标准异常(消息) {}
};
私有的:
类型1 存储[节点大小];
长度单位 长度; /* 存储中的元素数量 */
链串 *下一个;
链串 *上一个;
链串 *头;
链串 *尾;
空类型 _推() {
链串*新的;
尝试{ 新的 = 新建 链串(); }
捕获异常 (std::exception& exp){
抛出异常 链串异常{"链串推失败"};
}
_拼接节点(新的);
}
空类型 _拼接节点(链串* 新的) {
对象->尾->下一个 = 新的;
新的->上一个 = 对象->尾;
对象->尾 = 新的;
新的->头 = 对象;
}
};
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include "中文化.hpp"
#include "异常.hpp"
命名空间 中文标准 {
模板<类型名 类型1>
类 顺序表 {
公开的:
顺序表(长度单位 大小) {
存储 = 新建 类型1[大小];
长度 = 大小;
}
~顺序表() {
删除[] 存储;
}
类型1 _取下标重载(长度单位 下标) {
如果(下标 >= 长度)
抛出异常 顺序表异常{"下标超出范围"};
返回 存储[下标];
}
类 顺序表异常: 公开的 标准异常{
公开的:
顺序表异常(常量 字符* 消息) : 标准异常(消息) {}
};
私有的:
类型1 *存储;
长度单位 长度;
};
}
+107
View File
@@ -0,0 +1,107 @@
/* 日志 */
#pragma once
#include <iostream>
#include <string>
#include <mutex>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <ctime>
enum class LogLevel {
DEBUG,
INFO,
WARNING,
ERROR,
CRITICAL
};
namespace qing {
/*
* 这是由Deepseek创作的,用于记录日志的类模块
* 简化版本,只输出到控制台
*
* 优化意见:改为存储日志文件
*/
class Logger {
public:
//获取日志实例(单例模式)
static Logger& getInstance() {
static Logger instance;
return instance;
}
//初始化日志系统
void init(LogLevel minLogLevel = LogLevel::INFO,
bool consoleOutput = true) {
std::lock_guard<std::mutex> lock(mutex_);
if (initialized_) {
return;
}
minLogLevel_ = minLogLevel;
consoleOutput_ = consoleOutput;
initialized_ = true;
}
// 设置最低日志级别
void setMinLogLevel(LogLevel level) {
std::lock_guard<std::mutex> lock(mutex_);
minLogLevel_ = level;
}
// 日志输出方法
void log(LogLevel level, const std::string& message) {
if (level < minLogLevel_ || !consoleOutput_) {
return;
}
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch()) % 1000;
std::tm tm;
localtime_r(&in_time_t, &tm);
std::stringstream ss;
ss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S")
<< "." << std::setfill('0') << std::setw(3) << ms.count()
<< " [" << logLevelToString(level) << "] "
<< message;
std::lock_guard<std::mutex> lock(mutex_);
std::cout << ss.str() << std::endl;
}
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
private:
Logger() = default;
~Logger() = default;
std::string logLevelToString(LogLevel level) {
switch (level) {
case LogLevel::DEBUG: return "DEBUG";
case LogLevel::INFO: return "INFO";
case LogLevel::WARNING: return "WARNING";
case LogLevel::ERROR: return "ERROR";
case LogLevel::CRITICAL: return "CRITICAL";
default: return "UNKNOWN";
}
}
std::mutex mutex_;
LogLevel minLogLevel_ = LogLevel::INFO;
bool consoleOutput_ = true;
bool initialized_ = false;
};
}
#define LOG_DEBUG(message) qing::Logger::getInstance().log(LogLevel::DEBUG, message)
#define LOG_INFO(message) qing::Logger::getInstance().log(LogLevel::INFO, message)
#define LOG_WARNING(message) qing::Logger::getInstance().log(LogLevel::WARNING, message)
#define LOG_ERROR(message) qing::Logger::getInstance().log(LogLevel::ERROR, message)
#define LOG_CRITICAL(message) qing::Logger::getInstance().log(LogLevel::CRITICAL, message)
+110
View File
@@ -0,0 +1,110 @@
#pragma once
#include <us/Thread.hpp>
#include <us/ITask.hpp>
#include <us/HttpServer.hpp>
namespace qing {
namespace http = boost::beast::http;
/* ----------------
* HttpTask类 - 超文本服务器任务 */
class HttpTask: public ITask {
public:
/* 接受一个回调函数,其接受pmc::net::HttpServer对象的引用,在回调函数中对服务器进行配置 */
HttpTask(int port, std::function<void(pmc::net::HttpServer& server)> handler);
/* 在一个线程中判断线程是否正在有效运行 */
bool isRunning() override;
/* 启动该项任务 */
void start() override;
/* 停止该项任务 */
void stop() override;
private:
int port;
std::function<void(pmc::net::HttpServer& server)> handler;
std::unique_ptr<Thread> th; /* ---- 可控线程指针 */
std::unique_ptr<pmc::net::HttpServer> server; /* ---- HTTP服务器的指针 ---- */
/* 初始化线程,定义线程的行为(Http服务器) */
void init_thread();
};
/*-----------------------------------------------------------------------------*/
/* ================
* 进程托管http服务器
* ================
* 对操作进程列表的http服务器进行配置,即是输入回调函数 */
namespace process_http_server {
/* ---- 注册POST路由 ---- */
void registerRoutes(pmc::net::HttpServer& server);
/**
* @brief 解析请求体中的JSON数据
* @param body 请求体字符串
* @return JSON解析后的属性树
*/
boost::property_tree::ptree parseJsonBody(const std::string& body);
/**
* @brief 构建JSON响应
* @param success 是否成功
* @param message 消息
* @param data 附加数据
* @return JSON字符串
*/
std::string buildJsonResponse(bool success, const std::string& message,
const boost::property_tree::ptree& data = boost::property_tree::ptree());
/**
* @brief 从请求中提取target参数
* @param params 查询参数
* @return target值(空字符串表示本机)
*/
std::string getTarget(const std::unordered_map<std::string, std::string>& params);
/**
* @brief 从请求中提取exec参数
* @param params 查询参数
* @return 要执行的指令
*/
std::string getExecCommand(const std::unordered_map<std::string, std::string>& params);
/**
* @brief 从请求中提取kill参数
* @param params 查询参数
* @return 目标进程号
*/
int getPid(const std::unordered_map<std::string, std::string>& params);
/* POST方法处理器 */
http::response<http::string_body> handleList(
const http::request<http::string_body>& req,
const std::unordered_map<std::string, std::string>& params);
http::response<http::string_body> handleExec(
const http::request<http::string_body>& req,
const std::unordered_map<std::string, std::string>& params);
http::response<http::string_body> handleKill(
const http::request<http::string_body>& req,
const std::unordered_map<std::string, std::string>& params);
/** 内部实现函数 */
std::string listProcesses(const std::string& target);
std::string execCommand(const std::string& command, const std::string& target);
bool killProcess(int pid, const std::string& target);
}
}
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#include <iostream>
#include <memory>
#include <list>
#include "main/ProcessTask.hh"
namespace qing {
/* -----------------
* subprocess pool 子进程池
* ----------------
* FIXME: 将列表(序列化)功能放到这里来 */
class PPool {
public:
/* CREATE PROCESS - 创建进程
*
* cmd: 启动命令 */
void crtp(const std::string& cmd);
/* CLEAR 清理 - 删除所有已经停下的进程 */
void clr();
/* 获取进程池的大小 */
size_t size() { return pool.size(); }
/* 删除一个进程,需要输入进程的下标。
*
* FIXME: 输入进程下标似乎不太自然 */
void kill(int idx);
/* 取下标运算符重载 - 取元素对象 */
ProcessTask& operator[](const size_t idx);
/* TODO: 实现迭代器和begin()、end()
* ...... */
private:
/* 进程任务的shared指针的容器 */
std::list<std::shared_ptr<ProcessTask>> pool{};
};
}
+70
View File
@@ -0,0 +1,70 @@
#pragma once
#include <boost/process.hpp>
#include <us/ITask.hpp>
namespace qing {
/* ----------------
* 【子进程任务】
* ----------------
* 输入要执行的命令,构造子进程任务
* TODO: 我们可以重定向子进程的输入和输出,实时交互 */
class ProcessTask: public ITask {
public:
/* 输入一个字符串(要执行的命令)(但是并没有执行起来) */
ProcessTask(std::string cmd): cmd(cmd) {}
/* 任务是否在运行中 */
bool isRunning() override { return p && p->running(); }
/* 启动任务 */
void start() override {
if (!isRunning())
this->p = std::make_unique<boost::process::child>(cmd); }
/* 终止该任务(并且重置子进程指针) */
void stop() override {
if (isRunning()) p->terminate();
p.reset();
}
/* 获取该任务(子进程)的命令 */
std::string check() { return this->cmd; }
/* 获取该子进程的pid(进程编号) */
pid_t pid() { return p->id(); }
private:
std::unique_ptr<boost::process::child> p; /* 子进程指针 */
std::string cmd; /* 该进程执行的命令 */
};
}
#ifdef __NEW_VER
/* ---- [子进程任务]boost.process库升级到了v2 ---- */
class ProcessTask: public ITask {
public:
ProcessTask(std::string cmd): cmd(cmd) {}
bool isRunning() override;
int getExitCode();
void start() override;
/* ---- NOTE(202606025-qing): 杀死进程失败只是打印错误信息 ---- */
void stop() override;
std::string check() {
return this->cmd;
}
pid_t pid() {
return p->id();
}
private:
boost::asio::io_context ctx; /* 异步上下文 */
std::unique_ptr<boost::process::v2::process> p; /* 子进程指针 */
boost::system::error_code exit_code; /* 进程退出的代码 */
std::string cmd; /* 要执行的命令 */
};
}
#endif
+58
View File
@@ -0,0 +1,58 @@
#pragma onces
#include "tt/Mq.h"
namespace qing {
/*
* TRANSMIT TASK 通信任务
* (创建一个通信伺服器,它收到消息就执行回调)
* (长时间伺服运行会不会有问题)
*/
class Tttask: public ITask {
public:
/* 构造【通信任务】
* msglen: 单条消息的长度
* msgcnt: 消息伺服长度
* callback: 回调函数 */
Tttask(const size_t msglen, size_t msgcnt, const sf_t callback);
/* 启动该通信伺服任务 */
void start() override;
/* 终止这个通信伺服任务
*
* TODO: 研究一下要不要释放一些资源
* TODO: 增加超时 */
void stop() override {
if (this->isRunning())
th->WaitClose();
}
/* 该任务是否在运行
*
* FIXME: 对START状态的处理还应该考虑
* FIXME: 如果在STOP状态而没有stop()任务,可能会造成线程未关闭,一直占用资源? */
bool isRunning() override;
private:
std::unique_ptr<Thread> th; /* 可控线程指针 */
std::unique_ptr<sf_t> callback; /* 回调行为(接收之后)指针 */
std::unique_ptr<Mq> mq; /* 消息队列指针 */
size_t msglen=0, msgcnt=0; /* 消息的缓存规格 */
std::string name; /* 消息队列名(进程号) */
/* 初始化通信伺服线程,
* 初始化方法就是通过传入一些函数,
* 构建线程 */
void init_thread();
};
}
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include <iostream>
namespace qing {
/* ----------------
* 进程托管服务方法集
* ----------------
* 直接对进程组列表进行操作
*
*/
namespace pmc_mtd
{
auto list() -> std::string; /* 列出所有的进程 */
auto kill(const int pid) -> bool; /* 杀死一个进程,需提供PID */
auto exec(const std::string& cmd) -> bool; /* 执行一个进程,输入要执行的命令行 */
auto parse_self_init_list(std::string &path) -> void; /* 解析自启动脚本 */
}
}
+19
View File
@@ -0,0 +1,19 @@
#pragma once
namespace qing {
/* ----------------
* 子系统调用
* ----------------
* 通过进程间通信与子系统进行通讯,调用不同的功能
*
*/
namespace subsys_call
{
std::string send_list_and_recv_pipe(const std::string& name_mq);
std::string send_start_and_recv_pipe(const std::string& name_mq, const std::string& exec);
std::string send_kill_and_recv_pipe(const std::string& name_mq, const int kill);
}
}
+93
View File
@@ -0,0 +1,93 @@
/*
* 目前是Message Queue 的发送端(不涉及创建消息队列)
*
* FIXME: 集成发送、接收和创建
*/
#pragma once
#include <iostream>
#include <cstring>
#include <memory>
#include <boost/interprocess/ipc/message_queue.hpp>
namespace qing {
namespace bip = boost::interprocess;
using sf_t = std::function<void(const char*)>; /* 通信成功的回调函数 success */
using ef_t = std::function<void(void)>; /* 通信失败的回调函数 error */
class Mq {
public:
enum {CREATOR=0, USER=1};
Mq(const std::string& name, int msglen, size_t msgcnt, int mode = USER) {
this->name = std::string("/") + name;
this->msglen = msglen;
this->msgcnt = msgcnt;
this->mode = mode;
switch (mode) {
case USER:
mqp = std::make_unique<bip::message_queue>(bip::open_only, this->name.c_str());
break;
case CREATOR: /* 由创建者创建消息队列 */
bip::message_queue::remove(this->name.c_str());
mqp = std::make_unique<bip::message_queue>(
bip::create_only, this->name.c_str(),
msgcnt, msglen * sizeof(char)
);
break;
}
}
/* 创建者负责清理 */
~Mq() {
if (mode == CREATOR)
bip::message_queue::remove(name.c_str());
}
/* */
Mq(const Mq&) = delete;
Mq& operator=(const Mq&) = delete;
/* 发送消息 */
void send(std::string &msg)
{
if (msg.size() + 1 > msglen) /* over the len */
throw std::length_error("Message queue Send Length over");
mqp->send(msg.c_str(), msg.size() + 1, 0); /* include \0 */
}
/* 尝试接收消息 */
void recv(sf_t success, ef_t notyet) {
auto data = std::make_unique<char[]>(msglen); /* 接收缓冲区 */
unsigned int priority; /* 优先级 */
bip::message_queue::size_type recvd_size;
try { /* try_receive()返回bool类型 */
auto r = mqp->try_receive(
data.get(), msglen*sizeof(char),
recvd_size, priority
);
if (r) /* 成功接收到数据 */
success(data.get());
else /* 没有收到数据 */
notyet();
}
catch (std::exception &exp) {
std::cerr << "exception type: " << typeid(exp).name() << std::endl;
std::cerr << "exception message: " << exp.what() << std::endl;
}
}
private:
/* */
std::unique_ptr<bip::message_queue> mqp;
std::string name;
size_t msglen=0, msgcnt=0;
int mode;
};
}
+157
View File
@@ -0,0 +1,157 @@
#pragma once
#include <string>
#include <iostream>
#include <unistd.h>
#include <fcntl.h> /* open() */
#include <sys/stat.h> /* mkfifo() */
#include <sys/select.h>
namespace qing {
/* 20260309(qing): 该类不会抛出异常 */
class Pipe{
public:
static const int CREATOR = 1;
static const int USER =2;
static const ssize_t PIPE_MAX_LEN = 2048;
Pipe(const std::string& path, int mode)
: fd(-1), isCreator(mode == CREATOR) {
std::string real_path = "/tmp/pst-";
real_path += path;
fifo_path = real_path;
if (isCreator && mkfifo(fifo_path.c_str(), 0666) == -1 && errno != EEXIST) /* wr_wr_wr */
perror("mkfifo"); /* 文件已存在是正常情况,其他错误才需要处理 */
}
~Pipe() {
/* 如果打开了文件,则关闭文件 */
if (fd != -1) close(fd);
/**********************/
/* 如果管道由该对象创建,就要负责清理 */
if (isCreator) unlink(fifo_path.c_str()); /* 创建者负责清理 */
}
Pipe(const Pipe&) = delete;
Pipe& operator=(const Pipe&) = delete;
/* 这里才是打开文件的指令 - 以读模式打开,可以非阻塞 */
bool openForRead(bool nonblock = false) {
/* 设置是否以非阻塞方式打开文件 */
int flags = O_RDONLY;
if (nonblock) {
flags |= O_NONBLOCK;
}
fd = open(fifo_path.c_str(), flags);
if (fd == -1) {
perror("open for read");
return false;
}
else {
FD_ZERO(&read_fds);
FD_SET(fd, &read_fds);
if (fd > max_fd) max_fd = fd;
return true;
}
}
/* 以写模式打开文件 */
bool openForWrite(/*bool nonblock = falsei*/) {
/* 写入管道是不需要阻塞/非阻塞的? */
int flags = O_WRONLY;
//if (nonblock) {
// flags |= O_NONBLOCK;
//}
fd = open(fifo_path.c_str(), flags);
if (fd == -1) {
perror("open for write");
return false;
}
else {
FD_ZERO(&write_fds);
FD_SET(fd, &write_fds);
if (fd > max_fd) max_fd = fd;
return true;
}
}
/* 写入管道,如果失败返回-1。成功返回写入的字符数。 */
ssize_t writePipe(const std::string &data) {
if (fd == -1) {
std::cerr << "Pipe not opened for writing" << std::endl;
return -1;
}
else {
return write(fd, data.c_str(), data.size());
}
}
/* 将探测与读取解耦,使用者可以自行决定要不要阻塞 */
bool waitForRead(int timeout_sec = 0, int timeout_usec = 0) {
/* 如果文件没打开,等待是失败的 */
if (fd == -1) return false;
fd_set temp_fds = read_fds;
struct timeval timeout = {timeout_sec, timeout_usec};
int ret = select(max_fd + 1, &temp_fds, nullptr, nullptr, &timeout);
if (ret == -1) {
perror("select");
return false;
}
else {
return ret > 0 && FD_ISSET(fd, &temp_fds);
}
}
/* 读取数据到字符串,返回实际读取的字节数 */
ssize_t readPipe(std::string *output) {
if (fd == -1) {
std::cerr << "Pipe not opened for reading" << std::endl;
return -1;
}
else
{
char buffer[PIPE_MAX_LEN];
ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
if (n >0) {
buffer[n] = '\0';
*output = buffer;
}
else if (n == 0) {
/* 管道写入端关闭 */
*output = "";
}
else {
perror("read");
}
return n;
}
}
private:
std::string fifo_path;
int fd;
bool isCreator;
fd_set read_fds;
fd_set write_fds;
fd_set except_fds;
int max_fd;
};
}
+2
View File
@@ -0,0 +1,2 @@
bash /home/qing/micro_servers/gateway/_run.sh
bash /home/qing/micro_servers/static/_run.sh
+306
View File
@@ -0,0 +1,306 @@
/* ===============================================
* 通用子系统、进程机器、进程托管服务
*
*
* 【主函数文件】
*
* 直接子系统调用,或者启动一个pmc子系统(可以打开http)。
* ===============================================
*/
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <thread>
#include <memory>
#include <vector>
#include <list>
#include <cstddef>
#include <csignal>
#include <cctype>
#include <iomanip>
#include <unistd.h>
#include <sys/types.h>
#include <boost/json.hpp>
#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include "logs/Logger.hpp"
#include <us/Thread.hpp>
#include <us/Cv_wait.hpp>
#include <us/ITask.hpp>
#include "tt/Pipe.h"
#include "main/Tttask.hh"
#include "main/HttpTask.hh"
#include "main/pmc_mtd.hh"
#include "main/subsys_call.hh"
/* 中文模式 Chinese Mode */
#include "cn/中文化.hpp"
/* 静态区 - 存放全局变量 */
static const char *PMC_VERSION = "0.0.10"; /* 版本号 */
static const size_t MSGLEN = 2048; /* 单条消息的长度 */
static const size_t MSGCNT = 100; /* 消息条数 */
/* ---- 命名空间 ---- */
using namespace qing;
/* ---- 给命令行参数的命名空间取别名 ---- */
namespace po = boost::program_options;
void pmc_init(po::variables_map&); /* 初始化pmc并行机器 */
void pmc_serve(po::variables_map&); /* pmc的http伺服器模式 */
void parse_data_from_mq(std::string&); /* 解析消息队列收到的消息 */
//-------------------------------------------------------------
//-------------------------------------------------------------
/*-------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------*/
Cv_wait cv = Cv_wait(); /* 条件变量的等待机制(让主程序等待中断信号) */
auto taskPool = std::vector<std::shared_ptr<ITask>>{}; /* 基层任务池 - !!! 非子进程 !!! */
/*-------------------------------------------------------------------------*/
/* 捕获中断信号,结束线程并且退出 */
void signalHandler(int signum)
{
LOG_INFO("收到终止信号,准备停止服务器...");
cv.WakeCv(); /* 唤醒条件信号即关闭程序 */
//if (server) server->stop(); /* TODO: 封装成ITask */
}
/*---------------- SIGNAL ACTION ----------------*/
//
/* 对信号的响应行为 TODO: 我应该系统地学习一下这个库 */
void set_signal_action() {
/* 该结构体用于描述信号的处理方式 */
struct sigaction sa;
/* 绑定处理函数 */
sa.sa_handler = signalHandler;
/*
* 清空并初始化一个信号掩码集 --------------> 用于指定哪些信号在当前或即将执行的信号处理函数期间应该被阻塞(位掩码)
* “在执行这个信号处理函数时,除了当前正在处理的信号外,还希望临时阻塞其他某些信号”
* 不阻塞其他信号
* 确保在执行期间没有其他特定的信号会被阻塞
* 防止处理过程中被其他信号中断
*/
sigemptyset(&sa.sa_mask);
/*
* 用于设置信号处理函数的行为特性。
* 0 - 默认选项
* SA_NODEFER - 表示在执行信号处理函数时不允许其他信号被阻塞
* SA_RESETHAND - 在信号处理函数返回后,将信号的处理方式重置为默认
* SA_NOCLDSTOP - 对于子进程发送的停止信号,父进程不会停止。
* SA_NOCLDWAIT - 父进程在等待等待子进程终止时不会因为子进程发送信号而收到通知
* SA_SIGINFO - 使用扩展的信号信息,信号处理函数接收三个参数而不是一个
*/
sa.sa_flags = 0;
/* 注册信号 */
sigaction(SIGINT, &sa, nullptr); /* Ctrl + C */
sigaction(SIGTERM, &sa, nullptr); /* kill 或 systemctl stop */
}
/*-------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------*/
/* 入口函数 */
int main(int argc, char** argv) {
/*------------------------------*/
/* 设置信号行为*/
set_signal_action();
/*------------------------------*/
/* 解析命令行参数 */
po::options_description desc("pmc subsystem start options");
desc.add_options() /* 定义选项 */
("help,h", "display help message") /* 帮助菜单 */
("version,v", "display version message") /* 显示版本 */
/******** 子系统调用模式 *********/
("send,s", po::value<std::string>(), "send a message to pmc sys") /* 输入目标pid */
("exec", po::value<std::string>(), "message body") /* 启动一个进程 */
("list", "list process all run") /* 列出运行中的进程 */
("kill", po::value<int>(), "kill a process") /* 杀死一个进程 */
/********* 子系统服务模式 ********/
("init,i", po::value<std::string>(), "self-init list") /* 输入自启动列表 */
("serve", po::value<int>(), "Run as http server"); /* 启用http伺服器 */
/* 参数变量映射关系 */
po::variables_map vm;
try { /* 开始解析 */
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) { /* 获取帮助页面 */
std::cout << desc << std::endl;
std::cout << "--------- API MAP ---------" << std::endl;
std::cout << "Available endpoints:" << std::endl;
std::cout << " POST /list?target=optional" << std::endl;
std::cout << " POST /exec?command=ls&target=optional" << std::endl;
std::cout << " POST /kill?pid=1234&target=optional" << std::endl;
return 0;
}
if (vm.count("version")) { /* 获取版本信息 */
std::cout << PMC_VERSION << std::endl;
return 0;
}
}
catch (const std::exception& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
std::cerr << "using --help to check options message" << std::endl;
throw e;
}
/*----------------------------------------*/
if ( vm.count("send") && vm.count("exec")) {
auto send = vm["send"].as<std::string>();
auto exec = vm["exec"].as<std::string> ();
auto msg = subsys_call::send_start_and_recv_pipe(send, exec);
std::cout << msg << std::endl;
return 0;
}
else if ( vm.count("send") && vm.count("list")){
auto send = vm["send"].as<std::string> ();
auto msg = subsys_call::send_list_and_recv_pipe(send);
std::cout << msg << std::endl;
return 0;
}
else if (vm.count("send") && vm.count("kill")) {
auto send = vm["send"].as<std::string> ();
auto kill = vm["kill"].as<int>();
auto msg = subsys_call::send_kill_and_recv_pipe(send, kill);
std::cout << msg << std::endl;
return 0;
}
/* 初始化日志模块 */
Logger::getInstance().init(LogLevel::DEBUG, true);
/* 列表自启动 */
if (vm.count("init")){
std::string path = vm["init"].as<std::string>();
pmc_mtd::parse_self_init_list(path);
}
/**********************************************/
/* TODO: 抽象出来 */
if (vm.count("serve"))
pmc_serve(vm);
/* pmc初始化函数 */
pmc_init(vm);
/*
* 主线程等待
*
* 触发器在信号处理那里
*/
cv.Wait();
/* 主线程被唤醒,停止所有任务 */
for (auto& task: taskPool) {
task->stop();
}
}
/*-----------------------------------------------------------------------------*/
/* 初始化子系统 即是启动通信 */
void pmc_init(po::variables_map& vm) {
/*-------------------*/
auto ttt = std::make_shared<Tttask> (MSGLEN, MSGCNT,
[](const char *data) { /* 处理收到的数据 */
auto json_str = std::string(data);
parse_data_from_mq(json_str);
});
ttt->start();
taskPool.push_back(ttt);
}
/* http伺服器模式(只监听本地)TODO: 集成为ITask */
void pmc_serve(po::variables_map& vm)
{
int port = vm["serve"].as<int>();
auto server = std::make_shared<HttpTask> (port, [](pmc::net::HttpServer& server_) {
process_http_server::registerRoutes(server_);
});
server->start();
taskPool.push_back(server);
}
/* 解析从消息队列中接收到的数据,运行在服务端 */
void parse_data_from_mq(std::string& json_str)
try {
boost::json::value jv = boost::json::parse(json_str);
std::string namepipe = jv.at("pipe").as_string().c_str();
std::string typ = jv.at("type").as_string().c_str();
auto pipe = Pipe(namepipe, Pipe::USER);
pipe.openForWrite();
if (typ == "list") {
auto msg = pmc_mtd::list();
pipe.writePipe(msg);
return;
}
else if (typ == "kill") {
int trg = jv.at("kill").as_int64();
auto flag = pmc_mtd::kill(trg);
std::string msg = flag ? "OK" : "Nope";
pipe.writePipe(msg);
return;
}
else if (typ == "exec"){
std::string cmd = jv.at("exec").as_string().c_str();
std::string msg = (pmc_mtd::exec(cmd)) ? "OK" : "ERR";
pipe.writePipe(msg);
return;
}
}
/* 捕获异常后,仅仅只是打印出来? */
catch (std::exception &exp) {
std::cerr << "Exception at: parse_data_from_mq()" << std::endl;
std::cerr << "Exception type: " << typeid(exp).name() << std::endl;
std::cerr << "Exception info: " << exp.what() << std::endl;
}
+347
View File
@@ -0,0 +1,347 @@
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "main/HttpTask.hh"
#include "main/pmc_mtd.hh"
#include "main/subsys_call.hh"
using namespace qing;
namespace qing {
/* -------- HttpTask -------- */
HttpTask::HttpTask(int port, std::function<void(pmc::net::HttpServer& server)> handler)
: port(port), handler(handler) {
this->th = std::make_unique<Thread> ();
init_thread();
}
bool HttpTask::isRunning() {
auto stat = th->check();
return !(stat == Fsm::Stat::STOP || stat == Fsm::Stat::SHUT);
}
void HttpTask::start() {
if (!this->isRunning()) {
th->Activate(); /* FIXME: 这里获取了资源,不知道会不会造成内存泄漏 */
th->WaitStart(); /* TODO: add timeout 增加超时 */
}
}
void HttpTask::stop() {
this->server->stop();
if (this->isRunning())
th->WaitClose();
}
void HttpTask::init_thread() {
/* 构造通信线程 */
this->th = std::make_unique<Thread> ();
/* stop callback 静止事件 */
this->th->set_stop( [](Thread& th) -> void {
/* 由线程提供的等待状态机发生改变信号的方法 */
th.suspend();
});
/* start callback 唤醒事件 */
this->th->set_wake( [this](Thread& th) -> void {
this->server = std::make_unique<pmc::net::HttpServer> ("127.0.0.1", port, "server.crt", "server.key", 4);
handler(*this->server);
th.run();
this->server->start(); /* 这里包含了端口启动提示符输出 */
this->server->run(); /* 堵死线程,等待服务器运行结束 */
});
/* loop callback 循环事件 */
this->th->set_loop( [this](Thread& th) -> void {
/* 如果服务器是主动退出的 */
th.stop(); /* 停止线程,防止跌入死循环 */
});
/* clean callback 清理事件 */
this->th->set_clear( [this] (Thread& th) -> void {
this->server.reset();;
});
}
/*==============================================================*/
/* 这些是尚未整理的工具 */
/* --------------------------- */
/* json字符串转boost.ptree
* FIXME: 这个方法好像在ProcessManagerService进程托管服务中集成了*/
boost::property_tree::ptree parseJsonToPtree(const std::string& jsonStr) {
boost::property_tree::ptree pt;
try {
std::stringstream ss(jsonStr);
boost::property_tree::read_json(ss, pt);
} catch (const boost::property_tree::json_parser_error& e) {
// 解析失败处理
std::cerr << "JSON parse error: " << e.what() << std::endl;
}
return pt;
}
/* --------------------------- */
/* url 解码 */
static std::string url_decode(const std::string& str) {
std::string result;
std::istringstream iss(str);
char ch;
while (iss.get(ch)) {
if (ch == '%') {
int hex;
if (iss >> std::hex >> hex) {
result += static_cast<char>(hex);
}
} else if (ch == '+') {
result += ' ';
} else {
result += ch;
}
}
return result;
}
/*==============================================================*/
/**
* @brief 进程托管服务 - 相关模块
*
* 提供进程的列表、执行和终止功能
* TODO(20260629-qing): 将这个模块合入HttpTask类模块
*/
namespace process_http_server {
/* ---- 注册POST路由 ---- */
void registerRoutes(pmc::net::HttpServer& server) {
server.post("/list", [](const auto& req, const auto& params) {
return handleList(req, params);
});
server.post("/exec", [](const auto& req, const auto& params) {
return handleExec(req, params);
});
server.post("/kill", [](const auto& req, const auto& params) {
return handleKill(req, params);
});
}
/* ---- 解析json ---- */
boost::property_tree::ptree parseJsonBody(const std::string& body) {
boost::property_tree::ptree pt;
try {
std::stringstream ss(body);
boost::property_tree::read_json(ss, pt);
}
catch (...) {
/* ---- JSON解析失败,返回空树 ---- */
}
return pt;
}
std::string buildJsonResponse(bool success, const std::string& message,
const boost::property_tree::ptree& data) {
boost::property_tree::ptree response;
response.put("success", success);
response.put("message", message);
if (!data.empty()) {
response.add_child("data", data);
}
std::stringstream ss;
boost::property_tree::write_json(ss, response);
return ss.str();
}
std::string getTarget(const std::unordered_map<std::string, std::string>& params) {
auto it = params.find("target");
if (it != params.end())
return url_decode(it->second); // <--- 这里
return "";
}
std::string getExecCommand(const std::unordered_map<std::string, std::string>& params) {
auto it = params.find("command");
if (it != params.end())
return url_decode(it->second); // <--- 这里
return "";
}
int getPid(const std::unordered_map<std::string, std::string>& params) {
auto it = params.find("pid");
if (it != params.end()) {
std::string decoded = url_decode(it->second); // <--- 这里
return std::stoi(decoded);
}
return -1;
}
http::response<http::string_body> handleList(
const http::request<http::string_body>& req,
const std::unordered_map<std::string, std::string>& params) {
http::response<http::string_body> res;
res.version(req.version());
res.set(http::field::content_type, "application/json");
try {
std::string target = getTarget(params);
std::string result = listProcesses(target);
boost::property_tree::ptree data = parseJsonToPtree(result);
res.result(http::status::ok);
res.body() = buildJsonResponse(true, "Process list retrieved successfully", data);
}
catch (const std::exception& e) {
res.result(http::status::internal_server_error);
res.body() = buildJsonResponse(false, std::string("Error: ") + e.what());
}
res.prepare_payload();
return res;
}
http::response<http::string_body> handleExec(
const http::request<http::string_body>& req,
const std::unordered_map<std::string, std::string>& params) {
http::response<http::string_body> res;
res.version(req.version());
res.set(http::field::content_type, "application/json");
try {
std::string target = getTarget(params);
std::string command = getExecCommand(params);
if (command.empty()) {
// 尝试从POST body中获取command
auto body_json = parseJsonBody(req.body());
command = body_json.get<std::string>("command", "");
}
if (command.empty()) {
res.result(http::status::bad_request);
res.body() = buildJsonResponse(false, "Missing required parameter: command");
res.prepare_payload();
return res;
}
// 实现命令执行逻辑
std::string result = execCommand(command, target);
boost::property_tree::ptree data;
data.put("command", command);
data.put("output", result);
res.result(http::status::ok);
res.body() = buildJsonResponse(true, "Command executed successfully", data);
}
catch (const std::exception& e) {
res.result(http::status::internal_server_error);
res.body() = buildJsonResponse(false, std::string("Error: ") + e.what());
}
res.prepare_payload();
return res;
}
http::response<http::string_body> handleKill(
const http::request<http::string_body>& req,
const std::unordered_map<std::string, std::string>& params) {
http::response<http::string_body> res;
res.version(req.version());
res.set(http::field::content_type, "application/json");
try {
std::string target = getTarget(params);
int pid = getPid(params);
if (pid <= 0 && !req.body().empty()) {
// 尝试从POST body中获取pid
auto body_json = parseJsonBody(req.body());
pid = body_json.get<int>("pid", -1);
}
if (pid <= 0) {
res.result(http::status::bad_request);
res.body() = buildJsonResponse(false, "Missing or invalid parameter: pid");
res.prepare_payload();
return res;
}
bool success = killProcess(pid, target);
if (success) {
boost::property_tree::ptree data;
data.put("pid", pid);
res.result(http::status::ok);
res.body() = buildJsonResponse(true, "Process terminated successfully", data);
} else {
res.result(http::status::internal_server_error);
res.body() = buildJsonResponse(false, "Failed to terminate process");
}
}
catch (const std::exception& e) {
res.result(http::status::internal_server_error);
res.body() = buildJsonResponse(false, std::string("Error: ") + e.what());
}
res.prepare_payload();
return res;
}
// 如果target为空,在本机执行
// 否则在目标服务器执行
std::string listProcesses(const std::string& target)
{
if (target == "")
return pmc_mtd::list();
else
return subsys_call::send_list_and_recv_pipe(target);
}
std::string execCommand(const std::string& command, const std::string& target)
{
if (target == "")
return pmc_mtd::exec(command) ? "OK" :"ERR";
else
return subsys_call::send_start_and_recv_pipe(target, command); /* 发送启动命令并且接收回复 */
}
bool killProcess(int pid, const std::string& target)
{
if (target == "")
return pmc_mtd::kill(pid);
else
return subsys_call::send_kill_and_recv_pipe(target, pid) == "OK";
}
}
}
+61
View File
@@ -0,0 +1,61 @@
#include <iostream>
#include <stdexcept>
#include "main/PPool.hh"
namespace qing {
void PPool::crtp(const std::string& cmd) try
{
auto pt = std::make_shared<ProcessTask>(cmd);
pt->start(); /* 直接创建了进程丢进容器 */
pool.push_back(pt);
}
/* 如果boost的子进程模块报错,表示子进程创建失败? */
catch (boost::system::system_error &exp) {
std::cerr << "Failed to execute this command: " << cmd << std::endl;
}
void PPool::clr() {
auto it = --pool.end(); /* 由最后一个元素开始 */
for (; it != pool.begin(); --it) /* 回溯遍历 */
if (!(*it)-> isRunning()) { /* 如果任务已经终止 */
auto tmp= it; /* 储存当前位置 */
it++; /* 返回上一个结点 */
pool.erase(tmp); /* 自动释放终止的节点 */
}
/* 循环结束时it == begin(),如果容器为空则end() == begin() */
if (pool.size() > 0 && !(*it)->isRunning()) /* */
pool.erase(it); /* 如果end() == begin(),此步将会试图删除哨兵 */
}
void PPool::kill(int idx) {
/* 从头部向后计数idx */
auto it = pool.begin();
int i = 0;
for (; i < idx && it != pool.end(); ++i, ++it);
if (it != pool.end()) { /* 如果找到了目标(因到达idx而停止)(计数器没有指向尾节点) */
(*it)->stop(); /* 关闭当前任务 */
pool.erase(it); /* 从容器中移除当前任务 */
}
/* 因抵达终点而停下(下标越界) */
else {
throw std::out_of_range("PPool::kill()");
}
}
ProcessTask& PPool::operator[](const size_t idx) {
auto it = pool.begin();
for (int i = 0; i < idx; ++it, ++i) /* 遍历idx次 */
if (it == pool.end()) /* 如果该节点是尾部哨兵(下标越界) */
throw std::out_of_range("PPool::operator[]()");
return **it; /* 返回当前节点 */
}
}
+30
View File
@@ -0,0 +1,30 @@
#include <iostream>
#include "main/ProcessTask.hh"
#ifdef __NEW_VER
namespace qing {
bool ProcessTask::isRunning() {
return p && p->running(exit_code);
}
int ProcessTask::getExitCode() {
return exit_code.value();
}
void ProcessTask::start() {
if (!isRunning()) {
auto ccmd = boost::process::v2::shell(cmd);
auto exe = ccmd.exe();
auto args = ccmd.args();
this->p = std::make_unique<boost::process::v2::process>(ctx, exe, args);
}
}
void ProcessTask::stop() {
p->terminate(exit_code);
if (exit_code) {
std::cerr << "杀死进程失败: " << exit_code.message() << std::endl;
}
else {
p.reset();
}
}
}
#endif
+69
View File
@@ -0,0 +1,69 @@
#include <iostream>
#include <memory>
#include <us/Thread.hpp>
#include <us/ITask.hpp>
#include "main/Tttask.hh"
namespace qing {
Tttask::Tttask(const size_t msglen, size_t msgcnt, const sf_t callback)
: msglen(msglen), msgcnt(msgcnt) {
this->callback = std::make_unique<sf_t>(callback); /* FIXME: 使用指针似乎有所不妥 */
init_thread();
}
void Tttask::start() {
if (!this->isRunning()) {
th->Activate(); /* FIXME: 这里获取了资源,不知道会不会造成内存泄漏 */
th->WaitStart(); /* TODO: add timeout 增加超时 */
}
}
bool Tttask::isRunning() {
auto stat = th->check();
return !(stat == Fsm::Stat::STOP
|| stat == Fsm::Stat::SHUT);
}
void Tttask::init_thread() {
/* 构造通信线程 */
this->th = std::make_unique<Thread> ();
/* stop callback 静止事件 */
this->th->set_stop( [](Thread& th) -> void {
/* 由线程提供的等待状态机发生改变信号的方法 */
th.suspend();
});
/* start callback 唤醒事件 */
this->th->set_wake( [this](Thread& th) -> void {
name = std::to_string(getpid()); /* 以进程名构建消息队列 */
mq = std::make_unique<Mq> (name, msglen, msgcnt, Mq::CREATOR);
th.run();
});
/* loop callback 循环事件 */
this->th->set_loop( [this](Thread& th) -> void {
/* 第一个是接收成功的处理事件,第二个是接收失败的处理事件
*
* TODO: 作为参数传入延时
* TODO: 使用标准库的线程延时*/
mq->recv(*callback, []() { usleep(10000); });
});
/* clean callback 清理事件 */
this->th->set_clear( [this] (Thread& th) -> void {
/* 直接重置指针 */
mq.reset();
});
}
}
+132
View File
@@ -0,0 +1,132 @@
#include <boost/json.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "main/PPool.hh"
#include "main/pmc_mtd.hh"
namespace qing {
/* -------- 用于存放子进程的进程池 -------- */
static PPool ppool;
/*-------------------------------------------------------------------------*/
/* --------【pmc method子进程操作】集合 -------- */
namespace pmc_mtd {
/*
* 列举出所有子进程。
*
* {
* "pipe": "<int>",
* "type": "list",
* } */
auto list() -> std::string {
boost::json::array processes;
/* 遍历子进程池
*
* FIXME: 子进程池的迭代器完成后,改为使用for-in迭代 */
//ppool.clr() /* 保留已经跑完的进程,因为可能会涉及到输出的提取 *?
for (int i = 0; i < ppool.size(); ++i) {
processes.push_back({ /* 向json中推入对象 */
{"index", i},
{"pid", ppool[i].pid()},
{"status", ppool[i].check()}
});
}
/* 返回序列化的json对象 */
return boost::json::serialize(processes);
}
/*
* 删除一个子进程,需要提供pid
*
* {
* "pipe": "<integer>",
* "type": "kill",
* "kill": <integer>
* } */
auto kill(const int pid) -> bool {
/* 遍历子进程池对比pid */
for (int i=0; i<ppool.size(); ++i)
if ( ppool[i].pid() == pid) { /* 寻找目标进程 */
ppool.kill(i); /* 杀死该进程 */
return true; } /* 成功返回逻辑真 */
/* 失败(没找到)返回逻辑假 */
return false;
}
/*
* 启动一个子进程
*
* {
* "pipe": "<integer>",
* "type": "exec",
* "exec": "<commandline>"
* } */
auto exec(const std::string& cmd) -> bool try
{
//ppool.clr(); /* 保留跑完的子进程 */
ppool.crtp(cmd);
return true; /* 成功返回逻辑真 */
}
/* 如果出现任何异常,返回假 */
catch(std::exception& exp) {
return false;
}
/* 解析自启动列表、添加自启动项
*
* 如果在解析过程中出错,只是打印异常? */
void parse_self_init_list(std::string &path)
try {
std::ifstream file(path);
if (!file.is_open()) { /* ---- 没能打开自启动文件 ---- */
std::cerr << "Failed to open self-init list" << std::endl;
return;
}
std::string row = "";
char ch;
while (file.get(ch))
if (ch == '\n') {
auto pos = row.find("#");
if (pos != -1)
row = row.substr(0, pos);
if (row != "") { /* trim() */
ppool.clr();
ppool.crtp(row); /* 创建进程 */
row = "";
}
}
else row += ch;
file.close();
}
catch (std::exception &exp) {
std::cerr << "Exception at: parse_self_init_list()" << std::endl;
std::cerr << "Exception type: " << typeid(exp).name() << std::endl;
std::cerr << "Exception info: " << exp.what() << std::endl;
}
}
}
+163
View File
@@ -0,0 +1,163 @@
#include "iostream"
#include "fstream"
#include <boost/json.hpp>
#include "tt/Mq.h"
#include "tt/Pipe.h"
#include "main/subsys_call.hh"
namespace qing {
namespace subsys_call {
/*-------------------------------------------------------------------------*/
/* -------- 向pmc的消息队列发送启动命令并且从管道接收回复 -------- */
std::string send_start_and_recv_pipe(const std::string& name_mq, const std::string& exec)
try {
auto name_pipe = std::to_string(getpid());
auto mq = Mq(name_mq, 2048, 100, Mq::USER); /* 放在这里避免管道文件的残留 */
boost::json::object obj;
obj["pipe"] = name_pipe;
obj["type"] = "exec";
obj["exec"] = exec;
auto jsonstr = boost::json::serialize(obj);
auto pipe = Pipe(name_pipe, Pipe::CREATOR); /* FIXME: 创建管道文件到/tmp下面 */
if (!pipe.openForRead(true)) {
std::cerr << "Failed to open pipe" << std::endl;
return "ERR";
}
mq.send(jsonstr);
if (!pipe.waitForRead(1, 0)) {
std::cerr << "Pipe Read Timeout" << std::endl;
return "ERR";
}
std::string res = "";
if (pipe.readPipe(&res) < 0) {
std::cerr << "Failed to read pipe" << std::endl;
return "ERR";
}
return res;
}
//catch (boost::interprocess::interprocess_exception &exp) {
// std::cerr << "Target Pmc Is Not Found" << std::endl;
// return 1;
//}
catch (std::exception &exp) {
std::cerr << "Exception at: send_start_and_recv_pipe()" << std::endl;
std::cerr << "Exception type: " << typeid(exp).name() << std::endl;
std::cerr << "Exception info: " << exp.what() << std::endl;
return "ERR";
}
/* -------- 向目标子系统发送列举命令并收集结果 -------- */
std::string send_list_and_recv_pipe(const std::string& name_mq)
try {
auto name_pipe = std::to_string(getpid());
auto mq = Mq(name_mq, 2048, 100, Mq::USER);
boost::json::object obj;
obj["pipe"] = name_pipe;
obj["type"] = "list";
auto jsonstr = boost::json::serialize(obj);
auto pipe = Pipe(name_pipe, Pipe::CREATOR);
if (!pipe.openForRead(true)) {
std::cerr << "Failed to open pipe" << std::endl;
return "ERR";
}
mq.send(jsonstr);
if (!pipe.waitForRead(1, 0)) {
std::cerr << "Pipe Read Timeout" << std::endl;
return "ERR";
}
std::string res = "";
if (pipe.readPipe(&res) < 0) {
std::cerr << "Failed to read pipe" << std::endl;
return "ERR";
}
return res;
}
//catch (boost::interprocess::interprocess_exception &exp) {
// std::cerr << "Target Pmc Is Not Found" << std::endl;
// return 1;
//}
catch (std::exception &exp) {
std::cerr << "Exception at: send_list_and_recv_pipe()" << std::endl;
std::cerr << "Exception type: " << typeid(exp).name() << std::endl;
std::cerr << "Exception info: " << exp.what() << std::endl;
return "ERR";
}
/* -------- 删除操作调用 -------- */
std::string send_kill_and_recv_pipe(const std::string& name_mq, const int kill)
try{
auto name_pipe = std::to_string(getpid());
auto mq = Mq(name_mq, 2048, 100, Mq::USER);
boost::json::object obj;
obj["pipe"] = name_pipe;
obj["type"] = "kill";
obj["kill"] = kill;
auto jsonstr = boost::json::serialize(obj);
auto pipe = Pipe(name_pipe, Pipe::CREATOR);
if (!pipe.openForRead(true)) {
std::cerr << "Failed to open pipe" << std::endl;
return "ERR";
}
mq.send(jsonstr);
if (!pipe.waitForRead(1, 0)) {
std::cerr << "Pipe Read Timeout" << std::endl;
return "ERR";
}
std::string res = "";
if (pipe.readPipe(&res) < 0) {
std::cerr << "Failed to read pipe" << std::endl;
return "ERR";
}
else return res;
}
/* 没有打开目标子系统的消息队列时,会触发这个异常
* 但是实际上这里捕获的是进程间通信通用异常(旧版) */
//catch (boost::interprocess::interprocess_exception &exp) {
// std::cerr << "Target Pmc Is Not Found" << std::endl;
// return 1;
//}
/* 这些函数抛出异常后可能导致管道文件残留 */
catch (std::exception &exp) {
std::cerr << "Exception at: send_kill_and_recv_pipe()" << std::endl;
std::cerr << "Exception type: " << typeid(exp).name() << std::endl;
std::cerr << "Exception info: " << exp.what() << std::endl;
return "ERR";
}
}
}