mirror of
https://github.com/veops/cmdb.git
synced 2025-09-07 05:47:00 +08:00
Compare commits
165 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
5b38385f7e | ||
|
036e1d236b | ||
|
c31be0f753 | ||
|
764d2fac3f | ||
|
f4079e9c3e | ||
|
2a0ed72235 | ||
|
9e803ae4c7 | ||
|
bebdb61adf | ||
|
f49cad771b | ||
|
a5b4fbda40 | ||
|
2cce2d5cf2 | ||
|
e720b7af66 | ||
|
09e4a5111b | ||
|
3539b12503 | ||
|
21d8673b5d | ||
|
7154426dc7 | ||
|
ca75c7dcd0 | ||
|
194a2254a6 | ||
|
26abad14d0 | ||
|
1521a71f9c | ||
|
d425b455f1 | ||
|
230307474b | ||
|
69d6b40e39 | ||
|
5dc2f89e7f | ||
|
9eaca4d6a0 | ||
|
3680a462f5 | ||
|
3ac50e7cd8 | ||
|
21b2cc1d5d | ||
|
cd5448cc7d | ||
|
10610bdb4b | ||
|
b5c2156387 | ||
|
b05ae0d1a7 | ||
|
bbf6138d43 | ||
|
1ba3e6a680 | ||
|
64045c1f93 | ||
|
5a3e55813c | ||
|
bc72e58886 | ||
|
9e78955ba1 | ||
|
136853d9a4 | ||
|
036e3ad00d | ||
|
5ce6c93237 | ||
|
43dba7f7ed | ||
|
f4879d20d6 | ||
|
740e4c6034 | ||
|
0f2baa1d94 | ||
|
405b0af72c | ||
|
a4e5178979 | ||
|
c14fe23283 | ||
|
b3a058f908 | ||
|
bd82a0e27c | ||
|
f22a5c3543 | ||
|
ed81c3f091 | ||
|
07814b85f9 | ||
|
db52b28d6b | ||
|
fc85ba21c8 | ||
|
6c5ee3fcd9 | ||
|
40f1ef88a9 | ||
|
bce422ffc8 | ||
|
7c79066532 | ||
|
1129ac93fb | ||
|
5ab0e7e737 | ||
|
23319c7417 | ||
|
c74f85cabb | ||
|
fce2b689fb | ||
|
105327bb0c | ||
|
745c43d0a4 | ||
|
3130d94568 | ||
|
04a66eb239 | ||
|
68390ec6f1 | ||
|
17392be138 | ||
|
f2fdb29221 | ||
|
4a18698423 | ||
|
95ccee04f9 | ||
|
b60628247b | ||
|
a6d7699ab4 | ||
|
4b21bcc438 | ||
|
33dce2f0f3 | ||
|
d43b827fe5 | ||
|
aec8bade41 | ||
|
89ae89a449 | ||
|
945f90e386 | ||
|
2ba6a16613 | ||
|
6089039366 | ||
|
e1e5307084 | ||
|
2ff7fce9dd | ||
|
fc4d3e0c1a | ||
|
f66a94712e | ||
|
24664c7686 | ||
|
1d668bab6e | ||
|
3d4b84909e | ||
|
8341e742eb | ||
|
a71ba83de0 | ||
|
9668131c18 | ||
|
4a744dcad9 | ||
|
2a420225e2 | ||
|
ff67785618 | ||
|
dfe1ba55d5 | ||
|
90b1b6b7af | ||
|
d5fbe42ed7 | ||
|
f424ad6864 | ||
|
16b724bd40 | ||
|
f70ed54cad | ||
|
dd64564160 | ||
|
cc2cdbcc9f | ||
|
81fe850627 | ||
|
487d9f76f6 | ||
|
92dd4c5dfe | ||
|
8ee7c6daf8 | ||
|
882b158d18 | ||
|
85222443c0 | ||
|
1696ecf49d | ||
|
73b92ff533 | ||
|
e977bb15a5 | ||
|
7c46d6cdbf | ||
|
4d11c1f7db | ||
|
0a563deb11 | ||
|
ba80ec4403 | ||
|
3b7cc4595b | ||
|
9fe47657a6 | ||
|
5a4a6caa07 | ||
|
9dadbe1599 | ||
|
40d016f513 | ||
|
655edaa7c8 | ||
|
7fa5cff919 | ||
|
d19834ed5d | ||
|
b6be430aa3 | ||
|
63792c242f | ||
|
10f7029722 | ||
|
ba176542dc | ||
|
aae3b6e2ff | ||
|
b370c7d46e | ||
|
efa5a8ea5d | ||
|
fd532626ac | ||
|
617337c614 | ||
|
9a3d24ac81 | ||
|
454dd4c56b | ||
|
88ad72d4dc | ||
|
8d1517d550 | ||
|
d3a8ef5966 | ||
|
e5baa5012d | ||
|
a1f63b00dd | ||
|
47ded84231 | ||
|
224a48a5f3 | ||
|
0e7c52df71 | ||
|
ff701cc770 | ||
|
6a7bb725cc | ||
|
0a13186c13 | ||
|
a0ffeb9950 | ||
|
6c70ec6d53 | ||
|
4b5f82699a | ||
|
f78c3b928b | ||
|
332659c1d5 | ||
|
3beb2706dc | ||
|
a14111e1ce | ||
|
c4320c14f9 | ||
|
4c5442748f | ||
|
a81750acba | ||
|
0439e2462b | ||
|
3b62bd7ac9 | ||
|
f6add52721 | ||
|
c85e535288 | ||
|
c0c6d116b5 | ||
|
39153e92d1 | ||
|
42bcc2e510 | ||
|
398fbb25dc |
14
.gitignore
vendored
14
.gitignore
vendored
@@ -38,6 +38,7 @@ pip-log.txt
|
||||
.tox
|
||||
nosetests.xml
|
||||
.pytest_cache
|
||||
cmdb-api/test-output
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
@@ -65,12 +66,11 @@ settings.py
|
||||
*.db
|
||||
|
||||
# UI
|
||||
ui/node_modules
|
||||
ui/dist
|
||||
cmdb-ui/node_modules
|
||||
cmdb-ui/dist
|
||||
|
||||
# Log files
|
||||
ui/npm-debug.log*
|
||||
ui/yarn-debug.log*
|
||||
ui/yarn-error.log*
|
||||
ui/yarn.lock
|
||||
|
||||
cmdb-ui/npm-debug.log*
|
||||
cmdb-ui/yarn-debug.log*
|
||||
cmdb-ui/yarn-error.log*
|
||||
cmdb-ui/package-lock.json
|
||||
|
48
Dockerfile
Normal file
48
Dockerfile
Normal file
@@ -0,0 +1,48 @@
|
||||
# ================================= UI ================================
|
||||
FROM node:alpine AS builder
|
||||
|
||||
LABEL description="cmdb-ui"
|
||||
|
||||
COPY cmdb-ui /data/apps/cmdb-ui
|
||||
|
||||
WORKDIR /data/apps/cmdb-ui
|
||||
|
||||
RUN sed -i "s#http://127.0.0.1:5000##g" .env && yarn install && yarn build
|
||||
|
||||
|
||||
FROM nginx:alpine AS cmdb-ui
|
||||
|
||||
RUN mkdir /etc/nginx/html && rm -f /etc/nginx/conf.d/default.conf
|
||||
|
||||
COPY --from=builder /data/apps/cmdb-ui/dist /etc/nginx/html/
|
||||
|
||||
|
||||
# ================================= API ================================
|
||||
FROM python:3.7-alpine AS cmdb-api
|
||||
|
||||
LABEL description="Python3.7,cmdb"
|
||||
|
||||
COPY cmdb-api /data/apps/cmdb
|
||||
|
||||
WORKDIR /data/apps/cmdb
|
||||
|
||||
RUN apk add --no-cache tzdata gcc musl-dev libffi-dev openldap-dev
|
||||
|
||||
ENV TZ=Asia/Shanghai
|
||||
|
||||
RUN pip install --no-cache-dir -r requirements.txt \
|
||||
&& cp ./settings.py.example settings.py \
|
||||
&& sed -i "s#{user}:{password}@127.0.0.1:3306/{db}#cmdb:123456@mysql:3306/cmdb#g" settings.py \
|
||||
&& sed -i "s#redis://127.0.0.1#redis://redis#g" settings.py \
|
||||
&& sed -i 's#CACHE_REDIS_HOST = "127.0.0.1"#CACHE_REDIS_HOST = "redis"#g' settings.py
|
||||
|
||||
ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.7.3/wait /wait
|
||||
RUN chmod +x /wait
|
||||
|
||||
CMD ["bash", "-c", "flask run"]
|
||||
|
||||
|
||||
# ================================= Search ================================
|
||||
FROM docker.elastic.co/elasticsearch/elasticsearch:7.4.2 AS cmdb-search
|
||||
|
||||
RUN yes | ./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.4.2/elasticsearch-analysis-ik-7.4.2.zip
|
138
LICENSE
138
LICENSE
@@ -1,21 +1,125 @@
|
||||
MIT License
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (c) pycook
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
Preamble
|
||||
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
|
||||
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
|
||||
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
|
||||
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
|
||||
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
How to Apply These Terms to Your New Programs
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
one line to give the program's name and an idea of what it does.
|
||||
Copyright (C) yyyy 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 2
|
||||
of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
|
||||
type `show w'. This is free software, and you are welcome
|
||||
to redistribute it under certain conditions; type `show c'
|
||||
for details.
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright
|
||||
interest in the program `Gnomovision'
|
||||
(which makes passes at compilers) written
|
||||
by James Hacker.
|
||||
|
||||
signature of Ty Coon, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.
|
30
Makefile
30
Makefile
@@ -1,25 +1,37 @@
|
||||
.PHONY: docs test
|
||||
.PHONY: env clean api ui worker
|
||||
|
||||
help:
|
||||
@echo " env create a development environment using virtualenv"
|
||||
@echo " env create a development environment using pipenv"
|
||||
@echo " deps install dependencies using pip"
|
||||
@echo " clean remove unwanted files like .pyc's"
|
||||
@echo " lint check style with flake8"
|
||||
@echo " test run all your tests using py.test"
|
||||
@echo " api start api server"
|
||||
@echo " ui start ui server"
|
||||
@echo " worker start async tasks worker"
|
||||
|
||||
env:
|
||||
sudo easy_install pip && \
|
||||
pip install pipenv &&
|
||||
pip install pipenv -i https://pypi.douban.com/simple && \
|
||||
npm install yarn && \
|
||||
make deps
|
||||
|
||||
deps:
|
||||
pipenv install --dev
|
||||
pipenv install --dev && \
|
||||
pipenv run flask db-setup && \
|
||||
pipenv run flask init-cache && \
|
||||
cd cmdb-ui && yarn install && cd ..
|
||||
|
||||
api:
|
||||
cd cmdb-api && pipenv run flask run -h 0.0.0.0
|
||||
|
||||
worker:
|
||||
cd cmdb-api && pipenv run celery worker -A celery_worker.celery -E -Q cmdb_async --concurrency=1
|
||||
|
||||
ui:
|
||||
cd cmdb-ui && yarn run serve
|
||||
|
||||
clean:
|
||||
python manage.py clean
|
||||
pipenv run flask clean
|
||||
|
||||
lint:
|
||||
flake8 --exclude=env .
|
||||
|
||||
test:
|
||||
py.test tests
|
151
README.md
151
README.md
@@ -1,66 +1,133 @@
|
||||
<h1 align="center">CMDB</h1>
|
||||
<div align="center">
|
||||
尽可能实现比较通用的运维资产数据的配置和管理
|
||||
|
||||
As far as possible to achieve more universal configuration and management of IT resources
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
|
||||
[](https://github.com/pycook/cmdb/blob/master/LICENSE)
|
||||
[](https://github.com/pycook/cmdb/blob/master/LICENSE)
|
||||
[](https://github.com/sendya/ant-design-pro-vue)
|
||||
[](https://github.com/pallets/flask)
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
[English](README.md) / [中文](README_cn.md)
|
||||
|
||||
- 在线预览: [CMDB](http://121.42.12.46:8000)
|
||||
- username: admin
|
||||
- password: admin
|
||||
## DEMO ONLINE
|
||||
- Preview online: [CMDB](http://121.42.12.46:8000)
|
||||
- username: demo
|
||||
- password: 123456
|
||||
|
||||
Overview
|
||||
> **ATTENTION**: branch `master` may be unstable as the result of continued development, please pull code from [releases](https://github.com/pycook/cmdb/releases)
|
||||
|
||||
----
|
||||

|
||||
## Overview
|
||||
|
||||

|
||||
The CMDB is a universal project that can define and manage almost all IT resources, even every resource as long as you want to, which treat all IT resources as resource objects. Objects has both attributes and relationship.
|
||||
|
||||
环境和依赖
|
||||
----
|
||||
- 存储: mysql, redis
|
||||
- python版本: python2.7, >=python3.6
|
||||
CMDB's main distinguishing features as compared to other resource systems are:
|
||||
- Define attributes of resource objects dynamically,you don't need to define all the attributes at the beginning.
|
||||
- Define relationship of resource objects dynamically and simply, even you can draw the relationship through the web.
|
||||
- Three view:
|
||||
- Resource view: model instance data that users can subscribe
|
||||
- Tree view: the model is hierarchical by field, shown in a tree diagram, and users can subscribe
|
||||
- Relational view: relationships between models, shown in a tree diagram, **are configurable by the administrator**
|
||||
|
||||
- Authority management
|
||||
|
||||
|
||||
安装
|
||||
----
|
||||
- 启动mysql服务, redis服务
|
||||
## Install
|
||||
|
||||
- 创建数据库cmdb
|
||||
- 拉取代码
|
||||
```bash
|
||||
git clone https://github.com/pycook/cmdb.git
|
||||
cd cmdb
|
||||
cp api/settings.py.example api/settings.py
|
||||
```
|
||||
设置api/settings.py里的database
|
||||
There are various ways of installing CMDB.
|
||||
|
||||
- 安装库
|
||||
- 后端: ```pipenv run pipenv install```
|
||||
- 前端: ```cd ui && yarn install && cd ..```
|
||||
### Install by Docker
|
||||
- Prepare: install docker and docker-compose
|
||||
- In directory cmdb
|
||||
```
|
||||
docker-compose up -d
|
||||
```
|
||||
- View: [http://127.0.0.1:8000](http://127.0.0.1:8000)
|
||||
|
||||
### Environment and dependency
|
||||
- database: mysql
|
||||
- cache: redis
|
||||
- python: python2.7, >=python3.6
|
||||
|
||||
### Install
|
||||
- Start mysql, redis
|
||||
- Create mysql database: cmdb
|
||||
- Pull code
|
||||
```bash
|
||||
git clone https://github.com/pycook/cmdb.git
|
||||
cd cmdb
|
||||
cp cmdb-api/settings.py.example cmdb-api/settings.py
|
||||
```
|
||||
**set database in config file cmdb-api/settings.py**
|
||||
|
||||
- Install library
|
||||
- backend: ```cd cmdb-api && pipenv run pipenv install && cd ..```
|
||||
- frontend: ```cd cmdb-ui && yarn install && cd ..```
|
||||
|
||||
- 创建数据库表 ```pipenv run flask db-setup```
|
||||
- 可以将docs/cmdb.sql导入到数据库里,登录用户和密码都是:admin
|
||||
|
||||
- 启动服务
|
||||
- 后端: ```pipenv run flask run -h 0.0.0.0```
|
||||
- 前端: ```cd ui && yarn run serve```
|
||||
|
||||
- 浏览器打开: [http://127.0.0.1:8000](http://127.0.0.1:8000)
|
||||
- 如果是非本机访问, 要修改**ui/.env**里**VUE_APP_API_BASE_URL**里的IP地址为后端服务的ip地址
|
||||
- Create tables of cmdb database:
|
||||
|
||||
in **cmdb-api** directory: ```pipenv run flask db-setup && pipenv run flask init-cache```
|
||||
- Suggest step: (default: user:demo,password:123456)
|
||||
|
||||
docker 一键构建和运行
|
||||
----
|
||||
- 进入主目录(首次镜像的构建需要**10分钟**左右,视网络情况而定)
|
||||
```
|
||||
docker-compose up -d
|
||||
```
|
||||
``` source docs/cmdb.sql```
|
||||
|
||||
- 浏览器打开: [http://localhost:8000](http://localhost:8000)
|
||||
- Start service
|
||||
- backend: in **cmdb-api** directory: ```pipenv run flask run -h 0.0.0.0```
|
||||
- frontend: in **cmdb-ui** directory: ```yarn run serve```
|
||||
- worker: in **cmdb-api** directory: ```pipenv run celery worker -A celery_worker.celery -E -Q cmdb_async --concurrency=1```
|
||||
|
||||
- homepage: [http://127.0.0.1:8000](http://127.0.0.1:8000)
|
||||
- if not run localhost: please change ip address(**VUE_APP_API_BASE_URL**) in config file **cmdb-ui/.env** into your backend ip address
|
||||
|
||||
### Install by Makefile
|
||||
- Start mysql,redis
|
||||
- Create mysql database: cmdb
|
||||
- Pull code
|
||||
```bash
|
||||
git clone https://github.com/pycook/cmdb.git
|
||||
cd cmdb
|
||||
cp cmdb-api/settings.py.example cmdb-api/settings.py
|
||||
```
|
||||
**set database in config file cmdb-api/settings.py**
|
||||
|
||||
- In cmdb directory,start in order as follows:
|
||||
- enviroment: ```make env```
|
||||
- start API: ```make api```
|
||||
- start UI: ```make ui```
|
||||
- start worker: ```make worker```
|
||||
|
||||
## Contributing
|
||||
|
||||
1. Fork it
|
||||
1. Create your feature branch (`git checkout -b my-feature`)
|
||||
1. Commit your changes (`git commit -am 'Add some feature'`)
|
||||
1. Push to the branch (`git push origin my-feature`)
|
||||
1. Create new Pull Request
|
||||
|
||||
|
||||
## DEMO
|
||||
##### resource view
|
||||

|
||||
|
||||
##### tree view
|
||||

|
||||
|
||||
##### relationship view
|
||||

|
||||
|
||||
##### user subscription
|
||||

|
||||
|
||||
##### define relationship view
|
||||

|
||||
|
||||
-----
|
||||
_**Welcome to join us through QQ group(336164978)**_
|
||||
|
||||

|
||||
|
112
README_cn.md
Normal file
112
README_cn.md
Normal file
@@ -0,0 +1,112 @@
|
||||
<h1 align="center">CMDB</h1>
|
||||
<div align="center">
|
||||
尽可能实现比较通用的运维资源的配置和管理
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
|
||||
[](https://github.com/pycook/cmdb/blob/master/LICENSE)
|
||||
[](https://github.com/sendya/ant-design-pro-vue)
|
||||
[](https://github.com/pallets/flask)
|
||||
|
||||
</div>
|
||||
|
||||
[English](README.md) / [中文](README_cn.md)
|
||||
|
||||
- 在线预览: [CMDB](http://121.42.12.46:8000)
|
||||
- username: demo
|
||||
- password: 123456
|
||||
|
||||
> **重要提示**: `master` 分支在开发过程中可能处于 *不稳定的状态* 。
|
||||
请通过[releases](https://github.com/pycook/cmdb/releases)获取
|
||||
|
||||
Overview
|
||||
----
|
||||
### 3种类型视图
|
||||
1. 资源视图 - 模型的实例数据, 用户可订阅
|
||||
2. 树形视图 - 模型按字段分级, 用树形图方式展示, 用户可订阅
|
||||
3. 关系视图 - 模型之间的关系, 用树形图方式展示, **管理员可配置**
|
||||
|
||||
##### 资源视图
|
||||

|
||||
|
||||
##### 树形视图
|
||||

|
||||
|
||||
##### 关系视图
|
||||

|
||||
|
||||
##### 用户订阅
|
||||

|
||||
|
||||
##### 关系视图配置
|
||||

|
||||
|
||||
Docker一键快速构建
|
||||
----
|
||||
- 进入主目录(先安装docker环境)
|
||||
```
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
- 浏览器打开: [http://127.0.0.1:8000](http://127.0.0.1:8000)
|
||||
|
||||
|
||||
本地搭建: 环境和依赖
|
||||
----
|
||||
- 存储: mysql, redis
|
||||
- python版本: python2.7, >=python3.6
|
||||
|
||||
Install
|
||||
----
|
||||
- 启动mysql服务, redis服务
|
||||
|
||||
- 创建数据库cmdb
|
||||
- 拉取代码
|
||||
```bash
|
||||
git clone https://github.com/pycook/cmdb.git
|
||||
cd cmdb
|
||||
cp cmdb-api/settings.py.example cmdb-api/settings.py
|
||||
```
|
||||
**设置cmdb-api/settings.py里的database**
|
||||
|
||||
- 安装库
|
||||
- 后端: ```cd cmdb-api && pipenv run pipenv install && cd ..```
|
||||
- 前端: ```cd cmdb-ui && yarn install && cd ..```
|
||||
|
||||
- 创建数据库表: 进入**cmdb-api**目录执行 ```pipenv run flask db-setup && pipenv run flask init-cache```
|
||||
- 可以将docs/cmdb.sql导入到数据库里,登录用户和密码分别是:demo/123456
|
||||
|
||||
- 启动服务
|
||||
- 后端: 进入**cmdb-api**目录执行 ```pipenv run flask run -h 0.0.0.0```
|
||||
- 前端: 进入**cmdb-ui**目录执行```yarn run serve```
|
||||
- worker: 进入**cmdb-api**目录执行 ```pipenv run celery worker -A celery_worker.celery -E -Q cmdb_async --concurrency=1```
|
||||
|
||||
- 浏览器打开: [http://127.0.0.1:8000](http://127.0.0.1:8000)
|
||||
- 如果是非本机访问, 要修改**cmdb-ui/.env**里**VUE_APP_API_BASE_URL**里的IP地址为后端服务的ip地址
|
||||
|
||||
|
||||
Install by Makefile
|
||||
----
|
||||
- 启动mysql服务, redis服务
|
||||
|
||||
- 创建数据库cmdb
|
||||
- 拉取代码
|
||||
```bash
|
||||
git clone https://github.com/pycook/cmdb.git
|
||||
cd cmdb
|
||||
cp cmdb-api/settings.py.example cmdb-api/settings.py
|
||||
```
|
||||
**设置cmdb-api/settings.py里的database**
|
||||
|
||||
- 顺序在cmdb目录下执行
|
||||
- 环境: ```make env```
|
||||
- 启动API: ```make api```
|
||||
- 启动UI: ```make ui```
|
||||
- 启动worker: ```make worker```
|
||||
|
||||
|
||||
----
|
||||
_**欢迎加入CMDB运维开发QQ群(336164978)**_
|
||||
|
||||

|
@@ -1,20 +0,0 @@
|
||||
# build under cmdb directory other than api
|
||||
# maybe use: cd ..
|
||||
FROM centos:7.6.1810 AS cmdb-api
|
||||
|
||||
LABEL description="Python2.7.5,cmdb"
|
||||
|
||||
RUN mkdir -p /data/apps/cmdb /data/apps/cmdb/logs
|
||||
|
||||
COPY . /data/apps/cmdb
|
||||
|
||||
WORKDIR /data/apps/cmdb
|
||||
|
||||
RUN yum install -y epel-release && yum clean all\
|
||||
&& yum install -y python-pip \
|
||||
&& pip install --no-cache-dir -r docs/requirements.txt \
|
||||
&& cp ./api/settings.py.example ./api/settings.py \
|
||||
&& sed -i "s#{user}:{password}@127.0.0.1:3306/{db}#cmdb:123456@mysql:3306/cmdb#g" api/settings.py \
|
||||
&& sed -i "s/127.0.0.1/redis/g" api/settings.py
|
||||
|
||||
CMD ["bash", "-c", "flask run"]
|
@@ -1,31 +0,0 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
import json
|
||||
|
||||
import click
|
||||
from flask.cli import with_appcontext
|
||||
|
||||
import api.lib.cmdb.ci
|
||||
from api.extensions import db
|
||||
from api.extensions import rd
|
||||
from api.models.cmdb import CI
|
||||
|
||||
|
||||
@click.command()
|
||||
@with_appcontext
|
||||
def init_cache():
|
||||
db.session.remove()
|
||||
|
||||
cis = CI.get_by(to_dict=False)
|
||||
for ci in cis:
|
||||
|
||||
if list(filter(lambda x: x, rd.get([ci.id]))):
|
||||
continue
|
||||
|
||||
m = api.lib.cmdb.ci.CIManager()
|
||||
ci_dict = m.get_ci_by_id_from_db(ci.id, need_children=False, use_master=False)
|
||||
rd.delete(ci.id)
|
||||
rd.add({ci.id: json.dumps(ci_dict)})
|
||||
|
||||
db.session.remove()
|
@@ -1,152 +0,0 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
from __future__ import unicode_literals
|
||||
|
||||
import datetime
|
||||
|
||||
import six
|
||||
from markupsafe import escape
|
||||
|
||||
from api.lib.cmdb.cache import AttributeCache
|
||||
from api.models.cmdb import Attribute
|
||||
from api.models.cmdb import CIIndexValueDateTime
|
||||
from api.models.cmdb import CIIndexValueFloat
|
||||
from api.models.cmdb import CIIndexValueInteger
|
||||
from api.models.cmdb import CIIndexValueText
|
||||
from api.models.cmdb import CIValueDateTime
|
||||
from api.models.cmdb import CIValueFloat
|
||||
from api.models.cmdb import CIValueInteger
|
||||
from api.models.cmdb import CIValueText
|
||||
from api.models.cmdb import FloatChoice
|
||||
from api.models.cmdb import IntegerChoice
|
||||
from api.models.cmdb import TextChoice
|
||||
|
||||
|
||||
def string2int(x):
|
||||
return int(float(x))
|
||||
|
||||
|
||||
def str2datetime(x):
|
||||
try:
|
||||
return datetime.datetime.strptime(x, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
type_map = {
|
||||
'deserialize': {
|
||||
Attribute.INT: string2int,
|
||||
Attribute.FLOAT: float,
|
||||
Attribute.TEXT: lambda x: escape(x).encode('utf-8').decode('utf-8'),
|
||||
Attribute.TIME: lambda x: escape(x).encode('utf-8').decode('utf-8'),
|
||||
Attribute.DATETIME: str2datetime,
|
||||
Attribute.DATE: str2datetime,
|
||||
},
|
||||
'serialize': {
|
||||
Attribute.INT: int,
|
||||
Attribute.FLOAT: float,
|
||||
Attribute.TEXT: lambda x: x if isinstance(x, six.text_type) else str(x),
|
||||
Attribute.TIME: lambda x: x if isinstance(x, six.text_type) else str(x),
|
||||
Attribute.DATE: lambda x: x.strftime("%Y-%m-%d"),
|
||||
Attribute.DATETIME: lambda x: x.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
},
|
||||
'serialize2': {
|
||||
Attribute.INT: int,
|
||||
Attribute.FLOAT: float,
|
||||
Attribute.TEXT: lambda x: x.decode() if not isinstance(x, six.string_types) else x,
|
||||
Attribute.TIME: lambda x: x.decode() if not isinstance(x, six.string_types) else x,
|
||||
Attribute.DATE: lambda x: x.decode() if not isinstance(x, six.string_types) else x,
|
||||
Attribute.DATETIME: lambda x: x.decode() if not isinstance(x, six.string_types) else x,
|
||||
},
|
||||
'choice': {
|
||||
Attribute.INT: IntegerChoice,
|
||||
Attribute.FLOAT: FloatChoice,
|
||||
Attribute.TEXT: TextChoice,
|
||||
},
|
||||
'table': {
|
||||
Attribute.INT: CIValueInteger,
|
||||
Attribute.TEXT: CIValueText,
|
||||
Attribute.DATETIME: CIValueDateTime,
|
||||
Attribute.DATE: CIValueDateTime,
|
||||
Attribute.TIME: CIValueText,
|
||||
Attribute.FLOAT: CIValueFloat,
|
||||
'index_{0}'.format(Attribute.INT): CIIndexValueInteger,
|
||||
'index_{0}'.format(Attribute.TEXT): CIIndexValueText,
|
||||
'index_{0}'.format(Attribute.DATETIME): CIIndexValueDateTime,
|
||||
'index_{0}'.format(Attribute.DATE): CIIndexValueDateTime,
|
||||
'index_{0}'.format(Attribute.TIME): CIIndexValueText,
|
||||
'index_{0}'.format(Attribute.FLOAT): CIIndexValueFloat,
|
||||
},
|
||||
'table_name': {
|
||||
Attribute.INT: 'c_value_integers',
|
||||
Attribute.TEXT: 'c_value_texts',
|
||||
Attribute.DATETIME: 'c_value_datetime',
|
||||
Attribute.DATE: 'c_value_datetime',
|
||||
Attribute.TIME: 'c_value_texts',
|
||||
Attribute.FLOAT: 'c_value_floats',
|
||||
'index_{0}'.format(Attribute.INT): 'c_value_index_integers',
|
||||
'index_{0}'.format(Attribute.TEXT): 'c_value_index_texts',
|
||||
'index_{0}'.format(Attribute.DATETIME): 'c_value_index_datetime',
|
||||
'index_{0}'.format(Attribute.DATE): 'c_value_index_datetime',
|
||||
'index_{0}'.format(Attribute.TIME): 'c_value_index_texts',
|
||||
'index_{0}'.format(Attribute.FLOAT): 'c_value_index_floats',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class TableMap(object):
|
||||
def __init__(self, attr_name=None):
|
||||
self.attr_name = attr_name
|
||||
|
||||
@property
|
||||
def table(self):
|
||||
attr = AttributeCache.get(self.attr_name)
|
||||
i = "index_{0}".format(attr.value_type) if attr.is_index else attr.value_type
|
||||
return type_map["table"].get(i)
|
||||
|
||||
@property
|
||||
def table_name(self):
|
||||
attr = AttributeCache.get(self.attr_name)
|
||||
i = "index_{0}".format(attr.value_type) if attr.is_index else attr.value_type
|
||||
return type_map["table_name"].get(i)
|
||||
|
||||
|
||||
class ExistPolicy(object):
|
||||
REJECT = "reject"
|
||||
NEED = "need"
|
||||
IGNORE = "ignore"
|
||||
REPLACE = "replace"
|
||||
|
||||
|
||||
class OperateType(object):
|
||||
ADD = "0"
|
||||
DELETE = "1"
|
||||
UPDATE = "2"
|
||||
|
||||
|
||||
class RetKey(object):
|
||||
ID = "id"
|
||||
NAME = "name"
|
||||
ALIAS = "alias"
|
||||
|
||||
|
||||
class ResourceType(object):
|
||||
CI = "CIType"
|
||||
|
||||
|
||||
class PermEnum(object):
|
||||
ADD = "add"
|
||||
UPDATE = "update"
|
||||
DELETE = "delete"
|
||||
READ = "read"
|
||||
|
||||
|
||||
class RoleEnum(object):
|
||||
CONFIG = "admin"
|
||||
|
||||
|
||||
CMDB_QUEUE = "cmdb_async"
|
||||
REDIS_PREFIX = "CMDB_CI"
|
@@ -1,5 +0,0 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
class CommitException(Exception):
|
||||
pass
|
@@ -1,139 +0,0 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
import functools
|
||||
|
||||
import six
|
||||
|
||||
from flask import current_app, g, request
|
||||
from flask import session, abort
|
||||
|
||||
from api.extensions import cache
|
||||
|
||||
|
||||
def get_access_token():
|
||||
return
|
||||
|
||||
|
||||
class AccessTokenCache(object):
|
||||
@classmethod
|
||||
def get(cls):
|
||||
if cache.get("AccessToken") is not None:
|
||||
return cache.get("AccessToken")
|
||||
|
||||
res = get_access_token() or ""
|
||||
|
||||
cache.set("AccessToken", res, timeout=60 * 60)
|
||||
return res
|
||||
|
||||
@classmethod
|
||||
def clean(cls):
|
||||
cache.clear("AccessToken")
|
||||
|
||||
|
||||
class ACLManager(object):
|
||||
def __init__(self):
|
||||
self.access_token = AccessTokenCache.get()
|
||||
self.acl_session = dict(uid=session.get("uid"),
|
||||
token=self.access_token)
|
||||
|
||||
self.user_info = session["acl"] if "acl" in session else {}
|
||||
|
||||
def add_resource(self, name, resource_type_name=None):
|
||||
pass
|
||||
|
||||
def grant_resource_to_role(self, name, role, resource_type_name=None):
|
||||
pass
|
||||
|
||||
def del_resource(self, name, resource_type_name=None):
|
||||
pass
|
||||
|
||||
def get_user_info(self, username):
|
||||
return dict()
|
||||
|
||||
def get_resources(self, resource_type_name=None):
|
||||
if "acl" not in session:
|
||||
abort(405)
|
||||
return []
|
||||
|
||||
def has_permission(self, resource_name, resource_type, perm):
|
||||
if "acl" not in session:
|
||||
abort(405)
|
||||
return True
|
||||
|
||||
|
||||
def validate_permission(resources, resource_type, perm):
|
||||
if not resources:
|
||||
return
|
||||
|
||||
if current_app.config.get("USE_ACL"):
|
||||
if g.user.username == "worker":
|
||||
return
|
||||
|
||||
resources = [resources] if isinstance(resources, six.string_types) else resources
|
||||
for resource in resources:
|
||||
if not ACLManager().has_permission(resource, resource_type, perm):
|
||||
return abort(403, "has no permission")
|
||||
|
||||
|
||||
def can_access_resources(resource_type):
|
||||
def decorator_can_access_resources(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper_can_access_resources(*args, **kwargs):
|
||||
if current_app.config.get("USE_ACL"):
|
||||
res = ACLManager().get_resources(resource_type)
|
||||
result = {i.get("name"): i.get("permissions") for i in res}
|
||||
if hasattr(g, "resources"):
|
||||
g.resources.update({resource_type: result})
|
||||
else:
|
||||
g.resources = {resource_type: result}
|
||||
return func(*args, **kwargs)
|
||||
return wrapper_can_access_resources
|
||||
return decorator_can_access_resources
|
||||
|
||||
|
||||
def has_perm(resources, resource_type, perm):
|
||||
def decorator_has_perm(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper_has_perm(*args, **kwargs):
|
||||
if not resources:
|
||||
return
|
||||
|
||||
if current_app.config.get("USE_ACL"):
|
||||
validate_permission(resources, resource_type, perm)
|
||||
|
||||
return func(*args, **kwargs)
|
||||
return wrapper_has_perm
|
||||
return decorator_has_perm
|
||||
|
||||
|
||||
def has_perm_from_args(arg_name, resource_type, perm, callback=None):
|
||||
def decorator_has_perm(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper_has_perm(*args, **kwargs):
|
||||
if not arg_name:
|
||||
return
|
||||
resource = request.view_args.get(arg_name) or request.values.get(arg_name)
|
||||
if callback is not None and resource:
|
||||
resource = callback(resource)
|
||||
|
||||
if current_app.config.get("USE_ACL") and resource:
|
||||
validate_permission(resource, resource_type, perm)
|
||||
|
||||
return func(*args, **kwargs)
|
||||
return wrapper_has_perm
|
||||
return decorator_has_perm
|
||||
|
||||
|
||||
def role_required(role_name):
|
||||
def decorator_role_required(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper_role_required(*args, **kwargs):
|
||||
if not role_name:
|
||||
return
|
||||
|
||||
if current_app.config.get("USE_ACL"):
|
||||
if role_name not in session.get("acl", {}).get("parentRoles", []):
|
||||
return abort(403, "Role {0} is required".format(role_name))
|
||||
return func(*args, **kwargs)
|
||||
return wrapper_role_required
|
||||
return decorator_role_required
|
@@ -1,91 +0,0 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
from api.extensions import cache
|
||||
from api.models.acl import Role
|
||||
|
||||
|
||||
class RoleCache(object):
|
||||
PREFIX_ID = "Role::id::{0}"
|
||||
PREFIX_NAME = "Role::app_id::{0}::name::{1}"
|
||||
|
||||
@classmethod
|
||||
def get_by_name(cls, app_id, name):
|
||||
role = cache.get(cls.PREFIX_NAME.format(app_id, name))
|
||||
if role is None:
|
||||
role = Role.get_by(app_id=app_id, name=name, first=True, to_dict=False)
|
||||
if role is not None:
|
||||
cache.set(cls.PREFIX_NAME.format(app_id, name), role)
|
||||
|
||||
return role
|
||||
|
||||
@classmethod
|
||||
def get(cls, rid):
|
||||
role = cache.get(cls.PREFIX_ID.format(rid))
|
||||
if role is None:
|
||||
role = Role.get_by_id(rid)
|
||||
if role is not None:
|
||||
cache.set(cls.PREFIX_ID.format(rid), role)
|
||||
|
||||
return role
|
||||
|
||||
@classmethod
|
||||
def clean(cls, rid):
|
||||
cache.delete(cls.PREFIX_ID.format(rid))
|
||||
|
||||
@classmethod
|
||||
def clean_by_name(cls, app_id, name):
|
||||
cache.delete(cls.PREFIX_NAME.format(app_id, name))
|
||||
|
||||
|
||||
class RoleRelationCache(object):
|
||||
PREFIX_PARENT = "RoleRelationParent::id::{0}"
|
||||
PREFIX_CHILDREN = "RoleRelationChildren::id::{0}"
|
||||
PREFIX_RESOURCES = "RoleRelationResources::id::{0}"
|
||||
|
||||
@classmethod
|
||||
def get_parent_ids(cls, rid):
|
||||
parent_ids = cache.get(cls.PREFIX_PARENT.format(rid))
|
||||
if not parent_ids:
|
||||
from api.lib.perm.acl.role import RoleCRUD
|
||||
parent_ids = RoleCRUD.get_parent_ids(rid)
|
||||
cache.set(cls.PREFIX_PARENT.format(rid), parent_ids, timeout=0)
|
||||
|
||||
return parent_ids
|
||||
|
||||
@classmethod
|
||||
def get_child_ids(cls, rid):
|
||||
child_ids = cache.get(cls.PREFIX_CHILDREN.format(rid))
|
||||
if not child_ids:
|
||||
from api.lib.perm.acl.role import RoleCRUD
|
||||
child_ids = RoleCRUD.get_child_ids(rid)
|
||||
cache.set(cls.PREFIX_CHILDREN.format(rid), child_ids, timeout=0)
|
||||
|
||||
return child_ids
|
||||
|
||||
@classmethod
|
||||
def get_resources(cls, rid):
|
||||
"""
|
||||
:param rid:
|
||||
:return: {id2perms: {resource_id: [perm,]}, group2perms: {group_id: [perm, ]}}
|
||||
"""
|
||||
resources = cache.get(cls.PREFIX_RESOURCES.format(rid))
|
||||
if not resources:
|
||||
from api.lib.perm.acl.role import RoleCRUD
|
||||
resources = RoleCRUD.get_resources(rid)
|
||||
cache.set(cls.PREFIX_RESOURCES.format(rid), resources, timeout=0)
|
||||
|
||||
return resources or {}
|
||||
|
||||
@classmethod
|
||||
def rebuild(cls, rid):
|
||||
cls.clean(rid)
|
||||
|
||||
cls.get_parent_ids(rid)
|
||||
cls.get_child_ids(rid)
|
||||
cls.get_resources(rid)
|
||||
|
||||
@classmethod
|
||||
def clean(cls, rid):
|
||||
cache.delete(cls.PREFIX_PARENT.format(rid))
|
||||
cache.delete(cls.PREFIX_CHILDREN.format(rid))
|
||||
cache.delete(cls.PREFIX_RESOURCES.format(rid))
|
@@ -1,4 +0,0 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
ACL_QUEUE = "acl_async"
|
@@ -1,74 +0,0 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
import redis
|
||||
import six
|
||||
from flask import current_app
|
||||
|
||||
|
||||
def get_page(page):
|
||||
try:
|
||||
page = int(page)
|
||||
except ValueError:
|
||||
page = 1
|
||||
return page if page >= 1 else 1
|
||||
|
||||
|
||||
def get_page_size(page_size):
|
||||
if page_size == "all":
|
||||
return page_size
|
||||
|
||||
try:
|
||||
page_size = int(page_size)
|
||||
except (ValueError, TypeError):
|
||||
page_size = current_app.config.get("DEFAULT_PAGE_COUNT")
|
||||
return page_size if page_size >= 1 else current_app.config.get("DEFAULT_PAGE_COUNT")
|
||||
|
||||
|
||||
def handle_arg_list(arg):
|
||||
return list(filter(lambda x: x != "", arg.strip().split(","))) if isinstance(arg, six.string_types) else arg
|
||||
|
||||
|
||||
class RedisHandler(object):
|
||||
def __init__(self, flask_app=None, prefix=None):
|
||||
self.flask_app = flask_app
|
||||
self.prefix = prefix
|
||||
self.r = None
|
||||
|
||||
def init_app(self, app):
|
||||
self.flask_app = app
|
||||
config = self.flask_app.config
|
||||
try:
|
||||
pool = redis.ConnectionPool(
|
||||
max_connections=config.get("REDIS_MAX_CONN"),
|
||||
host=config.get("CACHE_REDIS_HOST"),
|
||||
port=config.get("CACHE_REDIS_PORT"),
|
||||
db=config.get("REDIS_DB"))
|
||||
self.r = redis.Redis(connection_pool=pool)
|
||||
except Exception as e:
|
||||
current_app.logger.warning(str(e))
|
||||
current_app.logger.error("init redis connection failed")
|
||||
|
||||
def get(self, key_ids):
|
||||
try:
|
||||
value = self.r.hmget(self.prefix, key_ids)
|
||||
except Exception as e:
|
||||
current_app.logger.error("get redis error, {0}".format(str(e)))
|
||||
return
|
||||
return value
|
||||
|
||||
def _set(self, obj):
|
||||
try:
|
||||
self.r.hmset(self.prefix, obj)
|
||||
except Exception as e:
|
||||
current_app.logger.error("set redis error, {0}".format(str(e)))
|
||||
|
||||
def add(self, obj):
|
||||
self._set(obj)
|
||||
|
||||
def delete(self, key_id):
|
||||
try:
|
||||
ret = self.r.hdel(self.prefix, key_id)
|
||||
if not ret:
|
||||
current_app.logger.warn("[{0}] is not in redis".format(key_id))
|
||||
except Exception as e:
|
||||
current_app.logger.error("delete redis key error, {0}".format(str(e)))
|
@@ -1,139 +0,0 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
from datetime import datetime
|
||||
|
||||
from flask import current_app
|
||||
from flask_sqlalchemy import BaseQuery
|
||||
|
||||
from api.extensions import cache
|
||||
from api.extensions import db
|
||||
from api.lib.database import CRUDModel
|
||||
|
||||
|
||||
class UserQuery(BaseQuery):
|
||||
def _join(self, *args, **kwargs):
|
||||
super(UserQuery, self)._join(*args, **kwargs)
|
||||
|
||||
def authenticate(self, login, password):
|
||||
user = self.filter(db.or_(User.username == login,
|
||||
User.email == login)).first()
|
||||
if user:
|
||||
current_app.logger.info(user)
|
||||
authenticated = user.check_password(password)
|
||||
else:
|
||||
authenticated = False
|
||||
return user, authenticated
|
||||
|
||||
def authenticate_with_key(self, key, secret, args, path):
|
||||
user = self.filter(User.key == key).filter(User.block == 0).first()
|
||||
if not user:
|
||||
return None, False
|
||||
if user and hashlib.sha1('{0}{1}{2}'.format(
|
||||
path, user.secret, "".join(args)).encode("utf-8")).hexdigest() == secret:
|
||||
authenticated = True
|
||||
else:
|
||||
authenticated = False
|
||||
return user, authenticated
|
||||
|
||||
def search(self, key):
|
||||
query = self.filter(db.or_(User.email == key,
|
||||
User.nickname.ilike('%' + key + '%'),
|
||||
User.username.ilike('%' + key + '%')))
|
||||
return query
|
||||
|
||||
def get_by_username(self, username):
|
||||
user = self.filter(User.username == username).first()
|
||||
return user
|
||||
|
||||
def get_by_nickname(self, nickname):
|
||||
user = self.filter(User.nickname == nickname).first()
|
||||
return user
|
||||
|
||||
def get(self, uid):
|
||||
user = self.filter(User.uid == uid).first()
|
||||
return copy.deepcopy(user)
|
||||
|
||||
|
||||
class User(CRUDModel):
|
||||
__tablename__ = 'users'
|
||||
__bind_key__ = "user"
|
||||
query_class = UserQuery
|
||||
|
||||
uid = db.Column(db.Integer, primary_key=True, autoincrement=True)
|
||||
username = db.Column(db.String(32), unique=True)
|
||||
nickname = db.Column(db.String(20), nullable=True)
|
||||
department = db.Column(db.String(20))
|
||||
catalog = db.Column(db.String(64))
|
||||
email = db.Column(db.String(100), unique=True, nullable=False)
|
||||
mobile = db.Column(db.String(14), unique=True)
|
||||
_password = db.Column("password", db.String(80))
|
||||
key = db.Column(db.String(32), nullable=False)
|
||||
secret = db.Column(db.String(32), nullable=False)
|
||||
date_joined = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
last_login = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
block = db.Column(db.Boolean, default=False)
|
||||
has_logined = db.Column(db.Boolean, default=False)
|
||||
wx_id = db.Column(db.String(32))
|
||||
avatar = db.Column(db.String(128))
|
||||
|
||||
def __str__(self):
|
||||
return self.username
|
||||
|
||||
def is_active(self):
|
||||
return not self.block
|
||||
|
||||
def get_id(self):
|
||||
return self.uid
|
||||
|
||||
@staticmethod
|
||||
def is_authenticated():
|
||||
return True
|
||||
|
||||
def _get_password(self):
|
||||
return self._password
|
||||
|
||||
def _set_password(self, password):
|
||||
self._password = hashlib.md5(password.encode('utf-8')).hexdigest()
|
||||
|
||||
password = db.synonym("_password",
|
||||
descriptor=property(_get_password,
|
||||
_set_password))
|
||||
|
||||
def check_password(self, password):
|
||||
if self.password is None:
|
||||
return False
|
||||
return self.password == password
|
||||
|
||||
|
||||
class UserCache(object):
|
||||
PREFIX_ID = "User::uid::{0}"
|
||||
PREFIX_NAME = "User::username::{0}"
|
||||
PREFIX_NICK = "User::nickname::{0}"
|
||||
|
||||
@classmethod
|
||||
def get(cls, key):
|
||||
user = cache.get(cls.PREFIX_ID.format(key)) or \
|
||||
cache.get(cls.PREFIX_NAME.format(key)) or \
|
||||
cache.get(cls.PREFIX_NICK.format(key))
|
||||
if not user:
|
||||
user = User.query.get(key) or \
|
||||
User.query.get_by_username(key) or \
|
||||
User.query.get_by_nickname(key)
|
||||
if user:
|
||||
cls.set(user)
|
||||
|
||||
return user
|
||||
|
||||
@classmethod
|
||||
def set(cls, user):
|
||||
cache.set(cls.PREFIX_ID.format(user.uid), user)
|
||||
cache.set(cls.PREFIX_NAME.format(user.username), user)
|
||||
cache.set(cls.PREFIX_NICK.format(user.nickname), user)
|
||||
|
||||
@classmethod
|
||||
def clean(cls, user):
|
||||
cache.delete(cls.PREFIX_ID.format(user.uid))
|
||||
cache.delete(cls.PREFIX_NAME.format(user.username))
|
||||
cache.delete(cls.PREFIX_NICK.format(user.nickname))
|
@@ -1,91 +0,0 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
from api.extensions import db
|
||||
from api.lib.database import Model
|
||||
|
||||
|
||||
class App(Model):
|
||||
__tablename__ = "acl_apps"
|
||||
|
||||
name = db.Column(db.String(64), index=True)
|
||||
description = db.Column(db.Text)
|
||||
app_id = db.Column(db.Text)
|
||||
secret_key = db.Column(db.Text)
|
||||
|
||||
|
||||
class Role(Model):
|
||||
__tablename__ = "acl_roles"
|
||||
|
||||
name = db.Column(db.Text, nullable=False)
|
||||
is_app_admin = db.Column(db.Boolean, default=False)
|
||||
app_id = db.Column(db.Integer, db.ForeignKey("acl_apps.id"))
|
||||
uid = db.Column(db.Integer, db.ForeignKey("users.uid"))
|
||||
|
||||
|
||||
class RoleRelation(Model):
|
||||
__tablename__ = "acl_role_relations"
|
||||
|
||||
parent_id = db.Column(db.Integer, db.ForeignKey('acl_roles.id'))
|
||||
child_id = db.Column(db.Integer, db.ForeignKey('acl_roles.id'))
|
||||
|
||||
__table_args__ = (
|
||||
db.UniqueConstraint("parent_id", "child_id", name="role_relation_unique"),)
|
||||
|
||||
|
||||
class ResourceType(Model):
|
||||
__tablename__ = "acl_resource_types"
|
||||
|
||||
name = db.Column(db.String(64), index=True)
|
||||
description = db.Column(db.Text)
|
||||
app_id = db.Column(db.Integer, db.ForeignKey('acl_apps.id'))
|
||||
|
||||
|
||||
class ResourceGroup(Model):
|
||||
__tablename__ = "acl_resource_groups"
|
||||
|
||||
name = db.Column(db.String(64), index=True, nullable=False)
|
||||
resource_type_id = db.Column(db.Integer, db.ForeignKey("acl_resource_types.id"))
|
||||
|
||||
app_id = db.Column(db.Integer, db.ForeignKey('acl_apps.id'))
|
||||
|
||||
__table_args__ = (db.UniqueConstraint("name", "resource_type_id", "app_id", name="resource_group_app_unique"),)
|
||||
|
||||
|
||||
class Resource(Model):
|
||||
__tablename__ = "acl_resources"
|
||||
|
||||
name = db.Column(db.String(128), nullable=False)
|
||||
resource_type_id = db.Column(db.Integer, db.ForeignKey("acl_resource_types.id"))
|
||||
|
||||
app_id = db.Column(db.Integer, db.ForeignKey("acl_apps.id"))
|
||||
|
||||
__table_args__ = (db.UniqueConstraint("name", "resource_type_id", "app_id", name="resource_name_app_unique"),)
|
||||
|
||||
|
||||
class ResourceGroupItems(Model):
|
||||
__tablename__ = "acl_resource_group_items"
|
||||
|
||||
group_id = db.Column(db.Integer, db.ForeignKey('acl_resource_groups.id'), nullable=False)
|
||||
resource_id = db.Column(db.Integer, db.ForeignKey('acl_resources.id'), nullable=False)
|
||||
|
||||
|
||||
class Permission(Model):
|
||||
__tablename__ = "acl_permissions"
|
||||
|
||||
name = db.Column(db.String(64), nullable=False)
|
||||
resource_type_id = db.Column(db.Integer, db.ForeignKey("acl_resource_types.id"))
|
||||
|
||||
app_id = db.Column(db.Integer, db.ForeignKey("acl_apps.id"))
|
||||
|
||||
__table_args__ = (db.UniqueConstraint("name", "resource_type_id", "app_id", name="perm_name_app_unique"),)
|
||||
|
||||
|
||||
class RolePermission(Model):
|
||||
__tablename__ = "acl_role_permissions"
|
||||
|
||||
rid = db.Column(db.Integer, db.ForeignKey('acl_roles.id'))
|
||||
resource_id = db.Column(db.Integer, db.ForeignKey('acl_resources.id'))
|
||||
group_id = db.Column(db.Integer, db.ForeignKey('acl_resource_groups.id'))
|
||||
perm_id = db.Column(db.Integer, db.ForeignKey('acl_permissions.id'))
|
||||
|
||||
perm = db.relationship("Permission", backref='acl_role_permissions.perm_id')
|
@@ -1,33 +0,0 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
import json
|
||||
import time
|
||||
|
||||
from flask import current_app
|
||||
|
||||
import api.lib.cmdb.ci
|
||||
from api.extensions import celery
|
||||
from api.extensions import db
|
||||
from api.extensions import rd
|
||||
from api.lib.cmdb.const import CMDB_QUEUE
|
||||
|
||||
|
||||
@celery.task(name="cmdb.ci_cache", queue=CMDB_QUEUE)
|
||||
def ci_cache(ci_id):
|
||||
time.sleep(0.1)
|
||||
db.session.close()
|
||||
|
||||
m = api.lib.cmdb.ci.CIManager()
|
||||
ci = m.get_ci_by_id_from_db(ci_id, need_children=False, use_master=False)
|
||||
rd.delete(ci_id)
|
||||
rd.add({ci_id: json.dumps(ci)})
|
||||
|
||||
current_app.logger.info("%d caching.........." % ci_id)
|
||||
|
||||
|
||||
@celery.task(name="cmdb.ci_delete", queue=CMDB_QUEUE)
|
||||
def ci_delete(ci_id):
|
||||
current_app.logger.info(ci_id)
|
||||
rd.delete(ci_id)
|
||||
current_app.logger.info("%d delete.........." % ci_id)
|
@@ -1,66 +0,0 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
from flask import request
|
||||
|
||||
from api.lib.cmdb.ci import CIRelationManager
|
||||
from api.lib.utils import get_page
|
||||
from api.lib.utils import get_page_size
|
||||
from api.resource import APIView
|
||||
|
||||
|
||||
class GetSecondCIsView(APIView):
|
||||
url_prefix = "/ci_relations/<int:first_ci_id>/second_cis"
|
||||
|
||||
def get(self, first_ci_id):
|
||||
page = get_page(request.values.get("page", 1))
|
||||
count = get_page_size(request.values.get("count"))
|
||||
relation_type = request.values.get("relation_type", "contain")
|
||||
|
||||
manager = CIRelationManager()
|
||||
numfound, total, second_cis = manager.get_second_cis(
|
||||
first_ci_id, page=page, per_page=count, relation_type=relation_type)
|
||||
|
||||
return self.jsonify(numfound=numfound,
|
||||
total=total,
|
||||
page=page,
|
||||
second_cis=second_cis)
|
||||
|
||||
|
||||
class GetFirstCIsView(APIView):
|
||||
url_prefix = "/ci_relations/<int:second_ci_id>/first_cis"
|
||||
|
||||
def get(self, second_ci_id):
|
||||
page = get_page(request.values.get("page", 1))
|
||||
count = get_page_size(request.values.get("count"))
|
||||
|
||||
manager = CIRelationManager()
|
||||
numfound, total, first_cis = manager.get_first_cis(second_ci_id, per_page=count, page=page)
|
||||
|
||||
return self.jsonify(numfound=numfound,
|
||||
total=total,
|
||||
page=page,
|
||||
first_cis=first_cis)
|
||||
|
||||
|
||||
class CIRelationView(APIView):
|
||||
url_prefix = "/ci_relations/<int:first_ci_id>/<int:second_ci_id>"
|
||||
|
||||
def post(self, first_ci_id, second_ci_id):
|
||||
manager = CIRelationManager()
|
||||
res = manager.add(first_ci_id, second_ci_id)
|
||||
return self.jsonify(cr_id=res)
|
||||
|
||||
def delete(self, first_ci_id, second_ci_id):
|
||||
manager = CIRelationManager()
|
||||
manager.delete_2(first_ci_id, second_ci_id)
|
||||
return self.jsonify(message="CIType Relation is deleted")
|
||||
|
||||
|
||||
class DeleteCIRelationView(APIView):
|
||||
url_prefix = "/ci_relations/<int:cr_id>"
|
||||
|
||||
def delete(self, cr_id):
|
||||
manager = CIRelationManager()
|
||||
manager.delete(cr_id)
|
||||
return self.jsonify(message="CIType Relation is deleted")
|
@@ -1,49 +0,0 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
from flask import request
|
||||
from flask import session
|
||||
from flask_login import current_user
|
||||
|
||||
from api.lib.decorator import args_required
|
||||
from api.lib.perm.acl.acl import ACLManager
|
||||
from api.lib.perm.acl.acl import validate_permission
|
||||
from api.resource import APIView
|
||||
|
||||
|
||||
class HasPermissionView(APIView):
|
||||
url_prefix = "/validate"
|
||||
|
||||
@args_required("resource")
|
||||
@args_required("resource_type")
|
||||
@args_required("perm")
|
||||
def get(self):
|
||||
resource = request.values.get("resource")
|
||||
resource_type = request.values.get("resource_type")
|
||||
perm = request.values.get("perm")
|
||||
validate_permission(resource, resource_type, perm)
|
||||
return self.jsonify(is_valid=True)
|
||||
|
||||
def post(self):
|
||||
self.get()
|
||||
|
||||
|
||||
class GetResourcesView(APIView):
|
||||
url_prefix = "/resources"
|
||||
|
||||
@args_required("resource_type")
|
||||
def get(self):
|
||||
resource_type = request.values.get("resource_type")
|
||||
res = ACLManager().get_resources(resource_type)
|
||||
return self.jsonify(res)
|
||||
|
||||
|
||||
class GetUserInfoView(APIView):
|
||||
url_prefix = "/user/info"
|
||||
|
||||
def get(self):
|
||||
name = session.get("acl", {}).get("nickName") or session.get("CAS_USERNAME") or current_user.nickname
|
||||
role = dict(permissions=session.get("acl", {}).get("parentRoles", []) or ["admin"])
|
||||
avatar = session.get("acl", {}).get("avatar") or current_user.avatar
|
||||
return self.jsonify(result=dict(name=name,
|
||||
role=role,
|
||||
avatar=avatar))
|
@@ -2,6 +2,6 @@
|
||||
FLASK_APP=autoapp.py
|
||||
FLASK_DEBUG=1
|
||||
FLASK_ENV=development
|
||||
GUNICORN_WORKERS=1
|
||||
GUNICORN_WORKERS=2
|
||||
LOG_LEVEL=debug
|
||||
SECRET_KEY='YourSecretKey'
|
||||
SECRET_KEY='<YourSecretKey>'
|
16
cmdb-api/Makefile
Normal file
16
cmdb-api/Makefile
Normal file
@@ -0,0 +1,16 @@
|
||||
default: help
|
||||
|
||||
test: ## test in local environment
|
||||
pytest -s --html=test-output/test/index.html --cov-report html:test-output/coverage --cov=api tests
|
||||
|
||||
clean_test: ## clean test output
|
||||
rm -f .coverage
|
||||
rm -rf .pytest_cache
|
||||
rm -rf test-output
|
||||
|
||||
|
||||
docker_test: ## test all case in docker container
|
||||
@echo "TODO"
|
||||
|
||||
help:
|
||||
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' ./Makefile | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
|
@@ -6,7 +6,7 @@ name = "pypi"
|
||||
[packages]
|
||||
# Flask
|
||||
Flask = "==1.0.3"
|
||||
Werkzeug = "==0.15.4"
|
||||
Werkzeug = ">=0.15.5"
|
||||
click = ">=5.0"
|
||||
# Api
|
||||
Flask-RESTful = "==0.3.7"
|
||||
@@ -25,6 +25,7 @@ supervisor = "==4.0.3"
|
||||
Flask-Login = "==0.4.1"
|
||||
Flask-Bcrypt = "==0.7.1"
|
||||
Flask-Cors = ">=3.0.8"
|
||||
python-ldap = "==3.2.0"
|
||||
# Caching
|
||||
Flask-Caching = ">=1.0.0"
|
||||
# Environment variable parsing
|
||||
@@ -40,6 +41,8 @@ bs4 = ">=0.0.1"
|
||||
toposort = ">=1.5"
|
||||
requests = ">=2.22.0"
|
||||
PyJWT = ">=1.7.1"
|
||||
elasticsearch = "==7.0.4"
|
||||
future = "==0.18.2"
|
||||
|
||||
[dev-packages]
|
||||
# Testing
|
@@ -6,6 +6,7 @@ import sys
|
||||
from inspect import getmembers
|
||||
from logging.handlers import RotatingFileHandler
|
||||
|
||||
from api.flask_cas import CAS
|
||||
from flask import Flask
|
||||
from flask import make_response, jsonify
|
||||
from flask.blueprints import Blueprint
|
||||
@@ -21,9 +22,9 @@ from api.extensions import (
|
||||
migrate,
|
||||
celery,
|
||||
rd,
|
||||
es
|
||||
)
|
||||
from api.flask_cas import CAS
|
||||
from api.models.account import User
|
||||
from .models.acl import User
|
||||
|
||||
HERE = os.path.abspath(os.path.dirname(__file__))
|
||||
PROJECT_ROOT = os.path.join(HERE, os.pardir)
|
||||
@@ -33,7 +34,7 @@ API_PACKAGE = "api"
|
||||
@login_manager.user_loader
|
||||
def load_user(user_id):
|
||||
"""Load user by ID."""
|
||||
return User.get_by_id(int(user_id))
|
||||
return User.get_by(uid=int(user_id), first=True, to_dict=False)
|
||||
|
||||
|
||||
class ReverseProxy(object):
|
||||
@@ -71,7 +72,7 @@ class ReverseProxy(object):
|
||||
return self.app(environ, start_response)
|
||||
|
||||
|
||||
def create_app(config_object="{0}.settings".format(API_PACKAGE)):
|
||||
def create_app(config_object="settings"):
|
||||
"""Create application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.
|
||||
|
||||
:param config_object: The configuration object to use.
|
||||
@@ -98,6 +99,8 @@ def register_extensions(app):
|
||||
login_manager.init_app(app)
|
||||
migrate.init_app(app, db)
|
||||
rd.init_app(app)
|
||||
if app.config.get("USE_ES"):
|
||||
es.init_app(app)
|
||||
celery.conf.update(app.config)
|
||||
|
||||
|
137
cmdb-api/api/commands/click_cmdb.py
Normal file
137
cmdb-api/api/commands/click_cmdb.py
Normal file
@@ -0,0 +1,137 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
import json
|
||||
|
||||
import click
|
||||
from flask import current_app
|
||||
from flask.cli import with_appcontext
|
||||
|
||||
import api.lib.cmdb.ci
|
||||
from api.extensions import db
|
||||
from api.extensions import rd
|
||||
from api.lib.cmdb.const import PermEnum
|
||||
from api.lib.cmdb.const import REDIS_PREFIX_CI
|
||||
from api.lib.cmdb.const import REDIS_PREFIX_CI_RELATION
|
||||
from api.lib.cmdb.const import ResourceTypeEnum
|
||||
from api.lib.cmdb.const import RoleEnum
|
||||
from api.lib.cmdb.const import ValueTypeEnum
|
||||
from api.lib.exception import AbortException
|
||||
from api.lib.perm.acl.acl import ACLManager
|
||||
from api.lib.perm.acl.cache import AppCache
|
||||
from api.lib.perm.acl.resource import ResourceCRUD
|
||||
from api.lib.perm.acl.resource import ResourceTypeCRUD
|
||||
from api.lib.perm.acl.role import RoleCRUD
|
||||
from api.models.acl import ResourceType
|
||||
from api.models.cmdb import CI
|
||||
from api.models.cmdb import CIRelation
|
||||
from api.models.cmdb import CIType
|
||||
from api.models.cmdb import PreferenceRelationView
|
||||
|
||||
|
||||
@click.command()
|
||||
@with_appcontext
|
||||
def init_cache():
|
||||
db.session.remove()
|
||||
|
||||
if current_app.config.get("USE_ES"):
|
||||
from api.extensions import es
|
||||
from api.models.cmdb import Attribute
|
||||
from api.lib.cmdb.utils import ValueTypeMap
|
||||
attributes = Attribute.get_by(to_dict=False)
|
||||
for attr in attributes:
|
||||
other = dict()
|
||||
other['index'] = True if attr.is_index else False
|
||||
if attr.value_type == ValueTypeEnum.TEXT:
|
||||
other['analyzer'] = 'ik_max_word'
|
||||
other['search_analyzer'] = 'ik_smart'
|
||||
if attr.is_index:
|
||||
other["fields"] = {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
try:
|
||||
es.update_mapping(attr.name, ValueTypeMap.es_type[attr.value_type], other)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
cis = CI.get_by(to_dict=False)
|
||||
for ci in cis:
|
||||
if current_app.config.get("USE_ES"):
|
||||
res = es.get_index_id(ci.id)
|
||||
if res:
|
||||
continue
|
||||
else:
|
||||
res = rd.get([ci.id], REDIS_PREFIX_CI)
|
||||
if res and list(filter(lambda x: x, res)):
|
||||
continue
|
||||
|
||||
m = api.lib.cmdb.ci.CIManager()
|
||||
ci_dict = m.get_ci_by_id_from_db(ci.id, need_children=False, use_master=False)
|
||||
|
||||
if current_app.config.get("USE_ES"):
|
||||
es.create(ci_dict)
|
||||
else:
|
||||
rd.create_or_update({ci.id: json.dumps(ci_dict)}, REDIS_PREFIX_CI)
|
||||
|
||||
ci_relations = CIRelation.get_by(to_dict=False)
|
||||
relations = dict()
|
||||
for cr in ci_relations:
|
||||
relations.setdefault(cr.first_ci_id, {}).update({cr.second_ci_id: cr.second_ci.type_id})
|
||||
for i in relations:
|
||||
relations[i] = json.dumps(relations[i])
|
||||
if relations:
|
||||
rd.create_or_update(relations, REDIS_PREFIX_CI_RELATION)
|
||||
|
||||
db.session.remove()
|
||||
|
||||
|
||||
@click.command()
|
||||
@with_appcontext
|
||||
def init_acl():
|
||||
app_id = AppCache.get('cmdb').id
|
||||
# 1. add resource type
|
||||
for resource_type in ResourceTypeEnum.all():
|
||||
try:
|
||||
ResourceTypeCRUD.add(app_id, resource_type, '', PermEnum.all())
|
||||
except AbortException:
|
||||
pass
|
||||
|
||||
# 2. add role
|
||||
try:
|
||||
RoleCRUD.add_role(RoleEnum.CONFIG, app_id, True)
|
||||
except AbortException:
|
||||
pass
|
||||
try:
|
||||
RoleCRUD.add_role(RoleEnum.CMDB_READ_ALL, app_id, False)
|
||||
except AbortException:
|
||||
pass
|
||||
|
||||
# 3. add resource and grant
|
||||
ci_types = CIType.get_by(to_dict=False)
|
||||
type_id = ResourceType.get_by(name=ResourceTypeEnum.CI, first=True, to_dict=False).id
|
||||
for ci_type in ci_types:
|
||||
try:
|
||||
ResourceCRUD.add(ci_type.name, type_id, app_id)
|
||||
except AbortException:
|
||||
pass
|
||||
|
||||
ACLManager().grant_resource_to_role(ci_type.name,
|
||||
RoleEnum.CMDB_READ_ALL,
|
||||
ResourceTypeEnum.CI,
|
||||
[PermEnum.READ])
|
||||
|
||||
relation_views = PreferenceRelationView.get_by(to_dict=False)
|
||||
type_id = ResourceType.get_by(name=ResourceTypeEnum.RELATION_VIEW, first=True, to_dict=False).id
|
||||
for view in relation_views:
|
||||
try:
|
||||
ResourceCRUD.add(view.name, type_id, app_id)
|
||||
except AbortException:
|
||||
pass
|
||||
|
||||
ACLManager().grant_resource_to_role(view.name,
|
||||
RoleEnum.CMDB_READ_ALL,
|
||||
ResourceTypeEnum.RELATION_VIEW,
|
||||
[PermEnum.READ])
|
@@ -9,6 +9,7 @@ from flask_login import LoginManager
|
||||
from flask_migrate import Migrate
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
|
||||
from api.lib.utils import ESHandler
|
||||
from api.lib.utils import RedisHandler
|
||||
|
||||
bcrypt = Bcrypt()
|
||||
@@ -18,4 +19,5 @@ migrate = Migrate()
|
||||
cache = Cache()
|
||||
celery = Celery()
|
||||
cors = CORS(supports_credentials=True)
|
||||
rd = RedisHandler(prefix="CMDB_CI") # TODO
|
||||
rd = RedisHandler()
|
||||
es = ESHandler()
|
@@ -8,7 +8,7 @@ from flask import current_app, session, request, url_for, redirect
|
||||
from flask_login import login_user, logout_user
|
||||
from six.moves.urllib_request import urlopen
|
||||
|
||||
from api.models.account import UserCache
|
||||
from api.lib.perm.acl.cache import UserCache
|
||||
from .cas_urls import create_cas_login_url
|
||||
from .cas_urls import create_cas_logout_url
|
||||
from .cas_urls import create_cas_validate_url
|
@@ -5,10 +5,12 @@ from flask import current_app
|
||||
|
||||
from api.extensions import db
|
||||
from api.lib.cmdb.cache import AttributeCache
|
||||
from api.lib.cmdb.const import type_map
|
||||
from api.lib.cmdb.const import ValueTypeEnum
|
||||
from api.lib.cmdb.utils import ValueTypeMap
|
||||
from api.lib.decorator import kwargs_required
|
||||
from api.models.cmdb import Attribute
|
||||
from api.models.cmdb import CITypeAttribute
|
||||
from api.models.cmdb import CITypeAttributeGroupItem
|
||||
from api.models.cmdb import PreferenceShowAttributes
|
||||
|
||||
|
||||
@@ -22,13 +24,13 @@ class AttributeManager(object):
|
||||
|
||||
@staticmethod
|
||||
def get_choice_values(attr_id, value_type):
|
||||
choice_table = type_map.get("choice").get(value_type)
|
||||
choice_table = ValueTypeMap.choice.get(value_type)
|
||||
choice_values = choice_table.get_by(fl=["value"], attr_id=attr_id)
|
||||
return [choice_value["value"] for choice_value in choice_values]
|
||||
|
||||
@staticmethod
|
||||
def _add_choice_values(_id, value_type, choice_values):
|
||||
choice_table = type_map.get("choice").get(value_type)
|
||||
choice_table = ValueTypeMap.choice.get(value_type)
|
||||
|
||||
db.session.query(choice_table).filter(choice_table.attr_id == _id).delete()
|
||||
db.session.flush()
|
||||
@@ -38,6 +40,13 @@ class AttributeManager(object):
|
||||
db.session.add(table)
|
||||
db.session.flush()
|
||||
|
||||
@staticmethod
|
||||
def _del_choice_values(_id, value_type):
|
||||
choice_table = ValueTypeMap.choice.get(value_type)
|
||||
|
||||
db.session.query(choice_table).filter(choice_table.attr_id == _id).delete()
|
||||
db.session.flush()
|
||||
|
||||
@classmethod
|
||||
def search_attributes(cls, name=None, alias=None, page=1, page_size=None):
|
||||
"""
|
||||
@@ -96,9 +105,8 @@ class AttributeManager(object):
|
||||
name = kwargs.pop("name")
|
||||
alias = kwargs.pop("alias", "")
|
||||
alias = name if not alias else alias
|
||||
Attribute.get_by(name=name, first=True) and abort(400, "attribute name <{0}> is already existed".format(name))
|
||||
Attribute.get_by(alias=alias, first=True) and abort(400,
|
||||
"attribute alias <{0}> is already existed".format(name))
|
||||
Attribute.get_by(name=name, first=True) and abort(400, "attribute name <{0}> is duplicated".format(name))
|
||||
Attribute.get_by(alias=alias, first=True) and abort(400, "attribute alias <{0}> is duplicated".format(name))
|
||||
|
||||
attr = Attribute.create(flush=True,
|
||||
name=name,
|
||||
@@ -118,6 +126,22 @@ class AttributeManager(object):
|
||||
|
||||
AttributeCache.clean(attr)
|
||||
|
||||
if current_app.config.get("USE_ES"):
|
||||
from api.extensions import es
|
||||
other = dict()
|
||||
other['index'] = True if attr.is_index else False
|
||||
if attr.value_type == ValueTypeEnum.TEXT:
|
||||
other['analyzer'] = 'ik_max_word'
|
||||
other['search_analyzer'] = 'ik_smart'
|
||||
if attr.is_index:
|
||||
other["fields"] = {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
es.update_mapping(name, ValueTypeMap.es_type[attr.value_type], other)
|
||||
|
||||
return attr.id
|
||||
|
||||
def update(self, _id, **kwargs):
|
||||
@@ -134,11 +158,14 @@ class AttributeManager(object):
|
||||
|
||||
choice_value = kwargs.pop("choice_value", False)
|
||||
is_choice = True if choice_value else False
|
||||
kwargs['is_choice'] = is_choice
|
||||
|
||||
attr.update(flush=True, **kwargs)
|
||||
|
||||
if is_choice:
|
||||
self._add_choice_values(attr.id, attr.value_type, choice_value)
|
||||
else:
|
||||
self._del_choice_values(attr.id, attr.value_type)
|
||||
|
||||
try:
|
||||
db.session.commit()
|
||||
@@ -157,7 +184,7 @@ class AttributeManager(object):
|
||||
name = attr.name
|
||||
|
||||
if attr.is_choice:
|
||||
choice_table = type_map["choice"].get(attr.value_type)
|
||||
choice_table = ValueTypeMap.choice.get(attr.value_type)
|
||||
db.session.query(choice_table).filter(choice_table.attr_id == _id).delete() # FIXME: session conflict
|
||||
db.session.flush()
|
||||
|
||||
@@ -171,4 +198,7 @@ class AttributeManager(object):
|
||||
for i in PreferenceShowAttributes.get_by(attr_id=_id, to_dict=False):
|
||||
i.soft_delete()
|
||||
|
||||
for i in CITypeAttributeGroupItem.get_by(attr_id=_id, to_dict=False):
|
||||
i.soft_delete()
|
||||
|
||||
return name
|
@@ -107,13 +107,13 @@ class RelationTypeCache(object):
|
||||
cache.delete(cls.PREFIX_ID.format(ct.id))
|
||||
|
||||
|
||||
class CITypeAttributeCache(object):
|
||||
class CITypeAttributesCache(object):
|
||||
"""
|
||||
key is type_id or type_name
|
||||
"""
|
||||
|
||||
PREFIX_ID = "CITypeAttribute::ID::{0}"
|
||||
PREFIX_NAME = "CITypeAttribute::Name::{0}"
|
||||
PREFIX_ID = "CITypeAttributes::TypeID::{0}"
|
||||
PREFIX_NAME = "CITypeAttributes::TypeName::{0}"
|
||||
|
||||
@classmethod
|
||||
def get(cls, key):
|
||||
@@ -146,3 +146,30 @@ class CITypeAttributeCache(object):
|
||||
if attrs is not None and ci_type:
|
||||
cache.delete(cls.PREFIX_ID.format(ci_type.id))
|
||||
cache.delete(cls.PREFIX_NAME.format(ci_type.name))
|
||||
|
||||
|
||||
class CITypeAttributeCache(object):
|
||||
"""
|
||||
key is type_id & attr_id
|
||||
"""
|
||||
|
||||
PREFIX_ID = "CITypeAttribute::TypeID::{0}::AttrID::{1}"
|
||||
|
||||
@classmethod
|
||||
def get(cls, type_id, attr_id):
|
||||
|
||||
attr = cache.get(cls.PREFIX_ID.format(type_id, attr_id))
|
||||
attr = attr or cache.get(cls.PREFIX_ID.format(type_id, attr_id))
|
||||
if not attr:
|
||||
attr = CITypeAttribute.get_by(type_id=type_id, attr_id=attr_id, first=True, to_dict=False)
|
||||
if attr is not None:
|
||||
cls.set(type_id, attr_id, attr)
|
||||
return attr
|
||||
|
||||
@classmethod
|
||||
def set(cls, type_id, attr_id, attr):
|
||||
cache.set(cls.PREFIX_ID.format(type_id, attr_id), attr)
|
||||
|
||||
@classmethod
|
||||
def clean(cls, type_id, attr_id):
|
||||
cache.delete(cls.PREFIX_ID.format(type_id, attr_id))
|
@@ -12,27 +12,30 @@ from api.extensions import db
|
||||
from api.extensions import rd
|
||||
from api.lib.cmdb.cache import AttributeCache
|
||||
from api.lib.cmdb.cache import CITypeCache
|
||||
from api.lib.cmdb.cache import RelationTypeCache
|
||||
from api.lib.cmdb.ci_type import CITypeAttributeManager
|
||||
from api.lib.cmdb.ci_type import CITypeManager
|
||||
from api.lib.cmdb.const import CMDB_QUEUE
|
||||
from api.lib.cmdb.const import ExistPolicy
|
||||
from api.lib.cmdb.const import OperateType
|
||||
from api.lib.cmdb.const import REDIS_PREFIX_CI
|
||||
from api.lib.cmdb.const import RetKey
|
||||
from api.lib.cmdb.const import TableMap
|
||||
from api.lib.cmdb.const import type_map
|
||||
from api.lib.cmdb.history import AttributeHistoryManger
|
||||
from api.lib.cmdb.history import CIRelationHistoryManager
|
||||
from api.lib.cmdb.query_sql import QUERY_CIS_BY_IDS
|
||||
from api.lib.cmdb.query_sql import QUERY_CIS_BY_VALUE_TABLE
|
||||
from api.lib.cmdb.search.ci.db.query_sql import QUERY_CIS_BY_IDS
|
||||
from api.lib.cmdb.search.ci.db.query_sql import QUERY_CIS_BY_VALUE_TABLE
|
||||
from api.lib.cmdb.utils import TableMap
|
||||
from api.lib.cmdb.utils import ValueTypeMap
|
||||
from api.lib.cmdb.value import AttributeValueManager
|
||||
from api.lib.decorator import kwargs_required
|
||||
from api.lib.utils import handle_arg_list
|
||||
from api.models.cmdb import CI
|
||||
from api.models.cmdb import CIRelation
|
||||
from api.models.cmdb import CITypeAttribute
|
||||
from api.models.cmdb import CITypeRelation
|
||||
from api.tasks.cmdb import ci_cache
|
||||
from api.tasks.cmdb import ci_delete
|
||||
from api.tasks.cmdb import ci_relation_cache
|
||||
from api.tasks.cmdb import ci_relation_delete
|
||||
|
||||
|
||||
class CIManager(object):
|
||||
@@ -49,7 +52,7 @@ class CIManager(object):
|
||||
|
||||
@staticmethod
|
||||
def confirm_ci_existed(ci_id):
|
||||
CI.get_by_id(ci_id) or abort(404, "CI <{0}> is not existed".format(ci_id))
|
||||
return CI.get_by_id(ci_id) or abort(404, "CI <{0}> is not existed".format(ci_id))
|
||||
|
||||
@classmethod
|
||||
def get_ci_by_id(cls, ci_id, ret_key=RetKey.NAME, fields=None, need_children=True):
|
||||
@@ -112,8 +115,8 @@ class CIManager(object):
|
||||
use_master=use_master)
|
||||
res.update(_res)
|
||||
|
||||
res['_type'] = ci_type.id
|
||||
res['_id'] = ci_id
|
||||
res['type_id'] = ci_type.id
|
||||
res['ci_id'] = ci_id
|
||||
|
||||
return res
|
||||
|
||||
@@ -187,7 +190,7 @@ class CIManager(object):
|
||||
value_manager = AttributeValueManager()
|
||||
for p, v in ci_dict.items():
|
||||
try:
|
||||
value_manager.create_or_update_attr_value(p, v, ci.id, _no_attribute_policy)
|
||||
value_manager.create_or_update_attr_value(p, v, ci, _no_attribute_policy)
|
||||
except BadRequest as e:
|
||||
if existed is None:
|
||||
cls.delete(ci.id)
|
||||
@@ -198,11 +201,12 @@ class CIManager(object):
|
||||
return ci.id
|
||||
|
||||
def update(self, ci_id, **ci_dict):
|
||||
self.confirm_ci_existed(ci_id)
|
||||
ci = self.confirm_ci_existed(ci_id)
|
||||
|
||||
value_manager = AttributeValueManager()
|
||||
for p, v in ci_dict.items():
|
||||
try:
|
||||
value_manager.create_or_update_attr_value(p, v, ci_id)
|
||||
value_manager.create_or_update_attr_value(p, v, ci)
|
||||
except BadRequest as e:
|
||||
raise e
|
||||
|
||||
@@ -210,9 +214,9 @@ class CIManager(object):
|
||||
|
||||
@staticmethod
|
||||
def update_unique_value(ci_id, unique_name, unique_value):
|
||||
CI.get_by_id(ci_id) or abort(404, "CI <{0}> is not found".format(ci_id))
|
||||
ci = CI.get_by_id(ci_id) or abort(404, "CI <{0}> is not found".format(ci_id))
|
||||
|
||||
AttributeValueManager().create_or_update_attr_value(unique_name, unique_value, ci_id)
|
||||
AttributeValueManager().create_or_update_attr_value(unique_name, unique_value, ci)
|
||||
|
||||
ci_cache.apply_async([ci_id], queue=CMDB_QUEUE)
|
||||
|
||||
@@ -228,9 +232,11 @@ class CIManager(object):
|
||||
item.delete()
|
||||
|
||||
for item in CIRelation.get_by(first_ci_id=ci_id, to_dict=False):
|
||||
ci_relation_delete.apply_async(args=(item.first_ci_id, item.second_ci_id), queue=CMDB_QUEUE)
|
||||
item.delete()
|
||||
|
||||
for item in CIRelation.get_by(second_ci_id=ci_id, to_dict=False):
|
||||
ci_relation_delete.apply_async(args=(item.first_ci_id, item.second_ci_id), queue=CMDB_QUEUE)
|
||||
item.delete()
|
||||
|
||||
ci.delete() # TODO: soft delete
|
||||
@@ -302,7 +308,7 @@ class CIManager(object):
|
||||
|
||||
@staticmethod
|
||||
def _get_cis_from_cache(ci_ids, ret_key=RetKey.NAME, fields=None):
|
||||
res = rd.get(ci_ids)
|
||||
res = rd.get(ci_ids, REDIS_PREFIX_CI)
|
||||
if res is not None and None not in res and ret_key == RetKey.NAME:
|
||||
res = list(map(json.loads, res))
|
||||
if not fields:
|
||||
@@ -332,7 +338,7 @@ class CIManager(object):
|
||||
|
||||
ci_ids = ",".join(ci_ids)
|
||||
if value_tables is None:
|
||||
value_tables = type_map["table_name"].values()
|
||||
value_tables = ValueTypeMap.table_name.values()
|
||||
|
||||
value_sql = " UNION ".join([QUERY_CIS_BY_VALUE_TABLE.format(value_table, ci_ids)
|
||||
for value_table in value_tables])
|
||||
@@ -346,8 +352,8 @@ class CIManager(object):
|
||||
if ci_id not in ci_set:
|
||||
ci_dict = dict()
|
||||
ci_type = CITypeCache.get(type_id)
|
||||
ci_dict["_id"] = ci_id
|
||||
ci_dict["_type"] = type_id
|
||||
ci_dict["ci_id"] = ci_id
|
||||
ci_dict["ci_type"] = type_id
|
||||
ci_dict["ci_type"] = ci_type.name
|
||||
ci_dict["ci_type_alias"] = ci_type.alias
|
||||
ci_set.add(ci_id)
|
||||
@@ -362,7 +368,7 @@ class CIManager(object):
|
||||
else:
|
||||
return abort(400, "invalid ret key")
|
||||
|
||||
value = type_map["serialize2"][value_type](value)
|
||||
value = ValueTypeMap.serialize2[value_type](value)
|
||||
if is_list:
|
||||
ci_dict.setdefault(attr_key, []).append(value)
|
||||
else:
|
||||
@@ -403,10 +409,6 @@ class CIRelationManager(object):
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def _get_default_relation_type():
|
||||
return RelationTypeCache.get("contain").id # FIXME
|
||||
|
||||
@classmethod
|
||||
def get_children(cls, ci_id, ret_key=RetKey.NAME):
|
||||
second_cis = CIRelation.get_by(first_ci_id=ci_id, to_dict=False)
|
||||
@@ -423,17 +425,15 @@ class CIRelationManager(object):
|
||||
res[ci_type.name] = children
|
||||
return res
|
||||
|
||||
def get_second_cis(self, first_ci_id, relation_type_id=None, page=1, per_page=None, **kwargs):
|
||||
@staticmethod
|
||||
def get_second_cis(first_ci_id, relation_type_id=None, page=1, per_page=None):
|
||||
second_cis = db.session.query(CI.id).filter(CI.deleted.is_(False)).join(
|
||||
CIRelation, CIRelation.second_ci_id == CI.id).filter(
|
||||
CIRelation.first_ci_id == first_ci_id)
|
||||
CIRelation.first_ci_id == first_ci_id).filter(CIRelation.deleted.is_(False))
|
||||
|
||||
if relation_type_id is not None:
|
||||
second_cis = second_cis.filter(CIRelation.relation_type_id == relation_type_id)
|
||||
|
||||
if kwargs: # TODO: special for devices
|
||||
second_cis = self._query_wrap_for_device(second_cis, **kwargs)
|
||||
|
||||
numfound = second_cis.count()
|
||||
if per_page != "all":
|
||||
second_cis = second_cis.offset((page - 1) * per_page).limit(per_page).all()
|
||||
@@ -468,33 +468,6 @@ class CIRelationManager(object):
|
||||
|
||||
return query_sql
|
||||
|
||||
def _query_wrap_for_device(self, query_sql, **kwargs):
|
||||
_type = kwargs.pop("_type", False) or kwargs.pop("type", False) or kwargs.pop("ci_type", False)
|
||||
if _type:
|
||||
ci_type = CITypeCache.get(_type)
|
||||
if ci_type is None:
|
||||
return
|
||||
query_sql = query_sql.filter(CI.type_id == ci_type.id)
|
||||
|
||||
for k, v in kwargs.items():
|
||||
attr = AttributeCache.get(k)
|
||||
if attr is None:
|
||||
continue
|
||||
|
||||
value_table = TableMap(attr_name=k).table
|
||||
ci_table = query_sql.subquery()
|
||||
query_sql = db.session.query(ci_table.c.id).join(
|
||||
value_table, value_table.ci_id == ci_table.c.id).filter(
|
||||
value_table.attr_id == attr.id).filter(ci_table.deleted.is_(False)).filter(
|
||||
value_table.value.ilike(v.replace("*", "%")))
|
||||
|
||||
# current_app.logger.debug(query_sql)
|
||||
sort_by = kwargs.pop("sort", "")
|
||||
if sort_by:
|
||||
query_sql = self._sort_handler(sort_by, query_sql)
|
||||
|
||||
return query_sql
|
||||
|
||||
@classmethod
|
||||
def get_first_cis(cls, second_ci, relation_type_id=None, page=1, per_page=None):
|
||||
first_cis = db.session.query(CIRelation.first_ci_id).filter(
|
||||
@@ -512,26 +485,48 @@ class CIRelationManager(object):
|
||||
return numfound, len(first_ci_ids), result
|
||||
|
||||
@classmethod
|
||||
def add(cls, first_ci_id, second_ci_id, more=None, relation_type_id=None):
|
||||
def add(cls, first_ci_id, second_ci_id, more=None, relation_type_id=None, many_to_one=False):
|
||||
|
||||
relation_type_id = relation_type_id or cls._get_default_relation_type()
|
||||
|
||||
CIManager.confirm_ci_existed(first_ci_id)
|
||||
CIManager.confirm_ci_existed(second_ci_id)
|
||||
first_ci = CIManager.confirm_ci_existed(first_ci_id)
|
||||
second_ci = CIManager.confirm_ci_existed(second_ci_id)
|
||||
|
||||
existed = CIRelation.get_by(first_ci_id=first_ci_id,
|
||||
second_ci_id=second_ci_id,
|
||||
to_dict=False,
|
||||
first=True)
|
||||
if existed is not None:
|
||||
if existed.relation_type_id != relation_type_id:
|
||||
if existed.relation_type_id != relation_type_id and relation_type_id is not None:
|
||||
existed.update(relation_type_id=relation_type_id)
|
||||
|
||||
CIRelationHistoryManager().add(existed, OperateType.UPDATE)
|
||||
else:
|
||||
if relation_type_id is None:
|
||||
type_relation = CITypeRelation.get_by(parent_id=first_ci.type_id,
|
||||
child_id=second_ci.type_id,
|
||||
first=True,
|
||||
to_dict=False)
|
||||
relation_type_id = type_relation and type_relation.relation_type_id
|
||||
relation_type_id or abort(404, "Relation {0} <-> {1} is not found".format(
|
||||
first_ci.ci_type.name, second_ci.ci_type.name))
|
||||
|
||||
if many_to_one:
|
||||
for item in CIRelation.get_by(second_ci_id=second_ci_id,
|
||||
relation_type_id=relation_type_id,
|
||||
to_dict=False):
|
||||
item.soft_delete()
|
||||
his_manager = CIRelationHistoryManager()
|
||||
his_manager.add(item, operate_type=OperateType.DELETE)
|
||||
|
||||
ci_relation_delete.apply_async(args=(item.first_ci_id, item.second_ci_id), queue=CMDB_QUEUE)
|
||||
|
||||
existed = CIRelation.create(first_ci_id=first_ci_id,
|
||||
second_ci_id=second_ci_id,
|
||||
relation_type_id=relation_type_id)
|
||||
|
||||
CIRelationHistoryManager().add(existed, OperateType.ADD)
|
||||
|
||||
ci_relation_cache.apply_async(args=(first_ci_id, second_ci_id), queue=CMDB_QUEUE)
|
||||
|
||||
if more is not None:
|
||||
existed.upadte(more=more)
|
||||
|
||||
@@ -540,11 +535,13 @@ class CIRelationManager(object):
|
||||
@staticmethod
|
||||
def delete(cr_id):
|
||||
cr = CIRelation.get_by_id(cr_id) or abort(404, "CIRelation <{0}> is not existed".format(cr_id))
|
||||
cr.soft_delete()
|
||||
cr.delete()
|
||||
|
||||
his_manager = CIRelationHistoryManager()
|
||||
his_manager.add(cr, operate_type=OperateType.DELETE)
|
||||
|
||||
ci_relation_delete.apply_async(args=(cr.first_ci_id, cr.second_ci_id), queue=CMDB_QUEUE)
|
||||
|
||||
return cr_id
|
||||
|
||||
@classmethod
|
||||
@@ -553,4 +550,29 @@ class CIRelationManager(object):
|
||||
second_ci_id=second_ci_id,
|
||||
to_dict=False,
|
||||
first=True)
|
||||
return cls.delete(cr.cr_id)
|
||||
|
||||
ci_relation_delete.apply_async(args=(first_ci_id, second_ci_id), queue=CMDB_QUEUE)
|
||||
|
||||
return cls.delete(cr.id)
|
||||
|
||||
@classmethod
|
||||
def batch_update(cls, ci_ids, parents):
|
||||
"""
|
||||
only for many to one
|
||||
:param ci_ids:
|
||||
:param parents:
|
||||
:return:
|
||||
"""
|
||||
from api.lib.cmdb.utils import TableMap
|
||||
|
||||
if parents is not None and isinstance(parents, dict):
|
||||
for attr_name in parents:
|
||||
if parents[attr_name]:
|
||||
attr = AttributeCache.get(attr_name)
|
||||
value_table = TableMap(attr_name=attr.name).table
|
||||
parent = value_table.get_by(attr_id=attr.id, value=parents[attr_name], first=True, to_dict=False)
|
||||
if not parent:
|
||||
return abort(404, "{0}: {1} is not found".format(attr_name, parents[attr_name]))
|
||||
parent_id = parent.ci_id
|
||||
for ci_id in ci_ids:
|
||||
cls.add(parent_id, ci_id, many_to_one=True)
|
@@ -4,11 +4,16 @@
|
||||
from flask import abort
|
||||
from flask import current_app
|
||||
|
||||
from api.extensions import db
|
||||
from api.lib.cmdb.attribute import AttributeManager
|
||||
from api.lib.cmdb.cache import AttributeCache
|
||||
from api.lib.cmdb.cache import CITypeAttributeCache
|
||||
from api.lib.cmdb.cache import CITypeAttributesCache
|
||||
from api.lib.cmdb.cache import CITypeCache
|
||||
from api.lib.cmdb.const import CMDB_QUEUE
|
||||
from api.lib.cmdb.value import AttributeValueManager
|
||||
from api.lib.decorator import kwargs_required
|
||||
from api.models.cmdb import CI
|
||||
from api.models.cmdb import CIType
|
||||
from api.models.cmdb import CITypeAttribute
|
||||
from api.models.cmdb import CITypeAttributeGroup
|
||||
@@ -16,6 +21,8 @@ from api.models.cmdb import CITypeAttributeGroupItem
|
||||
from api.models.cmdb import CITypeGroup
|
||||
from api.models.cmdb import CITypeGroupItem
|
||||
from api.models.cmdb import CITypeRelation
|
||||
from api.models.cmdb import PreferenceShowAttributes
|
||||
from api.models.cmdb import PreferenceTreeView
|
||||
|
||||
|
||||
class CITypeManager(object):
|
||||
@@ -32,7 +39,9 @@ class CITypeManager(object):
|
||||
|
||||
@staticmethod
|
||||
def check_is_existed(key):
|
||||
return CITypeCache.get(key) or abort(404, "CIType <{0}> is not existed".format(key))
|
||||
ci_type = CITypeCache.get(key) or abort(404, "CIType <{0}> is not existed".format(key))
|
||||
|
||||
return CIType.get_by_id(ci_type.id)
|
||||
|
||||
@staticmethod
|
||||
def get_ci_types(type_name=None):
|
||||
@@ -48,16 +57,35 @@ class CITypeManager(object):
|
||||
ci_type = CITypeCache.get(_type) or abort(404, "CIType <{0}> is not found".format(_type))
|
||||
return ci_type.to_dict()
|
||||
|
||||
@staticmethod
|
||||
def _validate_unique(type_id=None, name=None, alias=None):
|
||||
if name is not None:
|
||||
ci_type = CIType.get_by(name=name, first=True, to_dict=False)
|
||||
elif alias is not None:
|
||||
ci_type = CIType.get_by(alias=alias, first=True, to_dict=False)
|
||||
else:
|
||||
return
|
||||
|
||||
if not ci_type:
|
||||
return
|
||||
|
||||
if type_id is not None and ci_type.id != type_id:
|
||||
return abort(400, "CIType <{0}> is already existed".format(name or alias))
|
||||
|
||||
if type_id is None and ci_type is not None:
|
||||
return abort(400, "CIType <{0}> is already existed".format(name or alias))
|
||||
|
||||
@classmethod
|
||||
@kwargs_required("name")
|
||||
def add(cls, **kwargs):
|
||||
unique_key = kwargs.pop("unique_key", None)
|
||||
unique_key = AttributeCache.get(unique_key) or abort(404, "Unique key is not defined")
|
||||
|
||||
CIType.get_by(name=kwargs['name']) and abort(404, "CIType <{0}> is already existed".format(kwargs.get("name")))
|
||||
|
||||
kwargs["alias"] = kwargs["name"] if not kwargs.get("alias") else kwargs["alias"]
|
||||
|
||||
cls._validate_unique(name=kwargs['name'])
|
||||
cls._validate_unique(alias=kwargs['alias'])
|
||||
|
||||
kwargs["unique_id"] = unique_key.id
|
||||
ci_type = CIType.create(**kwargs)
|
||||
|
||||
@@ -65,6 +93,15 @@ class CITypeManager(object):
|
||||
|
||||
CITypeCache.clean(ci_type.name)
|
||||
|
||||
if current_app.config.get("USE_ACL"):
|
||||
from api.lib.perm.acl.acl import ACLManager
|
||||
from api.lib.cmdb.const import ResourceTypeEnum, RoleEnum, PermEnum
|
||||
ACLManager().add_resource(ci_type.name, ResourceTypeEnum.CI)
|
||||
ACLManager().grant_resource_to_role(ci_type.name,
|
||||
RoleEnum.CMDB_READ_ALL,
|
||||
ResourceTypeEnum.CI,
|
||||
permissions=[PermEnum.READ])
|
||||
|
||||
return ci_type.id
|
||||
|
||||
@classmethod
|
||||
@@ -72,6 +109,9 @@ class CITypeManager(object):
|
||||
|
||||
ci_type = cls.check_is_existed(type_id)
|
||||
|
||||
cls._validate_unique(type_id=type_id, name=kwargs.get('name'))
|
||||
cls._validate_unique(type_id=type_id, alias=kwargs.get('alias'))
|
||||
|
||||
unique_key = kwargs.pop("unique_key", None)
|
||||
unique_key = AttributeCache.get(unique_key)
|
||||
if unique_key is not None:
|
||||
@@ -98,10 +138,31 @@ class CITypeManager(object):
|
||||
@classmethod
|
||||
def delete(cls, type_id):
|
||||
ci_type = cls.check_is_existed(type_id)
|
||||
|
||||
if CI.get_by(type_id=type_id, first=True, to_dict=False) is not None:
|
||||
return abort(400, "cannot delete, because CI instance exists")
|
||||
|
||||
for item in CITypeRelation.get_by(parent_id=type_id, to_dict=False):
|
||||
item.soft_delete()
|
||||
|
||||
for item in CITypeRelation.get_by(child_id=type_id, to_dict=False):
|
||||
item.soft_delete()
|
||||
|
||||
for item in PreferenceTreeView.get_by(type_id=type_id, to_dict=False):
|
||||
item.soft_delete()
|
||||
|
||||
for item in PreferenceShowAttributes.get_by(type_id=type_id, to_dict=False):
|
||||
item.soft_delete()
|
||||
|
||||
ci_type.soft_delete()
|
||||
|
||||
CITypeCache.clean(type_id)
|
||||
|
||||
if current_app.config.get("USE_ACL"):
|
||||
from api.lib.perm.acl.acl import ACLManager
|
||||
from api.lib.cmdb.const import ResourceTypeEnum, RoleEnum, PermEnum
|
||||
ACLManager().del_resource(ci_type.name, ResourceTypeEnum.CI)
|
||||
|
||||
|
||||
class CITypeGroupManager(object):
|
||||
@staticmethod
|
||||
@@ -167,11 +228,11 @@ class CITypeAttributeManager(object):
|
||||
|
||||
@staticmethod
|
||||
def get_attr_names_by_type_id(type_id):
|
||||
return [AttributeCache.get(attr.attr_id).name for attr in CITypeAttributeCache.get(type_id)]
|
||||
return [AttributeCache.get(attr.attr_id).name for attr in CITypeAttributesCache.get(type_id)]
|
||||
|
||||
@staticmethod
|
||||
def get_attributes_by_type_id(type_id):
|
||||
attrs = CITypeAttributeCache.get(type_id)
|
||||
attrs = CITypeAttributesCache.get(type_id)
|
||||
result = list()
|
||||
for attr in sorted(attrs, key=lambda x: (x.order, x.id)):
|
||||
attr_dict = AttributeManager().get_attribute(attr.attr_id)
|
||||
@@ -213,7 +274,7 @@ class CITypeAttributeManager(object):
|
||||
current_app.logger.debug(attr_id)
|
||||
CITypeAttribute.create(type_id=type_id, attr_id=attr_id, **kwargs)
|
||||
|
||||
CITypeAttributeCache.clean(type_id)
|
||||
CITypeAttributesCache.clean(type_id)
|
||||
|
||||
@classmethod
|
||||
def update(cls, type_id, attributes):
|
||||
@@ -235,7 +296,9 @@ class CITypeAttributeManager(object):
|
||||
|
||||
existed.update(**attr)
|
||||
|
||||
CITypeAttributeCache.clean(type_id)
|
||||
CITypeAttributeCache.clean(type_id, existed.attr_id)
|
||||
|
||||
CITypeAttributesCache.clean(type_id)
|
||||
|
||||
@classmethod
|
||||
def delete(cls, type_id, attr_ids=None):
|
||||
@@ -245,6 +308,8 @@ class CITypeAttributeManager(object):
|
||||
:param attr_ids: list
|
||||
:return:
|
||||
"""
|
||||
from api.tasks.cmdb import ci_cache
|
||||
|
||||
cls._check(type_id, attr_ids)
|
||||
|
||||
for attr_id in attr_ids:
|
||||
@@ -255,7 +320,40 @@ class CITypeAttributeManager(object):
|
||||
if existed is not None:
|
||||
existed.soft_delete()
|
||||
|
||||
CITypeAttributeCache.clean(type_id)
|
||||
for ci in CI.get_by(type_id=type_id, to_dict=False):
|
||||
AttributeValueManager.delete_attr_value(attr_id, ci.id)
|
||||
|
||||
ci_cache.apply_async([ci.id], queue=CMDB_QUEUE)
|
||||
|
||||
CITypeAttributeCache.clean(type_id, attr_id)
|
||||
|
||||
CITypeAttributesCache.clean(type_id)
|
||||
|
||||
@classmethod
|
||||
def transfer(cls, type_id, _from, _to):
|
||||
current_app.logger.info("[{0}] {1} -> {2}".format(type_id, _from, _to))
|
||||
attr_id = _from.get('attr_id')
|
||||
from_group_id = _from.get('group_id')
|
||||
to_group_id = _to.get('group_id')
|
||||
order = _to.get('order')
|
||||
|
||||
if from_group_id != to_group_id:
|
||||
if from_group_id is not None:
|
||||
CITypeAttributeGroupManager.delete_item(from_group_id, attr_id)
|
||||
|
||||
if to_group_id is not None:
|
||||
CITypeAttributeGroupManager.add_item(to_group_id, attr_id, order)
|
||||
|
||||
elif from_group_id:
|
||||
CITypeAttributeGroupManager.update_item(from_group_id, attr_id, order)
|
||||
|
||||
else: # other attribute transfer
|
||||
return abort(400, "invalid operation!!!")
|
||||
|
||||
CITypeAttributesCache.clean(type_id)
|
||||
|
||||
from api.tasks.cmdb import ci_type_attribute_order_rebuild
|
||||
ci_type_attribute_order_rebuild.apply_async(args=(type_id,), queue=CMDB_QUEUE)
|
||||
|
||||
|
||||
class CITypeRelationManager(object):
|
||||
@@ -263,8 +361,26 @@ class CITypeRelationManager(object):
|
||||
manage relation between CITypes
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
pass
|
||||
@staticmethod
|
||||
def get():
|
||||
res = CITypeRelation.get_by(to_dict=False)
|
||||
for idx, item in enumerate(res):
|
||||
_item = item.to_dict()
|
||||
res[idx] = _item
|
||||
res[idx]['parent'] = item.parent.to_dict()
|
||||
res[idx]['child'] = item.child.to_dict()
|
||||
res[idx]['relation_type'] = item.relation_type.to_dict()
|
||||
|
||||
return res
|
||||
|
||||
@staticmethod
|
||||
def get_child_type_ids(type_id, level):
|
||||
ids = [type_id]
|
||||
query = db.session.query(CITypeRelation).filter(CITypeRelation.deleted.is_(False))
|
||||
for _ in range(0, level):
|
||||
ids = [i.child_id for i in query.filter(CITypeRelation.parent_id.in_(ids))]
|
||||
|
||||
return ids
|
||||
|
||||
@staticmethod
|
||||
def _wrap_relation_type_dict(type_id, relation_inst):
|
||||
@@ -375,6 +491,8 @@ class CITypeAttributeGroupManager(object):
|
||||
return abort(400, "Group <{0}> duplicate".format(name))
|
||||
if name is not None:
|
||||
group.update(name=name)
|
||||
else:
|
||||
name = group.name
|
||||
|
||||
cls.create_or_update(group.type_id, name, attr_order, group_order)
|
||||
|
||||
@@ -389,3 +507,87 @@ class CITypeAttributeGroupManager(object):
|
||||
item.soft_delete()
|
||||
|
||||
return group_id
|
||||
|
||||
@classmethod
|
||||
def add_item(cls, group_id, attr_id, order):
|
||||
db.session.remove()
|
||||
|
||||
existed = CITypeAttributeGroupItem.get_by(group_id=group_id,
|
||||
attr_id=attr_id,
|
||||
first=True,
|
||||
to_dict=False)
|
||||
if existed is not None:
|
||||
existed.update(order=order)
|
||||
else:
|
||||
CITypeAttributeGroupItem.create(group_id=group_id, attr_id=attr_id, order=order)
|
||||
|
||||
gt_items = db.session.query(CITypeAttributeGroupItem).filter(
|
||||
CITypeAttributeGroupItem.deleted.is_(False)).filter(CITypeAttributeGroupItem.order > order)
|
||||
for _item in gt_items:
|
||||
_order = _item.order
|
||||
_item.update(order=_order + 1)
|
||||
|
||||
@classmethod
|
||||
def update_item(cls, group_id, attr_id, order):
|
||||
db.session.remove()
|
||||
|
||||
existed = CITypeAttributeGroupItem.get_by(group_id=group_id,
|
||||
attr_id=attr_id,
|
||||
first=True,
|
||||
to_dict=False)
|
||||
existed or abort(404, "Group<{0}> - Attribute<{1}> is not found".format(group_id, attr_id))
|
||||
|
||||
if existed.order > order: # forward, +1
|
||||
items = db.session.query(CITypeAttributeGroupItem).filter(
|
||||
CITypeAttributeGroupItem.deleted.is_(False)).filter(
|
||||
CITypeAttributeGroupItem.order >= order).filter(
|
||||
CITypeAttributeGroupItem.order < existed.order)
|
||||
for item in items:
|
||||
item.update(order=item.order + 1)
|
||||
|
||||
elif existed.order < order: # backward, -1
|
||||
items = db.session.query(CITypeAttributeGroupItem).filter(
|
||||
CITypeAttributeGroupItem.deleted.is_(False)).filter(
|
||||
CITypeAttributeGroupItem.order > existed.order).filter(
|
||||
CITypeAttributeGroupItem.order <= order)
|
||||
for item in items:
|
||||
item.update(order=item.order - 1)
|
||||
|
||||
existed.update(order=order)
|
||||
|
||||
@classmethod
|
||||
def delete_item(cls, group_id, attr_id):
|
||||
db.session.remove()
|
||||
|
||||
item = CITypeAttributeGroupItem.get_by(group_id=group_id,
|
||||
attr_id=attr_id,
|
||||
first=True,
|
||||
to_dict=False)
|
||||
|
||||
if item is not None:
|
||||
item.soft_delete()
|
||||
order = item.order
|
||||
gt_items = db.session.query(CITypeAttributeGroupItem).filter(
|
||||
CITypeAttributeGroupItem.deleted.is_(False)).filter(CITypeAttributeGroupItem.order > order)
|
||||
for _item in gt_items:
|
||||
_order = _item.order
|
||||
_item.update(order=_order - 1)
|
||||
|
||||
@classmethod
|
||||
def transfer(cls, type_id, _from, _to):
|
||||
current_app.logger.info("CIType[{0}] {1} -> {2}".format(type_id, _from, _to))
|
||||
from_group = CITypeAttributeGroup.get_by_id(_from)
|
||||
from_group or abort(404, "Group <{0}> is not found".format(_from))
|
||||
|
||||
to_group = CITypeAttributeGroup.get_by_id(_to)
|
||||
to_group or abort(404, "Group <{0}> is not found".format(_to))
|
||||
|
||||
from_order, to_order = from_group.order, to_group.order
|
||||
|
||||
from_group.update(order=to_order)
|
||||
to_group.update(order=from_order)
|
||||
|
||||
CITypeAttributesCache.clean(type_id)
|
||||
|
||||
from api.tasks.cmdb import ci_type_attribute_order_rebuild
|
||||
ci_type_attribute_order_rebuild.apply_async(args=(type_id,), queue=CMDB_QUEUE)
|
60
cmdb-api/api/lib/cmdb/const.py
Normal file
60
cmdb-api/api/lib/cmdb/const.py
Normal file
@@ -0,0 +1,60 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
from api.lib.utils import BaseEnum
|
||||
|
||||
|
||||
class ValueTypeEnum(BaseEnum):
|
||||
INT = "0"
|
||||
FLOAT = "1"
|
||||
TEXT = "2"
|
||||
DATETIME = "3"
|
||||
DATE = "4"
|
||||
TIME = "5"
|
||||
JSON = "6"
|
||||
|
||||
|
||||
class CIStatusEnum(BaseEnum):
|
||||
REVIEW = "0"
|
||||
VALIDATE = "1"
|
||||
|
||||
|
||||
class ExistPolicy(BaseEnum):
|
||||
REJECT = "reject"
|
||||
NEED = "need"
|
||||
IGNORE = "ignore"
|
||||
REPLACE = "replace"
|
||||
|
||||
|
||||
class OperateType(BaseEnum):
|
||||
ADD = "0"
|
||||
DELETE = "1"
|
||||
UPDATE = "2"
|
||||
|
||||
|
||||
class RetKey(BaseEnum):
|
||||
ID = "id"
|
||||
NAME = "name"
|
||||
ALIAS = "alias"
|
||||
|
||||
|
||||
class ResourceTypeEnum(BaseEnum):
|
||||
CI = "CIType"
|
||||
RELATION_VIEW = "RelationView"
|
||||
|
||||
|
||||
class PermEnum(BaseEnum):
|
||||
ADD = "add"
|
||||
UPDATE = "update"
|
||||
DELETE = "delete"
|
||||
READ = "read"
|
||||
|
||||
|
||||
class RoleEnum(BaseEnum):
|
||||
CONFIG = "admin"
|
||||
CMDB_READ_ALL = "CMDB_READ_ALL"
|
||||
|
||||
|
||||
CMDB_QUEUE = "cmdb_async"
|
||||
REDIS_PREFIX_CI = "CMDB_CI"
|
||||
REDIS_PREFIX_CI_RELATION = "CMDB_CI_RELATION"
|
@@ -1,13 +1,16 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
import json
|
||||
|
||||
from flask import abort
|
||||
from flask import g
|
||||
|
||||
from api.extensions import db
|
||||
from api.lib.cmdb.cache import AttributeCache
|
||||
from api.lib.cmdb.cache import RelationTypeCache
|
||||
from api.models.account import UserCache
|
||||
from api.lib.cmdb.const import OperateType
|
||||
from api.lib.perm.acl.cache import UserCache
|
||||
from api.models.cmdb import Attribute
|
||||
from api.models.cmdb import AttributeHistory
|
||||
from api.models.cmdb import CIRelationHistory
|
||||
@@ -104,15 +107,15 @@ class AttributeHistoryManger(object):
|
||||
for attr_id, operate_type, old, new in history_list or []:
|
||||
AttributeHistory.create(attr_id=attr_id,
|
||||
operate_type=operate_type,
|
||||
old=old,
|
||||
new=new,
|
||||
old=json.dumps(old) if isinstance(old, (dict, list)) else old,
|
||||
new=json.dumps(new) if isinstance(new, (dict, list)) else new,
|
||||
ci_id=ci_id,
|
||||
record_id=record.id)
|
||||
|
||||
|
||||
class CIRelationHistoryManager(object):
|
||||
@staticmethod
|
||||
def add(rel_obj, operate_type=CIRelationHistory.ADD):
|
||||
def add(rel_obj, operate_type=OperateType.ADD):
|
||||
record = OperationRecord.create(uid=g.user.uid)
|
||||
|
||||
CIRelationHistory.create(relation_id=rel_obj.id,
|
@@ -1,16 +1,25 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
import copy
|
||||
import json
|
||||
|
||||
import six
|
||||
import toposort
|
||||
from flask import abort
|
||||
from flask import current_app
|
||||
from flask import g
|
||||
|
||||
from api.extensions import db
|
||||
from api.lib.cmdb.attribute import AttributeManager
|
||||
from api.lib.cmdb.cache import AttributeCache
|
||||
from api.lib.cmdb.cache import CITypeAttributeCache
|
||||
from api.lib.cmdb.cache import CITypeAttributesCache
|
||||
from api.lib.cmdb.cache import CITypeCache
|
||||
from api.lib.cmdb.const import ResourceTypeEnum, RoleEnum, PermEnum
|
||||
from api.lib.exception import AbortException
|
||||
from api.lib.perm.acl.acl import ACLManager
|
||||
from api.models.cmdb import CITypeAttribute
|
||||
from api.models.cmdb import CITypeRelation
|
||||
from api.models.cmdb import PreferenceRelationView
|
||||
from api.models.cmdb import PreferenceShowAttributes
|
||||
from api.models.cmdb import PreferenceTreeView
|
||||
@@ -91,7 +100,7 @@ class PreferenceManager(object):
|
||||
|
||||
@staticmethod
|
||||
def create_or_update_tree_view(type_id, levels):
|
||||
attrs = CITypeAttributeCache.get(type_id)
|
||||
attrs = CITypeAttributesCache.get(type_id)
|
||||
for idx, i in enumerate(levels):
|
||||
for attr in attrs:
|
||||
attr = AttributeCache.get(attr.attr_id)
|
||||
@@ -110,27 +119,90 @@ class PreferenceManager(object):
|
||||
|
||||
@staticmethod
|
||||
def get_relation_view():
|
||||
views = PreferenceRelationView.get_by(to_dict=True)
|
||||
_views = PreferenceRelationView.get_by(to_dict=True)
|
||||
views = []
|
||||
if current_app.config.get("USE_ACL"):
|
||||
for i in _views:
|
||||
try:
|
||||
if ACLManager().has_permission(i.get('name'),
|
||||
ResourceTypeEnum.RELATION_VIEW,
|
||||
PermEnum.READ):
|
||||
views.append(i)
|
||||
except AbortException:
|
||||
pass
|
||||
else:
|
||||
views = _views
|
||||
|
||||
view2cr_ids = dict()
|
||||
result = dict()
|
||||
name2id = list()
|
||||
for view in views:
|
||||
result.setdefault(view['name'], []).append(view)
|
||||
view2cr_ids.setdefault(view['name'], []).extend(json.loads(view['cr_ids']))
|
||||
name2id.append([view['name'], view['id']])
|
||||
|
||||
for view_name in result:
|
||||
result[view_name] = toposort.toposort_flatten({i['child_id']: {i['parent_id']} for i in result[view_name]})
|
||||
id2type = dict()
|
||||
for view_name in view2cr_ids:
|
||||
for i in view2cr_ids[view_name]:
|
||||
id2type[i['parent_id']] = None
|
||||
id2type[i['child_id']] = None
|
||||
topo = {i['child_id']: {i['parent_id']} for i in view2cr_ids[view_name]}
|
||||
leaf = list(set(toposort.toposort_flatten(topo)) - set([j for i in topo.values() for j in i]))
|
||||
|
||||
return result
|
||||
leaf2show_types = {i: [t['child_id'] for t in CITypeRelation.get_by(parent_id=i)] for i in leaf}
|
||||
node2show_types = copy.deepcopy(leaf2show_types)
|
||||
|
||||
@staticmethod
|
||||
def create_or_update_relation_view(name, parent_id, child_id):
|
||||
existed = PreferenceRelationView.get_by(name=name, parent_id=parent_id, child_id=child_id,
|
||||
to_dict=False, first=True)
|
||||
def _find_parent(_node_id):
|
||||
parents = topo.get(_node_id, {})
|
||||
for parent in parents:
|
||||
node2show_types.setdefault(parent, []).extend(node2show_types.get(_node_id, []))
|
||||
_find_parent(parent)
|
||||
if not parents:
|
||||
return
|
||||
|
||||
for l in leaf:
|
||||
_find_parent(l)
|
||||
|
||||
for node_id in node2show_types:
|
||||
node2show_types[node_id] = [CITypeCache.get(i).to_dict() for i in set(node2show_types[node_id])]
|
||||
|
||||
result[view_name] = dict(topo=list(map(list, toposort.toposort(topo))),
|
||||
topo_flatten=list(toposort.toposort_flatten(topo)),
|
||||
leaf=leaf,
|
||||
leaf2show_types=leaf2show_types,
|
||||
node2show_types=node2show_types,
|
||||
show_types=[CITypeCache.get(j).to_dict()
|
||||
for i in leaf2show_types.values() for j in i])
|
||||
|
||||
for type_id in id2type:
|
||||
id2type[type_id] = CITypeCache.get(type_id).to_dict()
|
||||
|
||||
return result, id2type, sorted(name2id, key=lambda x: x[1])
|
||||
|
||||
@classmethod
|
||||
def create_or_update_relation_view(cls, name, cr_ids):
|
||||
if not cr_ids:
|
||||
return abort(400, "Node must be selected")
|
||||
|
||||
existed = PreferenceRelationView.get_by(name=name, to_dict=False, first=True)
|
||||
current_app.logger.debug(existed)
|
||||
if existed is None:
|
||||
return PreferenceRelationView.create(name=name, parent_id=parent_id, child_id=child_id)
|
||||
PreferenceRelationView.create(name=name, cr_ids=json.dumps(cr_ids))
|
||||
|
||||
return existed
|
||||
if current_app.config.get("USE_ACL"):
|
||||
ACLManager().add_resource(name, ResourceTypeEnum.RELATION_VIEW)
|
||||
ACLManager().grant_resource_to_role(name,
|
||||
RoleEnum.CMDB_READ_ALL,
|
||||
ResourceTypeEnum.RELATION_VIEW,
|
||||
permissions=[PermEnum.READ])
|
||||
|
||||
return cls.get_relation_view()
|
||||
|
||||
@staticmethod
|
||||
def delete_relation_view(name):
|
||||
for existed in PreferenceRelationView.get_by(name=name, to_dict=False):
|
||||
existed.soft_delete()
|
||||
|
||||
if current_app.config.get("USE_ACL"):
|
||||
ACLManager().del_resource(name, ResourceTypeEnum.RELATION_VIEW)
|
||||
|
||||
return name
|
11
cmdb-api/api/lib/cmdb/search/__init__.py
Normal file
11
cmdb-api/api/lib/cmdb/search/__init__.py
Normal file
@@ -0,0 +1,11 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
__all__ = ['ci', 'ci_relation', 'SearchError']
|
||||
|
||||
|
||||
class SearchError(Exception):
|
||||
def __init__(self, v):
|
||||
self.v = v
|
||||
|
||||
def __str__(self):
|
||||
return self.v
|
@@ -1,3 +1,3 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
__author__ = 'pycook'
|
||||
__all__ = ['db', 'es']
|
@@ -12,25 +12,25 @@ from api.lib.cmdb.cache import AttributeCache
|
||||
from api.lib.cmdb.cache import CITypeCache
|
||||
from api.lib.cmdb.ci import CIManager
|
||||
from api.lib.cmdb.const import RetKey
|
||||
from api.lib.cmdb.const import TableMap
|
||||
from api.lib.cmdb.query_sql import FACET_QUERY
|
||||
from api.lib.cmdb.query_sql import QUERY_CI_BY_ATTR_NAME
|
||||
from api.lib.cmdb.query_sql import QUERY_CI_BY_TYPE
|
||||
from api.lib.cmdb.const import ValueTypeEnum
|
||||
from api.lib.cmdb.search import SearchError
|
||||
from api.lib.cmdb.search.ci.db.query_sql import FACET_QUERY
|
||||
from api.lib.cmdb.search.ci.db.query_sql import QUERY_CI_BY_ATTR_NAME
|
||||
from api.lib.cmdb.search.ci.db.query_sql import QUERY_CI_BY_TYPE
|
||||
from api.lib.cmdb.utils import TableMap
|
||||
from api.lib.utils import handle_arg_list
|
||||
from api.models.cmdb import Attribute
|
||||
from api.models.cmdb import CI
|
||||
|
||||
|
||||
class SearchError(Exception):
|
||||
def __init__(self, v):
|
||||
self.v = v
|
||||
|
||||
def __str__(self):
|
||||
return self.v
|
||||
|
||||
|
||||
class Search(object):
|
||||
def __init__(self, query=None, fl=None, facet_field=None, page=1, ret_key=RetKey.NAME, count=1, sort=None):
|
||||
def __init__(self, query=None,
|
||||
fl=None,
|
||||
facet_field=None,
|
||||
page=1,
|
||||
ret_key=RetKey.NAME,
|
||||
count=1,
|
||||
sort=None,
|
||||
ci_ids=None):
|
||||
self.orig_query = query
|
||||
self.fl = fl
|
||||
self.facet_field = facet_field
|
||||
@@ -38,6 +38,7 @@ class Search(object):
|
||||
self.ret_key = ret_key
|
||||
self.count = count
|
||||
self.sort = sort
|
||||
self.ci_ids = ci_ids or []
|
||||
self.query_sql = ""
|
||||
self.type_id_list = []
|
||||
self.only_type_query = False
|
||||
@@ -60,10 +61,10 @@ class Search(object):
|
||||
operator, key = self._operator_proc(key)
|
||||
|
||||
if key in ('ci_type', 'type', '_type'):
|
||||
return '_type', Attribute.TEXT, operator, None
|
||||
return '_type', ValueTypeEnum.TEXT, operator, None
|
||||
|
||||
if key in ('id', 'ci_id', '_id'):
|
||||
return '_id', Attribute.TEXT, operator, None
|
||||
return '_id', ValueTypeEnum.TEXT, operator, None
|
||||
|
||||
attr = AttributeCache.get(key)
|
||||
if attr:
|
||||
@@ -134,12 +135,12 @@ class Search(object):
|
||||
elif self.type_id_list:
|
||||
self.query_sql = "SELECT B.ci_id FROM ({0}) AS B {1}".format(
|
||||
query_sql,
|
||||
"INNER JOIN c_cis on c_cis.id=B.ci_id WHERE c_cis.type_id in ({0}) ".format(
|
||||
"INNER JOIN c_cis on c_cis.id=B.ci_id WHERE c_cis.type_id IN ({0}) ".format(
|
||||
",".join(self.type_id_list)))
|
||||
|
||||
return ret_sql.format(
|
||||
query_sql,
|
||||
"INNER JOIN c_cis on c_cis.id=B.ci_id WHERE c_cis.type_id in ({3}) "
|
||||
"INNER JOIN c_cis on c_cis.id=B.ci_id WHERE c_cis.type_id IN ({3}) "
|
||||
"ORDER BY B.ci_id {1} LIMIT {0:d}, {2};".format(
|
||||
(self.page - 1) * self.count, sort_type, self.count, ",".join(self.type_id_list)))
|
||||
|
||||
@@ -173,12 +174,12 @@ class Search(object):
|
||||
self.query_sql = """SELECT C.ci_id
|
||||
FROM ({0}) AS C
|
||||
INNER JOIN c_cis on c_cis.id=C.ci_id
|
||||
WHERE c_cis.type_id in ({1})""".format(new_table, ",".join(self.type_id_list))
|
||||
WHERE c_cis.type_id IN ({1})""".format(new_table, ",".join(self.type_id_list))
|
||||
|
||||
return """SELECT SQL_CALC_FOUND_ROWS DISTINCT C.ci_id, C.value
|
||||
FROM ({0}) AS C
|
||||
INNER JOIN c_cis on c_cis.id=C.ci_id
|
||||
WHERE c_cis.type_id in ({4})
|
||||
WHERE c_cis.type_id IN ({4})
|
||||
ORDER BY C.value {2}
|
||||
LIMIT {1:d}, {3};""".format(new_table,
|
||||
(self.page - 1) * self.count,
|
||||
@@ -286,6 +287,13 @@ class Search(object):
|
||||
alias += "AA"
|
||||
return None, query_sql
|
||||
|
||||
def _filter_ids(self, query_sql):
|
||||
if self.ci_ids:
|
||||
return "SELECT * FROM ({0}) AS IN_QUERY WHERE IN_QUERY.ci_id IN ({1})".format(
|
||||
query_sql, ",".join(list(map(str, self.ci_ids))))
|
||||
|
||||
return query_sql
|
||||
|
||||
def _query_build_raw(self):
|
||||
|
||||
queries = handle_arg_list(self.orig_query)
|
||||
@@ -298,6 +306,7 @@ class Search(object):
|
||||
|
||||
s = time.time()
|
||||
if query_sql:
|
||||
query_sql = self._filter_ids(query_sql)
|
||||
self.query_sql = query_sql
|
||||
current_app.logger.debug(query_sql)
|
||||
numfound, res = self._execute_sql(query_sql)
|
260
cmdb-api/api/lib/cmdb/search/ci/es/search.py
Normal file
260
cmdb-api/api/lib/cmdb/search/ci/es/search.py
Normal file
@@ -0,0 +1,260 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
from __future__ import unicode_literals
|
||||
|
||||
import six
|
||||
from flask import current_app
|
||||
|
||||
from api.extensions import es
|
||||
from api.lib.cmdb.cache import AttributeCache
|
||||
from api.lib.cmdb.const import RetKey
|
||||
from api.lib.cmdb.const import ValueTypeEnum
|
||||
from api.lib.cmdb.search import SearchError
|
||||
from api.lib.utils import handle_arg_list
|
||||
|
||||
|
||||
class Search(object):
|
||||
def __init__(self, query=None,
|
||||
fl=None,
|
||||
facet_field=None,
|
||||
page=1,
|
||||
ret_key=RetKey.NAME,
|
||||
count=1,
|
||||
sort=None,
|
||||
ci_ids=None):
|
||||
self.orig_query = query
|
||||
self.fl = fl
|
||||
self.facet_field = facet_field
|
||||
self.page = page
|
||||
self.ret_key = ret_key
|
||||
self.count = count or current_app.config.get("DEFAULT_PAGE_COUNT")
|
||||
self.sort = sort or "ci_id"
|
||||
self.ci_ids = ci_ids or []
|
||||
|
||||
self.query = dict(query=dict(bool=dict(should=[], must=[], must_not=[])))
|
||||
|
||||
@staticmethod
|
||||
def _operator_proc(key):
|
||||
operator = "&"
|
||||
if key.startswith("+"):
|
||||
key = key[1:].strip()
|
||||
elif key.startswith("-"):
|
||||
operator = "|"
|
||||
key = key[1:].strip()
|
||||
elif key.startswith("~"):
|
||||
operator = "~"
|
||||
key = key[1:].strip()
|
||||
|
||||
return operator, key
|
||||
|
||||
def _operator2query(self, operator):
|
||||
if operator == "&":
|
||||
return self.query['query']['bool']['must']
|
||||
elif operator == "|":
|
||||
return self.query['query']['bool']['should']
|
||||
else:
|
||||
return self.query['query']['bool']['must_not']
|
||||
|
||||
def _attr_name_proc(self, key):
|
||||
operator, key = self._operator_proc(key)
|
||||
|
||||
if key in ('ci_type', 'type', '_type'):
|
||||
return 'ci_type', ValueTypeEnum.TEXT, operator
|
||||
|
||||
if key in ('id', 'ci_id', '_id'):
|
||||
return 'ci_id', ValueTypeEnum.TEXT, operator
|
||||
|
||||
attr = AttributeCache.get(key)
|
||||
if attr:
|
||||
return attr.name, attr.value_type, operator
|
||||
else:
|
||||
raise SearchError("{0} is not existed".format(key))
|
||||
|
||||
def _in_query_handle(self, attr, v):
|
||||
terms = v[1:-1].split(";")
|
||||
operator = "|"
|
||||
if attr in ('_type', 'ci_type', 'type_id') and terms and terms[0].isdigit():
|
||||
attr = "type_id"
|
||||
terms = map(int, terms)
|
||||
current_app.logger.warning(terms)
|
||||
for term in terms:
|
||||
self._operator2query(operator).append({
|
||||
"term": {
|
||||
attr: term
|
||||
}
|
||||
})
|
||||
|
||||
def _filter_ids(self):
|
||||
if self.ci_ids:
|
||||
self.query['query']['bool'].update(dict(filter=dict(terms=dict(ci_id=self.ci_ids))))
|
||||
|
||||
@staticmethod
|
||||
def _digit(s):
|
||||
if s.isdigit():
|
||||
return int(float(s))
|
||||
return s
|
||||
|
||||
def _range_query_handle(self, attr, v, operator):
|
||||
left, right = v.split("_TO_")
|
||||
left, right = left.strip()[1:], right.strip()[:-1]
|
||||
self._operator2query(operator).append({
|
||||
"range": {
|
||||
attr: {
|
||||
"lte": self._digit(right),
|
||||
"gte": self._digit(left),
|
||||
"boost": 2.0
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
def _comparison_query_handle(self, attr, v, operator):
|
||||
if v.startswith(">="):
|
||||
_query = dict(gte=self._digit(v[2:]), boost=2.0)
|
||||
elif v.startswith("<="):
|
||||
_query = dict(lte=self._digit(v[2:]), boost=2.0)
|
||||
elif v.startswith(">"):
|
||||
_query = dict(gt=self._digit(v[1:]), boost=2.0)
|
||||
elif v.startswith("<"):
|
||||
_query = dict(lt=self._digit(v[1:]), boost=2.0)
|
||||
else:
|
||||
return
|
||||
|
||||
self._operator2query(operator).append({
|
||||
"range": {
|
||||
attr: _query
|
||||
}
|
||||
})
|
||||
|
||||
def _match_query_handle(self, attr, v, operator):
|
||||
if "*" in v:
|
||||
self._operator2query(operator).append({
|
||||
"wildcard": {
|
||||
attr: v.lower() if isinstance(v, six.string_types) else v
|
||||
}
|
||||
})
|
||||
else:
|
||||
if attr == "ci_type" and v.isdigit():
|
||||
attr = "type_id"
|
||||
self._operator2query(operator).append({
|
||||
"term": {
|
||||
attr: v.lower() if isinstance(v, six.string_types) else v
|
||||
}
|
||||
})
|
||||
|
||||
def __query_build_by_field(self, queries):
|
||||
|
||||
for q in queries:
|
||||
if ":" in q:
|
||||
k = q.split(":")[0].strip()
|
||||
v = ":".join(q.split(":")[1:]).strip()
|
||||
field_name, field_type, operator = self._attr_name_proc(k)
|
||||
if field_name:
|
||||
# in query
|
||||
if v.startswith("(") and v.endswith(")"):
|
||||
self._in_query_handle(field_name, v)
|
||||
# range query
|
||||
elif v.startswith("[") and v.endswith("]") and "_TO_" in v:
|
||||
self._range_query_handle(field_name, v, operator)
|
||||
# comparison query
|
||||
elif v.startswith(">=") or v.startswith("<=") or v.startswith(">") or v.startswith("<"):
|
||||
self._comparison_query_handle(field_name, v, operator)
|
||||
else:
|
||||
self._match_query_handle(field_name, v, operator)
|
||||
else:
|
||||
raise SearchError("argument q format invalid: {0}".format(q))
|
||||
elif q:
|
||||
raise SearchError("argument q format invalid: {0}".format(q))
|
||||
|
||||
def _query_build_raw(self):
|
||||
|
||||
queries = handle_arg_list(self.orig_query)
|
||||
|
||||
current_app.logger.debug(queries)
|
||||
|
||||
self.__query_build_by_field(queries)
|
||||
|
||||
self._paginate_build()
|
||||
|
||||
filter_path = self._fl_build()
|
||||
|
||||
self._sort_build()
|
||||
|
||||
self._facet_build()
|
||||
|
||||
self._filter_ids()
|
||||
|
||||
return es.read(self.query, filter_path=filter_path)
|
||||
|
||||
def _facet_build(self):
|
||||
aggregations = dict(aggs={})
|
||||
for field in self.facet_field:
|
||||
attr = AttributeCache.get(field)
|
||||
if not attr:
|
||||
raise SearchError("Facet by <{0}> does not exist".format(field))
|
||||
aggregations['aggs'].update({
|
||||
field: {
|
||||
"terms": {
|
||||
"field": "{0}.keyword".format(field)
|
||||
if attr.value_type not in (ValueTypeEnum.INT, ValueTypeEnum.FLOAT) else field
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if aggregations['aggs']:
|
||||
self.query.update(aggregations)
|
||||
|
||||
def _sort_build(self):
|
||||
fields = list(filter(lambda x: x != "", (self.sort or "").split(",")))
|
||||
sorts = []
|
||||
for field in fields:
|
||||
sort_type = "asc"
|
||||
if field.startswith("+"):
|
||||
field = field[1:]
|
||||
elif field.startswith("-"):
|
||||
field = field[1:]
|
||||
sort_type = "desc"
|
||||
else:
|
||||
field = field
|
||||
if field == "ci_id":
|
||||
sorts.append({field: {"order": sort_type}})
|
||||
continue
|
||||
|
||||
attr = AttributeCache.get(field)
|
||||
if not attr:
|
||||
raise SearchError("Sort by <{0}> does not exist".format(field))
|
||||
|
||||
sort_by = "{0}.keyword".format(field) \
|
||||
if attr.value_type not in (ValueTypeEnum.INT, ValueTypeEnum.FLOAT) else field
|
||||
sorts.append({sort_by: {"order": sort_type}})
|
||||
|
||||
self.query.update(dict(sort=sorts))
|
||||
|
||||
def _paginate_build(self):
|
||||
self.query.update({"from": (self.page - 1) * self.count,
|
||||
"size": self.count})
|
||||
|
||||
def _fl_build(self):
|
||||
return ['hits.hits._source.{0}'.format(i) for i in self.fl]
|
||||
|
||||
def search(self):
|
||||
try:
|
||||
numfound, cis, facet = self._query_build_raw()
|
||||
except Exception as e:
|
||||
current_app.logger.error(str(e))
|
||||
raise SearchError("unknown search error")
|
||||
|
||||
total = len(cis)
|
||||
|
||||
counter = dict()
|
||||
for ci in cis:
|
||||
ci_type = ci.get("ci_type")
|
||||
if ci_type not in counter.keys():
|
||||
counter[ci_type] = 0
|
||||
counter[ci_type] += 1
|
||||
|
||||
facet_ = dict()
|
||||
for k in facet:
|
||||
facet_[k] = [[i['key'], i['doc_count'], k] for i in facet[k]["buckets"]]
|
||||
|
||||
return cis, counter, total, self.page, numfound, facet_
|
1
cmdb-api/api/lib/cmdb/search/ci_relation/__init__.py
Normal file
1
cmdb-api/api/lib/cmdb/search/ci_relation/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# -*- coding:utf-8 -*-
|
109
cmdb-api/api/lib/cmdb/search/ci_relation/search.py
Normal file
109
cmdb-api/api/lib/cmdb/search/ci_relation/search.py
Normal file
@@ -0,0 +1,109 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
import json
|
||||
|
||||
from flask import abort
|
||||
from flask import current_app
|
||||
|
||||
from api.extensions import rd
|
||||
from api.lib.cmdb.ci_type import CITypeRelationManager
|
||||
from api.lib.cmdb.const import REDIS_PREFIX_CI_RELATION
|
||||
from api.lib.cmdb.search.ci.db.search import Search as SearchFromDB
|
||||
from api.lib.cmdb.search.ci.es.search import Search as SearchFromES
|
||||
from api.models.cmdb import CI
|
||||
|
||||
|
||||
class Search(object):
|
||||
def __init__(self, root_id,
|
||||
level=None,
|
||||
query=None,
|
||||
fl=None,
|
||||
facet_field=None,
|
||||
page=1,
|
||||
count=None,
|
||||
sort=None):
|
||||
self.orig_query = query
|
||||
self.fl = fl
|
||||
self.facet_field = facet_field
|
||||
self.page = page
|
||||
self.count = count or current_app.config.get("DEFAULT_PAGE_COUNT")
|
||||
self.sort = sort or ("ci_id" if current_app.config.get("USE_ES") else None)
|
||||
|
||||
self.root_id = root_id
|
||||
self.level = level
|
||||
|
||||
def search(self):
|
||||
ids = [self.root_id] if not isinstance(self.root_id, list) else self.root_id
|
||||
cis = [CI.get_by_id(_id) or abort(404, "CI <{0}> does not exist".format(_id)) for _id in ids]
|
||||
|
||||
merge_ids = []
|
||||
for level in self.level:
|
||||
ids = [self.root_id] if not isinstance(self.root_id, list) else self.root_id
|
||||
for _ in range(0, level):
|
||||
_tmp = list(map(lambda x: list(json.loads(x).keys()),
|
||||
filter(lambda x: x is not None, rd.get(ids, REDIS_PREFIX_CI_RELATION) or [])))
|
||||
ids = [j for i in _tmp for j in i]
|
||||
|
||||
merge_ids.extend(ids)
|
||||
|
||||
if not self.orig_query or ("_type:" not in self.orig_query
|
||||
and "type_id:" not in self.orig_query
|
||||
and "ci_type:" not in self.orig_query):
|
||||
type_ids = []
|
||||
for level in self.level:
|
||||
for ci in cis:
|
||||
type_ids.extend(CITypeRelationManager.get_child_type_ids(ci.type_id, level))
|
||||
type_ids = list(set(type_ids))
|
||||
if self.orig_query:
|
||||
self.orig_query = "_type:({0}),{1}".format(";".join(list(map(str, type_ids))), self.orig_query)
|
||||
else:
|
||||
self.orig_query = "_type:({0})".format(";".join(list(map(str, type_ids))))
|
||||
|
||||
if not merge_ids:
|
||||
# cis, counter, total, self.page, numfound, facet_
|
||||
return [], {}, 0, self.page, 0, {}
|
||||
|
||||
if current_app.config.get("USE_ES"):
|
||||
return SearchFromES(self.orig_query,
|
||||
fl=self.fl,
|
||||
facet_field=self.facet_field,
|
||||
page=self.page,
|
||||
count=self.count,
|
||||
sort=self.sort,
|
||||
ci_ids=merge_ids).search()
|
||||
else:
|
||||
return SearchFromDB(self.orig_query,
|
||||
fl=self.fl,
|
||||
facet_field=self.facet_field,
|
||||
page=self.page,
|
||||
count=self.count,
|
||||
sort=self.sort,
|
||||
ci_ids=merge_ids).search()
|
||||
|
||||
def statistics(self, type_ids):
|
||||
_tmp = []
|
||||
ids = [self.root_id] if not isinstance(self.root_id, list) else self.root_id
|
||||
for l in range(0, int(self.level)):
|
||||
if not l:
|
||||
_tmp = list(map(lambda x: list(json.loads(x).keys()),
|
||||
[i or '{}' for i in rd.get(ids, REDIS_PREFIX_CI_RELATION) or []]))
|
||||
else:
|
||||
for idx, i in enumerate(_tmp):
|
||||
if i:
|
||||
if type_ids and l == self.level - 1:
|
||||
__tmp = list(
|
||||
map(lambda x: list({_id: 1 for _id, type_id in json.loads(x).items()
|
||||
if type_id in type_ids}.keys()),
|
||||
filter(lambda x: x is not None,
|
||||
rd.get(i, REDIS_PREFIX_CI_RELATION) or [])))
|
||||
else:
|
||||
|
||||
__tmp = list(map(lambda x: list(json.loads(x).keys()),
|
||||
filter(lambda x: x is not None,
|
||||
rd.get(i, REDIS_PREFIX_CI_RELATION) or [])))
|
||||
_tmp[idx] = [j for i in __tmp for j in i]
|
||||
else:
|
||||
_tmp[idx] = []
|
||||
|
||||
return {_id: len(_tmp[idx]) for idx, _id in enumerate(ids)}
|
125
cmdb-api/api/lib/cmdb/utils.py
Normal file
125
cmdb-api/api/lib/cmdb/utils.py
Normal file
@@ -0,0 +1,125 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
from __future__ import unicode_literals
|
||||
|
||||
import datetime
|
||||
import json
|
||||
|
||||
import six
|
||||
from markupsafe import escape
|
||||
|
||||
import api.models.cmdb as model
|
||||
from api.lib.cmdb.cache import AttributeCache
|
||||
from api.lib.cmdb.const import ValueTypeEnum
|
||||
|
||||
|
||||
def string2int(x):
|
||||
return int(float(x))
|
||||
|
||||
|
||||
def str2datetime(x):
|
||||
try:
|
||||
return datetime.datetime.strptime(x, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
class ValueTypeMap(object):
|
||||
deserialize = {
|
||||
ValueTypeEnum.INT: string2int,
|
||||
ValueTypeEnum.FLOAT: float,
|
||||
ValueTypeEnum.TEXT: lambda x: escape(x).encode('utf-8').decode('utf-8'),
|
||||
ValueTypeEnum.TIME: lambda x: escape(x).encode('utf-8').decode('utf-8'),
|
||||
ValueTypeEnum.DATETIME: str2datetime,
|
||||
ValueTypeEnum.DATE: str2datetime,
|
||||
ValueTypeEnum.JSON: lambda x: json.loads(x) if isinstance(x, six.string_types) and x else x,
|
||||
}
|
||||
|
||||
serialize = {
|
||||
ValueTypeEnum.INT: int,
|
||||
ValueTypeEnum.FLOAT: float,
|
||||
ValueTypeEnum.TEXT: lambda x: x if isinstance(x, six.string_types) else str(x),
|
||||
ValueTypeEnum.TIME: lambda x: x if isinstance(x, six.string_types) else str(x),
|
||||
ValueTypeEnum.DATE: lambda x: x.strftime("%Y-%m-%d"),
|
||||
ValueTypeEnum.DATETIME: lambda x: x.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
ValueTypeEnum.JSON: lambda x: json.loads(x) if isinstance(x, six.string_types) and x else x,
|
||||
}
|
||||
|
||||
serialize2 = {
|
||||
ValueTypeEnum.INT: int,
|
||||
ValueTypeEnum.FLOAT: float,
|
||||
ValueTypeEnum.TEXT: lambda x: x.decode() if not isinstance(x, six.string_types) else x,
|
||||
ValueTypeEnum.TIME: lambda x: x.decode() if not isinstance(x, six.string_types) else x,
|
||||
ValueTypeEnum.DATE: lambda x: x.decode() if not isinstance(x, six.string_types) else x,
|
||||
ValueTypeEnum.DATETIME: lambda x: x.decode() if not isinstance(x, six.string_types) else x,
|
||||
ValueTypeEnum.JSON: lambda x: json.loads(x) if isinstance(x, six.string_types) and x else x,
|
||||
}
|
||||
|
||||
choice = {
|
||||
ValueTypeEnum.INT: model.IntegerChoice,
|
||||
ValueTypeEnum.FLOAT: model.FloatChoice,
|
||||
ValueTypeEnum.TEXT: model.TextChoice,
|
||||
}
|
||||
|
||||
table = {
|
||||
ValueTypeEnum.INT: model.CIValueInteger,
|
||||
ValueTypeEnum.TEXT: model.CIValueText,
|
||||
ValueTypeEnum.DATETIME: model.CIValueDateTime,
|
||||
ValueTypeEnum.DATE: model.CIValueDateTime,
|
||||
ValueTypeEnum.TIME: model.CIValueText,
|
||||
ValueTypeEnum.FLOAT: model.CIValueFloat,
|
||||
ValueTypeEnum.JSON: model.CIValueJson,
|
||||
'index_{0}'.format(ValueTypeEnum.INT): model.CIIndexValueInteger,
|
||||
'index_{0}'.format(ValueTypeEnum.TEXT): model.CIIndexValueText,
|
||||
'index_{0}'.format(ValueTypeEnum.DATETIME): model.CIIndexValueDateTime,
|
||||
'index_{0}'.format(ValueTypeEnum.DATE): model.CIIndexValueDateTime,
|
||||
'index_{0}'.format(ValueTypeEnum.TIME): model.CIIndexValueText,
|
||||
'index_{0}'.format(ValueTypeEnum.FLOAT): model.CIIndexValueFloat,
|
||||
'index_{0}'.format(ValueTypeEnum.JSON): model.CIValueJson,
|
||||
}
|
||||
|
||||
table_name = {
|
||||
ValueTypeEnum.INT: 'c_value_integers',
|
||||
ValueTypeEnum.TEXT: 'c_value_texts',
|
||||
ValueTypeEnum.DATETIME: 'c_value_datetime',
|
||||
ValueTypeEnum.DATE: 'c_value_datetime',
|
||||
ValueTypeEnum.TIME: 'c_value_texts',
|
||||
ValueTypeEnum.FLOAT: 'c_value_floats',
|
||||
ValueTypeEnum.JSON: 'c_value_json',
|
||||
'index_{0}'.format(ValueTypeEnum.INT): 'c_value_index_integers',
|
||||
'index_{0}'.format(ValueTypeEnum.TEXT): 'c_value_index_texts',
|
||||
'index_{0}'.format(ValueTypeEnum.DATETIME): 'c_value_index_datetime',
|
||||
'index_{0}'.format(ValueTypeEnum.DATE): 'c_value_index_datetime',
|
||||
'index_{0}'.format(ValueTypeEnum.TIME): 'c_value_index_texts',
|
||||
'index_{0}'.format(ValueTypeEnum.FLOAT): 'c_value_index_floats',
|
||||
'index_{0}'.format(ValueTypeEnum.JSON): 'c_value_json',
|
||||
}
|
||||
|
||||
es_type = {
|
||||
ValueTypeEnum.INT: 'long',
|
||||
ValueTypeEnum.TEXT: 'text',
|
||||
ValueTypeEnum.DATETIME: 'text',
|
||||
ValueTypeEnum.DATE: 'text',
|
||||
ValueTypeEnum.TIME: 'text',
|
||||
ValueTypeEnum.FLOAT: 'float',
|
||||
ValueTypeEnum.JSON: 'object'
|
||||
}
|
||||
|
||||
|
||||
class TableMap(object):
|
||||
def __init__(self, attr_name=None):
|
||||
self.attr_name = attr_name
|
||||
|
||||
@property
|
||||
def table(self):
|
||||
attr = AttributeCache.get(self.attr_name)
|
||||
i = "index_{0}".format(attr.value_type) if attr.is_index else attr.value_type
|
||||
return ValueTypeMap.table.get(i)
|
||||
|
||||
@property
|
||||
def table_name(self):
|
||||
attr = AttributeCache.get(self.attr_name)
|
||||
i = "index_{0}".format(attr.value_type) if attr.is_index else attr.value_type
|
||||
return ValueTypeMap.table_name.get(i)
|
@@ -3,19 +3,19 @@
|
||||
|
||||
from __future__ import unicode_literals
|
||||
|
||||
import markupsafe
|
||||
from flask import abort
|
||||
|
||||
from api.extensions import db
|
||||
from api.lib.cmdb.attribute import AttributeManager
|
||||
from api.lib.cmdb.cache import AttributeCache
|
||||
from api.lib.cmdb.cache import CITypeAttributeCache
|
||||
from api.lib.cmdb.const import ExistPolicy
|
||||
from api.lib.cmdb.const import OperateType
|
||||
from api.lib.cmdb.const import TableMap
|
||||
from api.lib.cmdb.const import type_map
|
||||
from api.lib.cmdb.const import ValueTypeEnum
|
||||
from api.lib.cmdb.history import AttributeHistoryManger
|
||||
from api.lib.cmdb.utils import TableMap
|
||||
from api.lib.cmdb.utils import ValueTypeMap
|
||||
from api.lib.utils import handle_arg_list
|
||||
from api.models.cmdb import Attribute
|
||||
|
||||
|
||||
class AttributeValueManager(object):
|
||||
@@ -58,9 +58,9 @@ class AttributeValueManager(object):
|
||||
field_name = getattr(attr, ret_key)
|
||||
|
||||
if attr.is_list:
|
||||
res[field_name] = [type_map["serialize"][attr.value_type](i.value) for i in rs]
|
||||
res[field_name] = [ValueTypeMap.serialize[attr.value_type](i.value) for i in rs]
|
||||
else:
|
||||
res[field_name] = type_map["serialize"][attr.value_type](rs[0].value) if rs else None
|
||||
res[field_name] = ValueTypeMap.serialize[attr.value_type](rs[0].value) if rs else None
|
||||
|
||||
if unique_key is not None and attr.id == unique_key.id and rs:
|
||||
res['unique'] = unique_key.name
|
||||
@@ -71,7 +71,7 @@ class AttributeValueManager(object):
|
||||
def __deserialize_value(value_type, value):
|
||||
if not value:
|
||||
return value
|
||||
deserialize = type_map["deserialize"][value_type]
|
||||
deserialize = ValueTypeMap.deserialize[value_type]
|
||||
try:
|
||||
v = deserialize(value)
|
||||
return v
|
||||
@@ -79,23 +79,31 @@ class AttributeValueManager(object):
|
||||
return abort(400, "attribute value <{0}> is invalid".format(value))
|
||||
|
||||
@staticmethod
|
||||
def __check_is_choice(attr_id, value_type, value):
|
||||
choice_values = AttributeManager.get_choice_values(attr_id, value_type)
|
||||
def __check_is_choice(attr, value_type, value):
|
||||
choice_values = AttributeManager.get_choice_values(attr.id, value_type)
|
||||
if value not in choice_values:
|
||||
return abort(400, "{0} does not existed in choice values".format(value))
|
||||
|
||||
@staticmethod
|
||||
def __check_is_unique(value_table, attr_id, ci_id, value):
|
||||
def __check_is_unique(value_table, attr, ci_id, value):
|
||||
existed = db.session.query(value_table.attr_id).filter(
|
||||
value_table.attr_id == attr_id).filter(value_table.deleted.is_(False)).filter(
|
||||
value_table.attr_id == attr.id).filter(value_table.deleted.is_(False)).filter(
|
||||
value_table.value == value).filter(value_table.ci_id != ci_id).first()
|
||||
existed and abort(400, "attribute <{0}> value {1} must be unique".format(attr_id, value))
|
||||
existed and abort(400, "attribute <{0}> value {1} must be unique".format(attr.alias, value))
|
||||
|
||||
def _validate(self, attr, value, value_table, ci_id):
|
||||
@staticmethod
|
||||
def __check_is_required(type_id, attr, value):
|
||||
type_attr = CITypeAttributeCache.get(type_id, attr.id)
|
||||
if type_attr and type_attr.is_required and not value and value != 0:
|
||||
return abort(400, "attribute <{0}> value is required".format(attr.alias))
|
||||
|
||||
def _validate(self, attr, value, value_table, ci):
|
||||
v = self.__deserialize_value(attr.value_type, value)
|
||||
|
||||
attr.is_choice and value and self.__check_is_choice(attr.id, attr.value_type, v)
|
||||
attr.is_unique and self.__check_is_unique(value_table, attr.id, ci_id, v)
|
||||
attr.is_choice and value and self.__check_is_choice(attr, attr.value_type, v)
|
||||
attr.is_unique and self.__check_is_unique(value_table, attr, ci.id, v)
|
||||
|
||||
self.__check_is_required(ci.type_id, attr, v)
|
||||
|
||||
return v
|
||||
|
||||
@@ -103,12 +111,12 @@ class AttributeValueManager(object):
|
||||
def _write_change(ci_id, attr_id, operate_type, old, new):
|
||||
AttributeHistoryManger.add(ci_id, [(attr_id, operate_type, old, new)])
|
||||
|
||||
def create_or_update_attr_value(self, key, value, ci_id, _no_attribute_policy=ExistPolicy.IGNORE):
|
||||
def create_or_update_attr_value(self, key, value, ci, _no_attribute_policy=ExistPolicy.IGNORE):
|
||||
"""
|
||||
add or update attribute value, then write history
|
||||
:param key: id, name or alias
|
||||
:param value:
|
||||
:param ci_id:
|
||||
:param ci: instance object
|
||||
:param _no_attribute_policy: ignore or reject
|
||||
:return:
|
||||
"""
|
||||
@@ -120,29 +128,49 @@ class AttributeValueManager(object):
|
||||
return abort(400, 'attribute {0} does not exist'.format(key))
|
||||
|
||||
value_table = TableMap(attr_name=attr.name).table
|
||||
existed_attr = value_table.get_by(attr_id=attr.id,
|
||||
ci_id=ci_id,
|
||||
first=True,
|
||||
to_dict=False)
|
||||
existed_value = existed_attr and existed_attr.value
|
||||
operate_type = OperateType.ADD if existed_attr is None else OperateType.UPDATE
|
||||
|
||||
value_list = handle_arg_list(value) if attr.is_list else [value]
|
||||
if not isinstance(value, list):
|
||||
value_list = [value]
|
||||
if attr.is_list:
|
||||
value_list = [self._validate(attr, i, value_table, ci) for i in handle_arg_list(value)]
|
||||
if not value_list:
|
||||
self.__check_is_required(ci.type_id, attr, '')
|
||||
|
||||
for v in value_list:
|
||||
v = self._validate(attr, v, value_table, ci_id)
|
||||
if not v and attr.value_type != Attribute.TEXT:
|
||||
v = None
|
||||
existed_attrs = value_table.get_by(attr_id=attr.id,
|
||||
ci_id=ci.id,
|
||||
to_dict=False)
|
||||
existed_values = [i.value for i in existed_attrs]
|
||||
added = set(value_list) - set(existed_values)
|
||||
deleted = set(existed_values) - set(value_list)
|
||||
for v in added:
|
||||
value_table.create(ci_id=ci.id, attr_id=attr.id, value=v)
|
||||
self._write_change(ci.id, attr.id, OperateType.ADD, None, v)
|
||||
|
||||
if operate_type == OperateType.ADD:
|
||||
if v is not None:
|
||||
value_table.create(ci_id=ci_id, attr_id=attr.id, value=v)
|
||||
self._write_change(ci_id, attr.id, operate_type, None, v)
|
||||
elif existed_attr.value != v:
|
||||
if v is not None:
|
||||
existed_attr.update(value=v)
|
||||
else:
|
||||
for v in deleted:
|
||||
existed_attr = existed_attrs[existed_values.index(v)]
|
||||
existed_attr.delete()
|
||||
self._write_change(ci.id, attr.id, OperateType.DELETE, v, None)
|
||||
else:
|
||||
value = self._validate(attr, value, value_table, ci)
|
||||
existed_attr = value_table.get_by(attr_id=attr.id,
|
||||
ci_id=ci.id,
|
||||
first=True,
|
||||
to_dict=False)
|
||||
existed_value = existed_attr and existed_attr.value
|
||||
if existed_value is None:
|
||||
value_table.create(ci_id=ci.id, attr_id=attr.id, value=value)
|
||||
|
||||
self._write_change(ci.id, attr.id, OperateType.ADD, None, value)
|
||||
else:
|
||||
if not value and attr.value_type != ValueTypeEnum.TEXT:
|
||||
existed_attr.delete()
|
||||
self._write_change(ci_id, attr.id, operate_type, existed_value, v)
|
||||
else:
|
||||
existed_attr.update(value=value)
|
||||
|
||||
self._write_change(ci.id, attr.id, OperateType.UPDATE, existed_value, value)
|
||||
|
||||
@staticmethod
|
||||
def delete_attr_value(attr_id, ci_id):
|
||||
attr = AttributeCache.get(attr_id)
|
||||
if attr is not None:
|
||||
value_table = TableMap(attr_name=attr.name).table
|
||||
for item in value_table.get_by(attr_id=attr.id, ci_id=ci_id, to_dict=False):
|
||||
item.delete()
|
@@ -10,9 +10,14 @@ from api.lib.exception import CommitException
|
||||
|
||||
class FormatMixin(object):
|
||||
def to_dict(self):
|
||||
return dict([(k.name,
|
||||
getattr(self, k.name) if not isinstance(getattr(self, k.name), datetime.datetime) else getattr(
|
||||
self, k.name).strftime('%Y-%m-%d %H:%M:%S')) for k in getattr(self, "__table__").columns])
|
||||
res = dict()
|
||||
for k in getattr(self, "__table__").columns:
|
||||
if not isinstance(getattr(self, k.name), datetime.datetime):
|
||||
res[k.name] = getattr(self, k.name)
|
||||
else:
|
||||
res[k.name] = getattr(self, k.name).strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
return res
|
||||
|
||||
@classmethod
|
||||
def get_columns(cls):
|
||||
@@ -20,6 +25,9 @@ class FormatMixin(object):
|
||||
|
||||
|
||||
class CRUDMixin(FormatMixin):
|
||||
def __init__(self, **kwargs):
|
||||
super(CRUDMixin, self).__init__(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def create(cls, flush=False, **kwargs):
|
||||
return cls(**kwargs).save(flush=flush)
|
||||
@@ -64,7 +72,7 @@ class CRUDMixin(FormatMixin):
|
||||
@classmethod
|
||||
def get_by_id(cls, _id):
|
||||
if any((isinstance(_id, six.string_types) and _id.isdigit(),
|
||||
isinstance(_id, (int, float))), ):
|
||||
isinstance(_id, (six.integer_types, float))), ):
|
||||
return getattr(cls, "query").get(int(_id)) or None
|
||||
|
||||
@classmethod
|
11
cmdb-api/api/lib/exception.py
Normal file
11
cmdb-api/api/lib/exception.py
Normal file
@@ -0,0 +1,11 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
from werkzeug.exceptions import NotFound, Forbidden, BadRequest
|
||||
|
||||
|
||||
class CommitException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
AbortException = (NotFound, Forbidden, BadRequest)
|
@@ -12,7 +12,7 @@ from future.moves.urllib.parse import urlparse
|
||||
|
||||
|
||||
def build_api_key(path, params):
|
||||
g.user is not None or abort(403, "您得登陆才能进行该操作")
|
||||
g.user is not None or abort(403, "You have to login to do this")
|
||||
key = g.user.key
|
||||
secret = g.user.secret
|
||||
values = "".join([str(params[k]) for k in sorted(params.keys())
|
1
cmdb-api/api/lib/perm/__init__.py
Normal file
1
cmdb-api/api/lib/perm/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# -*- coding:utf-8 -*-
|
23
cmdb-api/api/lib/perm/acl/__init__.py
Normal file
23
cmdb-api/api/lib/perm/acl/__init__.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
from functools import wraps
|
||||
|
||||
from flask import request
|
||||
from flask import abort
|
||||
|
||||
from api.lib.perm.acl.cache import AppCache
|
||||
|
||||
|
||||
def validate_app(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
app_id = request.values.get('app_id')
|
||||
app = AppCache.get(app_id)
|
||||
if app is None:
|
||||
return abort(400, "App <{0}> does not exist".format(app_id))
|
||||
request.values['app_id'] = app.id
|
||||
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
174
cmdb-api/api/lib/perm/acl/acl.py
Normal file
174
cmdb-api/api/lib/perm/acl/acl.py
Normal file
@@ -0,0 +1,174 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
import functools
|
||||
|
||||
import six
|
||||
from flask import current_app, g, request
|
||||
from flask import session, abort
|
||||
|
||||
from api.lib.cmdb.const import ResourceTypeEnum as CmdbResourceType
|
||||
from api.lib.cmdb.const import RoleEnum
|
||||
from api.lib.perm.acl.cache import AppCache
|
||||
from api.lib.perm.acl.cache import RoleCache
|
||||
from api.lib.perm.acl.cache import UserCache
|
||||
from api.lib.perm.acl.permission import PermissionCRUD
|
||||
from api.lib.perm.acl.resource import ResourceCRUD
|
||||
from api.lib.perm.acl.role import RoleCRUD
|
||||
from api.models.acl import Resource
|
||||
from api.models.acl import ResourceGroup
|
||||
from api.models.acl import ResourceType
|
||||
from api.models.acl import Role
|
||||
|
||||
CMDB_RESOURCE_TYPES = CmdbResourceType.all()
|
||||
|
||||
|
||||
class ACLManager(object):
|
||||
def __init__(self):
|
||||
self.app_id = AppCache.get('cmdb')
|
||||
if not self.app_id:
|
||||
raise Exception("cmdb not in acl apps")
|
||||
self.app_id = self.app_id.id
|
||||
|
||||
def _get_resource(self, name, resource_type_name):
|
||||
resource_type = ResourceType.get_by(name=resource_type_name, first=True, to_dict=False)
|
||||
resource_type or abort(404, "ResourceType <{0}> cannot be found".format(resource_type_name))
|
||||
|
||||
return Resource.get_by(resource_type_id=resource_type.id,
|
||||
app_id=self.app_id,
|
||||
name=name,
|
||||
first=True,
|
||||
to_dict=False)
|
||||
|
||||
def _get_resource_group(self, name):
|
||||
return ResourceGroup.get_by(
|
||||
app_id=self.app_id,
|
||||
name=name,
|
||||
first=True,
|
||||
to_dict=False
|
||||
)
|
||||
|
||||
def _get_role(self, name):
|
||||
user = UserCache.get(name)
|
||||
if user:
|
||||
return Role.get_by(name=name, uid=user.uid, first=True, to_dict=False)
|
||||
|
||||
return Role.get_by(name=name, app_id=self.app_id, first=True, to_dict=False)
|
||||
|
||||
def add_resource(self, name, resource_type_name=None):
|
||||
resource_type = ResourceType.get_by(name=resource_type_name, first=True, to_dict=False)
|
||||
resource_type or abort(404, "ResourceType <{0}> cannot be found".format(resource_type_name))
|
||||
|
||||
ResourceCRUD.add(name, resource_type.id, self.app_id)
|
||||
|
||||
def grant_resource_to_role(self, name, role, resource_type_name=None, permissions=None):
|
||||
resource = self._get_resource(name, resource_type_name)
|
||||
|
||||
role = self._get_role(role)
|
||||
|
||||
if resource:
|
||||
PermissionCRUD.grant(role.id, permissions, resource_id=resource.id)
|
||||
else:
|
||||
group = self._get_resource_group(name)
|
||||
if group:
|
||||
PermissionCRUD.grant(role.id, permissions, group_id=group.id)
|
||||
|
||||
def del_resource(self, name, resource_type_name=None):
|
||||
resource = self._get_resource(name, resource_type_name)
|
||||
if resource:
|
||||
ResourceCRUD.delete(resource.id)
|
||||
|
||||
def has_permission(self, resource_name, resource_type, perm):
|
||||
|
||||
role = self._get_role(g.user.username)
|
||||
|
||||
role or abort(404, "Role <{0}> is not found".format(g.user.username))
|
||||
|
||||
return RoleCRUD.has_permission(role.id, resource_name, resource_type, self.app_id, perm)
|
||||
|
||||
|
||||
def validate_permission(resources, resource_type, perm):
|
||||
if not resources:
|
||||
return
|
||||
|
||||
if current_app.config.get("USE_ACL"):
|
||||
if g.user.username == "worker":
|
||||
return
|
||||
|
||||
resources = [resources] if isinstance(resources, six.string_types) else resources
|
||||
for resource in resources:
|
||||
if not ACLManager().has_permission(resource, resource_type, perm):
|
||||
return abort(403, "has no permission")
|
||||
|
||||
|
||||
def has_perm(resources, resource_type, perm):
|
||||
def decorator_has_perm(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper_has_perm(*args, **kwargs):
|
||||
if not resources:
|
||||
return
|
||||
|
||||
if current_app.config.get("USE_ACL"):
|
||||
if is_app_admin():
|
||||
return func(*args, **kwargs)
|
||||
|
||||
validate_permission(resources, resource_type, perm)
|
||||
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper_has_perm
|
||||
|
||||
return decorator_has_perm
|
||||
|
||||
|
||||
def is_app_admin(app=None):
|
||||
if RoleEnum.CONFIG in session.get("acl", {}).get("parentRoles", []):
|
||||
return True
|
||||
|
||||
app = app or 'cmdb'
|
||||
app_id = AppCache.get(app).id
|
||||
|
||||
for role in session.get("acl", {}).get("parentRoles", []):
|
||||
if RoleCache.get_by_name(app_id, role).is_app_admin:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def has_perm_from_args(arg_name, resource_type, perm, callback=None):
|
||||
def decorator_has_perm(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper_has_perm(*args, **kwargs):
|
||||
if not arg_name:
|
||||
return
|
||||
resource = request.view_args.get(arg_name) or request.values.get(arg_name)
|
||||
if callback is not None and resource:
|
||||
resource = callback(resource)
|
||||
|
||||
if current_app.config.get("USE_ACL") and resource:
|
||||
if is_app_admin():
|
||||
return func(*args, **kwargs)
|
||||
|
||||
validate_permission(resource, resource_type, perm)
|
||||
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper_has_perm
|
||||
|
||||
return decorator_has_perm
|
||||
|
||||
|
||||
def role_required(role_name):
|
||||
def decorator_role_required(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper_role_required(*args, **kwargs):
|
||||
if not role_name:
|
||||
return
|
||||
|
||||
if current_app.config.get("USE_ACL"):
|
||||
if role_name not in session.get("acl", {}).get("parentRoles", []) and not is_app_admin():
|
||||
return abort(403, "Role {0} is required".format(role_name))
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper_role_required
|
||||
|
||||
return decorator_role_required
|
174
cmdb-api/api/lib/perm/acl/cache.py
Normal file
174
cmdb-api/api/lib/perm/acl/cache.py
Normal file
@@ -0,0 +1,174 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
from api.extensions import cache
|
||||
from api.extensions import db
|
||||
from api.models.acl import App
|
||||
from api.models.acl import Permission
|
||||
from api.models.acl import Role
|
||||
from api.models.acl import User
|
||||
|
||||
|
||||
class AppCache(object):
|
||||
PREFIX_ID = "App::id::{0}"
|
||||
PREFIX_NAME = "App::name::{0}"
|
||||
|
||||
@classmethod
|
||||
def get(cls, key):
|
||||
app = cache.get(cls.PREFIX_ID.format(key)) or cache.get(cls.PREFIX_NAME.format(key))
|
||||
if app is None:
|
||||
app = App.get_by_id(key) or App.get_by(name=key, to_dict=False, first=True)
|
||||
if app is not None:
|
||||
cls.set(app)
|
||||
|
||||
return app
|
||||
|
||||
@classmethod
|
||||
def set(cls, app):
|
||||
cache.set(cls.PREFIX_ID.format(app.id), app)
|
||||
cache.set(cls.PREFIX_NAME.format(app.name), app)
|
||||
|
||||
@classmethod
|
||||
def clean(cls, app):
|
||||
cache.delete(cls.PREFIX_ID.format(app.id))
|
||||
cache.delete(cls.PREFIX_NAME.format(app.name))
|
||||
|
||||
|
||||
class UserCache(object):
|
||||
PREFIX_ID = "User::uid::{0}"
|
||||
PREFIX_NAME = "User::username::{0}"
|
||||
PREFIX_NICK = "User::nickname::{0}"
|
||||
|
||||
@classmethod
|
||||
def get(cls, key):
|
||||
user = cache.get(cls.PREFIX_ID.format(key)) or \
|
||||
cache.get(cls.PREFIX_NAME.format(key)) or \
|
||||
cache.get(cls.PREFIX_NICK.format(key))
|
||||
if not user:
|
||||
user = User.query.get(key) or \
|
||||
User.query.get_by_username(key) or \
|
||||
User.query.get_by_nickname(key)
|
||||
if user:
|
||||
cls.set(user)
|
||||
|
||||
return user
|
||||
|
||||
@classmethod
|
||||
def set(cls, user):
|
||||
cache.set(cls.PREFIX_ID.format(user.uid), user)
|
||||
cache.set(cls.PREFIX_NAME.format(user.username), user)
|
||||
cache.set(cls.PREFIX_NICK.format(user.nickname), user)
|
||||
|
||||
@classmethod
|
||||
def clean(cls, user):
|
||||
cache.delete(cls.PREFIX_ID.format(user.uid))
|
||||
cache.delete(cls.PREFIX_NAME.format(user.username))
|
||||
cache.delete(cls.PREFIX_NICK.format(user.nickname))
|
||||
|
||||
|
||||
class RoleCache(object):
|
||||
PREFIX_ID = "Role::id::{0}"
|
||||
PREFIX_NAME = "Role::app_id::{0}::name::{1}"
|
||||
|
||||
@classmethod
|
||||
def get_by_name(cls, app_id, name):
|
||||
role = cache.get(cls.PREFIX_NAME.format(app_id, name))
|
||||
if role is None:
|
||||
role = Role.get_by(app_id=app_id, name=name, first=True, to_dict=False)
|
||||
if role is not None:
|
||||
cache.set(cls.PREFIX_NAME.format(app_id, name), role)
|
||||
|
||||
return role
|
||||
|
||||
@classmethod
|
||||
def get(cls, rid):
|
||||
role = cache.get(cls.PREFIX_ID.format(rid))
|
||||
if role is None:
|
||||
role = Role.get_by_id(rid)
|
||||
if role is not None:
|
||||
cache.set(cls.PREFIX_ID.format(rid), role)
|
||||
|
||||
return role
|
||||
|
||||
@classmethod
|
||||
def clean(cls, rid):
|
||||
cache.delete(cls.PREFIX_ID.format(rid))
|
||||
|
||||
@classmethod
|
||||
def clean_by_name(cls, app_id, name):
|
||||
cache.delete(cls.PREFIX_NAME.format(app_id, name))
|
||||
|
||||
|
||||
class RoleRelationCache(object):
|
||||
PREFIX_PARENT = "RoleRelationParent::id::{0}"
|
||||
PREFIX_CHILDREN = "RoleRelationChildren::id::{0}"
|
||||
PREFIX_RESOURCES = "RoleRelationResources::id::{0}"
|
||||
|
||||
@classmethod
|
||||
def get_parent_ids(cls, rid):
|
||||
parent_ids = cache.get(cls.PREFIX_PARENT.format(rid))
|
||||
if not parent_ids:
|
||||
from api.lib.perm.acl.role import RoleRelationCRUD
|
||||
parent_ids = RoleRelationCRUD.get_parent_ids(rid)
|
||||
cache.set(cls.PREFIX_PARENT.format(rid), parent_ids, timeout=0)
|
||||
|
||||
return parent_ids
|
||||
|
||||
@classmethod
|
||||
def get_child_ids(cls, rid):
|
||||
child_ids = cache.get(cls.PREFIX_CHILDREN.format(rid))
|
||||
if not child_ids:
|
||||
from api.lib.perm.acl.role import RoleRelationCRUD
|
||||
child_ids = RoleRelationCRUD.get_child_ids(rid)
|
||||
cache.set(cls.PREFIX_CHILDREN.format(rid), child_ids, timeout=0)
|
||||
|
||||
return child_ids
|
||||
|
||||
@classmethod
|
||||
def get_resources(cls, rid):
|
||||
"""
|
||||
:param rid:
|
||||
:return: {id2perms: {resource_id: [perm,]}, group2perms: {group_id: [perm, ]}}
|
||||
"""
|
||||
resources = cache.get(cls.PREFIX_RESOURCES.format(rid))
|
||||
if not resources:
|
||||
from api.lib.perm.acl.role import RoleCRUD
|
||||
resources = RoleCRUD.get_resources(rid)
|
||||
cache.set(cls.PREFIX_RESOURCES.format(rid), resources, timeout=0)
|
||||
|
||||
return resources or {}
|
||||
|
||||
@classmethod
|
||||
def rebuild(cls, rid):
|
||||
cls.clean(rid)
|
||||
db.session.close()
|
||||
cls.get_parent_ids(rid)
|
||||
cls.get_child_ids(rid)
|
||||
cls.get_resources(rid)
|
||||
|
||||
@classmethod
|
||||
def clean(cls, rid):
|
||||
cache.delete(cls.PREFIX_PARENT.format(rid))
|
||||
cache.delete(cls.PREFIX_CHILDREN.format(rid))
|
||||
cache.delete(cls.PREFIX_RESOURCES.format(rid))
|
||||
|
||||
|
||||
class PermissionCache(object):
|
||||
PREFIX_ID = "Permission::id::{0}"
|
||||
PREFIX_NAME = "Permission::name::{0}"
|
||||
|
||||
@classmethod
|
||||
def get(cls, key):
|
||||
perm = cache.get(cls.PREFIX_ID.format(key))
|
||||
perm = perm or cache.get(cls.PREFIX_NAME.format(key))
|
||||
if perm is None:
|
||||
perm = Permission.get_by_id(key)
|
||||
perm = perm or Permission.get_by(name=key, first=True, to_dict=False)
|
||||
if perm is not None:
|
||||
cache.set(cls.PREFIX_ID.format(key), perm)
|
||||
|
||||
return perm
|
||||
|
||||
@classmethod
|
||||
def clean(cls, key):
|
||||
cache.delete(cls.PREFIX_ID.format(key))
|
||||
cache.delete(cls.PREFIX_NAME.format(key))
|
5
cmdb-api/api/lib/perm/acl/const.py
Normal file
5
cmdb-api/api/lib/perm/acl/const.py
Normal file
@@ -0,0 +1,5 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
from api.lib.cmdb.const import CMDB_QUEUE
|
||||
|
||||
ACL_QUEUE = CMDB_QUEUE
|
48
cmdb-api/api/lib/perm/acl/permission.py
Normal file
48
cmdb-api/api/lib/perm/acl/permission.py
Normal file
@@ -0,0 +1,48 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
from api.lib.perm.acl.cache import PermissionCache
|
||||
from api.lib.perm.acl.cache import RoleCache
|
||||
from api.lib.perm.acl.const import ACL_QUEUE
|
||||
from api.models.acl import RolePermission
|
||||
from api.tasks.acl import role_rebuild
|
||||
|
||||
|
||||
class PermissionCRUD(object):
|
||||
@staticmethod
|
||||
def get_all(resource_id=None, group_id=None):
|
||||
result = dict()
|
||||
if resource_id is not None:
|
||||
perms = RolePermission.get_by(resource_id=resource_id, to_dict=False)
|
||||
else:
|
||||
perms = RolePermission.get_by(group_id=group_id, to_dict=False)
|
||||
|
||||
for perm in perms:
|
||||
perm_dict = PermissionCache.get(perm.perm_id).to_dict()
|
||||
perm_dict.update(dict(rid=perm.rid))
|
||||
result.setdefault(RoleCache.get(perm.rid).name, []).append(perm_dict)
|
||||
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def grant(rid, perms, resource_id=None, group_id=None):
|
||||
for perm in perms:
|
||||
perm = PermissionCache.get(perm)
|
||||
existed = RolePermission.get_by(rid=rid, perm_id=perm.id, group_id=group_id, resource_id=resource_id)
|
||||
existed or RolePermission.create(rid=rid, perm_id=perm.id, group_id=group_id, resource_id=resource_id)
|
||||
|
||||
role_rebuild.apply_async(args=(rid,), queue=ACL_QUEUE)
|
||||
|
||||
@staticmethod
|
||||
def revoke(rid, perms, resource_id=None, group_id=None):
|
||||
for perm in perms:
|
||||
perm = PermissionCache.get(perm)
|
||||
existed = RolePermission.get_by(rid=rid,
|
||||
perm_id=perm.id,
|
||||
group_id=group_id,
|
||||
resource_id=resource_id,
|
||||
first=True,
|
||||
to_dict=False)
|
||||
existed and existed.soft_delete()
|
||||
|
||||
role_rebuild.apply_async(args=(rid,), queue=ACL_QUEUE)
|
@@ -4,11 +4,14 @@
|
||||
from flask import abort
|
||||
|
||||
from api.extensions import db
|
||||
from api.lib.perm.acl.const import ACL_QUEUE
|
||||
from api.models.acl import Permission
|
||||
from api.models.acl import Resource
|
||||
from api.models.acl import ResourceGroup
|
||||
from api.models.acl import ResourceGroupItems
|
||||
from api.models.acl import ResourceType
|
||||
from api.models.acl import RolePermission
|
||||
from api.tasks.acl import role_rebuild
|
||||
|
||||
|
||||
class ResourceTypeCRUD(object):
|
||||
@@ -20,15 +23,27 @@ class ResourceTypeCRUD(object):
|
||||
query = query.filter(ResourceType.name.ilike('%{0}%'.format(q)))
|
||||
|
||||
numfound = query.count()
|
||||
res = query.offset((page - 1) * page_size).limit(page_size)
|
||||
rt_ids = [i.id for i in res]
|
||||
perms = db.session.query(Permission).filter(Permission.deleted.is_(False)).filter(
|
||||
Permission.resource_type_id.in_(rt_ids))
|
||||
id2perms = dict()
|
||||
for perm in perms:
|
||||
id2perms.setdefault(perm.resource_type_id, []).append(perm.to_dict())
|
||||
|
||||
return numfound, query.offset((page - 1) * page_size).limit(page_size)
|
||||
return numfound, res, id2perms
|
||||
|
||||
@staticmethod
|
||||
def get_perms(rt_id):
|
||||
perms = Permission.get_by(resource_type_id=rt_id, to_dict=False)
|
||||
return [i.to_dict() for i in perms]
|
||||
|
||||
@classmethod
|
||||
def add(cls, app_id, name, perms):
|
||||
def add(cls, app_id, name, description, perms):
|
||||
ResourceType.get_by(name=name, app_id=app_id) and abort(
|
||||
400, "ResourceType <{0}> is already existed".format(name))
|
||||
|
||||
rt = ResourceType.create(name=name, app_id=app_id)
|
||||
rt = ResourceType.create(name=name, description=description, app_id=app_id)
|
||||
|
||||
cls.update_perms(rt.id, perms, app_id)
|
||||
|
||||
@@ -36,14 +51,16 @@ class ResourceTypeCRUD(object):
|
||||
|
||||
@classmethod
|
||||
def update(cls, rt_id, **kwargs):
|
||||
kwargs.pop('app_id', None)
|
||||
|
||||
rt = ResourceType.get_by_id(rt_id) or abort(404, "ResourceType <{0}> is not found".format(rt_id))
|
||||
if 'name' in kwargs:
|
||||
other = ResourceType.get_by(name=kwargs['name'], app_id=rt.app_id, to_dict=False, first=True)
|
||||
if other.id != rt_id:
|
||||
if other and other.id != rt_id:
|
||||
return abort(400, "ResourceType <{0}> is duplicated".format(kwargs['name']))
|
||||
|
||||
if 'perms' in kwargs:
|
||||
cls.update_perms(rt_id, kwargs['perms'], rt.app_id)
|
||||
cls.update_perms(rt_id, kwargs.pop('perms'), rt.app_id)
|
||||
|
||||
return rt.update(**kwargs)
|
||||
|
||||
@@ -51,6 +68,9 @@ class ResourceTypeCRUD(object):
|
||||
def delete(cls, rt_id):
|
||||
rt = ResourceType.get_by_id(rt_id) or abort(404, "ResourceType <{0}> is not found".format(rt_id))
|
||||
|
||||
if Resource.get_by(resource_type_id=rt_id):
|
||||
return abort(400, "At least one instance of this type exists and cannot be deleted")
|
||||
|
||||
cls.update_perms(rt_id, [], rt.app_id)
|
||||
|
||||
rt.soft_delete()
|
||||
@@ -92,7 +112,7 @@ class ResourceGroupCRUD(object):
|
||||
|
||||
@staticmethod
|
||||
def add(name, type_id, app_id):
|
||||
ResourceGroup.get(name=name, resource_type_id=type_id, app_id=app_id) and abort(
|
||||
ResourceGroup.get_by(name=name, resource_type_id=type_id, app_id=app_id) and abort(
|
||||
400, "ResourceGroup <{0}> is already existed".format(name))
|
||||
|
||||
return ResourceGroup.create(name=name, resource_type_id=type_id, app_id=app_id)
|
||||
@@ -120,23 +140,30 @@ class ResourceGroupCRUD(object):
|
||||
for item in items:
|
||||
item.soft_delete()
|
||||
|
||||
for i in RolePermission.get_by(group_id=rg_id, to_dict=False):
|
||||
i.soft_delete()
|
||||
role_rebuild.apply_async(args=(i.rid,), queue=ACL_QUEUE)
|
||||
|
||||
|
||||
class ResourceCRUD(object):
|
||||
@staticmethod
|
||||
def search(q, app_id, page=1, page_size=None):
|
||||
def search(q, app_id, resource_type_id=None, page=1, page_size=None):
|
||||
query = db.session.query(Resource).filter(
|
||||
Resource.deleted.is_(False)).filter(Resource.app_id == app_id)
|
||||
|
||||
if q:
|
||||
query = query.filter(Resource.name.ilike("%{0}%".format(q)))
|
||||
|
||||
if resource_type_id:
|
||||
query = query.filter(Resource.resource_type_id == resource_type_id)
|
||||
|
||||
numfound = query.count()
|
||||
|
||||
return numfound, query.offset((page - 1) * page_size).limit(page_size)
|
||||
|
||||
@staticmethod
|
||||
def add(name, type_id, app_id):
|
||||
Resource.get(name=name, resource_type_id=type_id, app_id=app_id) and abort(
|
||||
Resource.get_by(name=name, resource_type_id=type_id, app_id=app_id) and abort(
|
||||
400, "Resource <{0}> is already existed".format(name))
|
||||
|
||||
return Resource.create(name=name, resource_type_id=type_id, app_id=app_id)
|
||||
@@ -146,7 +173,7 @@ class ResourceCRUD(object):
|
||||
resource = Resource.get_by_id(_id) or abort(404, "Resource <{0}> is not found".format(_id))
|
||||
|
||||
other = Resource.get_by(name=name, resource_type_id=resource.resource_type_id, to_dict=False, first=True)
|
||||
if other.id != _id:
|
||||
if other and other.id != _id:
|
||||
return abort(400, "Resource <{0}> is duplicated".format(name))
|
||||
|
||||
return resource.update(name=name)
|
||||
@@ -156,3 +183,7 @@ class ResourceCRUD(object):
|
||||
resource = Resource.get_by_id(_id) or abort(404, "Resource <{0}> is not found".format(_id))
|
||||
|
||||
resource.soft_delete()
|
||||
|
||||
for i in RolePermission.get_by(resource_id=_id, to_dict=False):
|
||||
i.soft_delete()
|
||||
role_rebuild.apply_async(args=(i.rid,), queue=ACL_QUEUE)
|
@@ -1,6 +1,7 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
import six
|
||||
from flask import abort
|
||||
|
||||
from api.extensions import db
|
||||
@@ -9,6 +10,7 @@ from api.lib.perm.acl.cache import RoleRelationCache
|
||||
from api.lib.perm.acl.const import ACL_QUEUE
|
||||
from api.models.acl import Resource
|
||||
from api.models.acl import ResourceGroupItems
|
||||
from api.models.acl import ResourceType
|
||||
from api.models.acl import Role
|
||||
from api.models.acl import RolePermission
|
||||
from api.models.acl import RoleRelation
|
||||
@@ -16,75 +18,24 @@ from api.tasks.acl import role_rebuild
|
||||
|
||||
|
||||
class RoleRelationCRUD(object):
|
||||
pass
|
||||
|
||||
|
||||
class RoleCRUD(object):
|
||||
@staticmethod
|
||||
def search(q, app_id, page=1, page_size=None):
|
||||
query = db.session.query(Role).filter(Role.deleted.is_(False)).filter(
|
||||
Role.app_id == app_id).filter(Role.uid.is_(None))
|
||||
if q:
|
||||
query = query.filter(Role.name.ilike('%{0}%'.format(q)))
|
||||
def get_parents(rids=None, uids=None):
|
||||
rid2uid = dict()
|
||||
if uids is not None:
|
||||
uids = [uids] if isinstance(uids, six.integer_types) else uids
|
||||
rids = db.session.query(Role).filter(Role.deleted.is_(False)).filter(Role.uid.in_(uids))
|
||||
rid2uid = {i.id: i.uid for i in rids}
|
||||
rids = [i.id for i in rids]
|
||||
else:
|
||||
rids = [rids] if isinstance(rids, six.integer_types) else rids
|
||||
|
||||
numfound = query.count()
|
||||
|
||||
return numfound, query.offset((page - 1) * page_size).limit(page_size)
|
||||
|
||||
@staticmethod
|
||||
def add_role(name, app_id, is_app_admin=False, uid=None):
|
||||
Role.get_by(name=name, app_id=app_id) and abort(400, "Role <{0}> is already existed".format(name))
|
||||
|
||||
return Role.create(name=name,
|
||||
app_id=app_id,
|
||||
is_app_admin=is_app_admin,
|
||||
uid=uid)
|
||||
|
||||
@staticmethod
|
||||
def update_role(rid, **kwargs):
|
||||
role = Role.get_by_id(rid) or abort(404, "Role <{0}> does not exist".format(rid))
|
||||
|
||||
RoleCache.clean(rid)
|
||||
|
||||
return role.update(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def delete_role(cls, rid):
|
||||
role = Role.get_by_id(rid) or abort(404, "Role <{0}> does not exist".format(rid))
|
||||
|
||||
parent_ids = cls.get_parent_ids(rid)
|
||||
child_ids = cls.get_child_ids(rid)
|
||||
|
||||
for i in RoleRelation.get_by(parent_id=rid, to_dict=False):
|
||||
i.soft_delete()
|
||||
for i in RoleRelation.get_by(child_id=rid, to_dict=False):
|
||||
i.soft_delete()
|
||||
|
||||
for i in RolePermission.get_by(rid=rid, to_dict=False):
|
||||
i.soft_delete()
|
||||
|
||||
role_rebuild.apply_async(args=(parent_ids + child_ids,), queue=ACL_QUEUE)
|
||||
|
||||
RoleCache.clean(rid)
|
||||
RoleRelationCache.clean(rid)
|
||||
|
||||
role.soft_delete()
|
||||
|
||||
@staticmethod
|
||||
def get_resources(rid):
|
||||
res = RolePermission.get_by(rid=rid, to_dict=False)
|
||||
id2perms = dict(id2perms={}, group2perms={})
|
||||
res = db.session.query(RoleRelation).filter(
|
||||
RoleRelation.child_id.in_(rids)).filter(RoleRelation.deleted.is_(False))
|
||||
id2parents = {}
|
||||
for i in res:
|
||||
if i.resource_id:
|
||||
id2perms['id2perms'].setdefault(i.resource_id, []).append(i.perm.name)
|
||||
elif i.group_id:
|
||||
id2perms['group2perms'].setdefault(i.group_id, []).append(i.perm.name)
|
||||
id2parents.setdefault(rid2uid.get(i.child_id, i.child_id), []).append(RoleCache.get(i.parent_id).to_dict())
|
||||
|
||||
return id2perms
|
||||
|
||||
@staticmethod
|
||||
def get_group_ids(resource_id):
|
||||
return [i.group_id for i in ResourceGroupItems.get_by(resource_id, to_dict=False)]
|
||||
return id2parents
|
||||
|
||||
@staticmethod
|
||||
def get_parent_ids(rid):
|
||||
@@ -94,9 +45,9 @@ class RoleCRUD(object):
|
||||
|
||||
@staticmethod
|
||||
def get_child_ids(rid):
|
||||
res = RoleRelation.get_by(child_id=rid, to_dict=False)
|
||||
res = RoleRelation.get_by(parent_id=rid, to_dict=False)
|
||||
|
||||
return [i.parent_id for i in res]
|
||||
return [i.child_id for i in res]
|
||||
|
||||
@classmethod
|
||||
def recursive_parent_ids(cls, rid):
|
||||
@@ -127,17 +78,129 @@ class RoleCRUD(object):
|
||||
return all_child_ids
|
||||
|
||||
@classmethod
|
||||
def has_permission(cls, rid, resource_name, perm):
|
||||
resource = Resource.get_by(name=resource_name, first=True, to_dict=False)
|
||||
def add(cls, parent_id, child_id):
|
||||
RoleRelation.get_by(parent_id=parent_id, child_id=child_id) and abort(400, "It's already existed")
|
||||
|
||||
if parent_id in cls.recursive_child_ids(child_id):
|
||||
return abort(400, "Circulation inheritance!!!")
|
||||
|
||||
RoleRelationCache.clean(parent_id)
|
||||
RoleRelationCache.clean(child_id)
|
||||
|
||||
return RoleRelation.create(parent_id=parent_id, child_id=child_id)
|
||||
|
||||
@classmethod
|
||||
def delete(cls, _id):
|
||||
existed = RoleRelation.get_by_id(_id) or abort(400, "RoleRelation <{0}> does not exist".format(_id))
|
||||
|
||||
child_ids = cls.recursive_child_ids(existed.child_id)
|
||||
for child_id in child_ids:
|
||||
role_rebuild.apply_async(args=(child_id,), queue=ACL_QUEUE)
|
||||
|
||||
RoleRelationCache.clean(existed.parent_id)
|
||||
RoleRelationCache.clean(existed.child_id)
|
||||
|
||||
existed.soft_delete()
|
||||
|
||||
@classmethod
|
||||
def delete2(cls, parent_id, child_id):
|
||||
existed = RoleRelation.get_by(parent_id=parent_id, child_id=child_id, first=True, to_dict=False)
|
||||
existed or abort(400, "RoleRelation < {0} -> {1} > does not exist".format(parent_id, child_id))
|
||||
|
||||
child_ids = cls.recursive_child_ids(existed.child_id)
|
||||
for child_id in child_ids:
|
||||
role_rebuild.apply_async(args=(child_id,), queue=ACL_QUEUE)
|
||||
|
||||
RoleRelationCache.clean(existed.parent_id)
|
||||
RoleRelationCache.clean(existed.child_id)
|
||||
|
||||
existed.soft_delete()
|
||||
|
||||
|
||||
class RoleCRUD(object):
|
||||
@staticmethod
|
||||
def search(q, app_id, page=1, page_size=None, user_role=True):
|
||||
query = db.session.query(Role).filter(Role.deleted.is_(False))
|
||||
query = query.filter(Role.app_id == app_id).filter(Role.uid.is_(None))
|
||||
|
||||
if user_role:
|
||||
query1 = db.session.query(Role).filter(Role.deleted.is_(False)).filter(Role.uid.isnot(None))
|
||||
query = query.union(query1)
|
||||
|
||||
if q:
|
||||
query = query.filter(Role.name.ilike('%{0}%'.format(q)))
|
||||
|
||||
numfound = query.count()
|
||||
|
||||
return numfound, query.offset((page - 1) * page_size).limit(page_size)
|
||||
|
||||
@staticmethod
|
||||
def add_role(name, app_id=None, is_app_admin=False, uid=None):
|
||||
Role.get_by(name=name, app_id=app_id) and abort(400, "Role <{0}> is already existed".format(name))
|
||||
|
||||
return Role.create(name=name,
|
||||
app_id=app_id,
|
||||
is_app_admin=is_app_admin,
|
||||
uid=uid)
|
||||
|
||||
@staticmethod
|
||||
def update_role(rid, **kwargs):
|
||||
kwargs.pop('app_id', None)
|
||||
|
||||
role = Role.get_by_id(rid) or abort(404, "Role <{0}> does not exist".format(rid))
|
||||
|
||||
RoleCache.clean(rid)
|
||||
|
||||
return role.update(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def delete_role(cls, rid):
|
||||
role = Role.get_by_id(rid) or abort(404, "Role <{0}> does not exist".format(rid))
|
||||
|
||||
for i in RoleRelation.get_by(parent_id=rid, to_dict=False):
|
||||
i.soft_delete()
|
||||
for i in RoleRelation.get_by(child_id=rid, to_dict=False):
|
||||
i.soft_delete()
|
||||
|
||||
for i in RolePermission.get_by(rid=rid, to_dict=False):
|
||||
i.soft_delete()
|
||||
|
||||
role_rebuild.apply_async(args=(list(RoleRelationCRUD.recursive_child_ids(rid)), ), queue=ACL_QUEUE)
|
||||
|
||||
RoleCache.clean(rid)
|
||||
RoleRelationCache.clean(rid)
|
||||
|
||||
role.soft_delete()
|
||||
|
||||
@staticmethod
|
||||
def get_resources(rid):
|
||||
res = RolePermission.get_by(rid=rid, to_dict=False)
|
||||
id2perms = dict(id2perms={}, group2perms={})
|
||||
for i in res:
|
||||
if i.resource_id:
|
||||
id2perms['id2perms'].setdefault(i.resource_id, []).append(i.perm.name)
|
||||
elif i.group_id:
|
||||
id2perms['group2perms'].setdefault(i.group_id, []).append(i.perm.name)
|
||||
|
||||
return id2perms
|
||||
|
||||
@staticmethod
|
||||
def get_group_ids(resource_id):
|
||||
return [i.group_id for i in ResourceGroupItems.get_by(resource_id=resource_id, to_dict=False)]
|
||||
|
||||
@classmethod
|
||||
def has_permission(cls, rid, resource_name, resource_type, app_id, perm):
|
||||
resource_type = ResourceType.get_by(app_id=app_id, name=resource_type, first=True, to_dict=False)
|
||||
resource_type or abort(404, "ResourceType <{0}> is not found".format(resource_type))
|
||||
type_id = resource_type.id
|
||||
resource = Resource.get_by(name=resource_name, resource_type_id=type_id, first=True, to_dict=False)
|
||||
resource = resource or abort(403, "Resource <{0}> is not in ACL".format(resource_name))
|
||||
|
||||
parent_ids = cls.recursive_parent_ids(rid)
|
||||
parent_ids = RoleRelationCRUD.recursive_parent_ids(rid)
|
||||
|
||||
group_ids = cls.get_group_ids(resource.id)
|
||||
|
||||
for parent_id in parent_ids:
|
||||
id2perms = RoleRelationCache.get_resources(parent_id)
|
||||
|
||||
perms = id2perms['id2perms'].get(resource.id, [])
|
||||
if perms and {perm}.issubset(set(perms)):
|
||||
return True
|
||||
@@ -154,7 +217,7 @@ class RoleCRUD(object):
|
||||
resource = Resource.get_by(name=resource_name, first=True, to_dict=False)
|
||||
resource = resource or abort(403, "Resource <{0}> is not in ACL".format(resource_name))
|
||||
|
||||
parent_ids = cls.recursive_parent_ids(rid)
|
||||
parent_ids = RoleRelationCRUD.recursive_parent_ids(rid)
|
||||
group_ids = cls.get_group_ids(resource.id)
|
||||
|
||||
perms = []
|
85
cmdb-api/api/lib/perm/acl/user.py
Normal file
85
cmdb-api/api/lib/perm/acl/user.py
Normal file
@@ -0,0 +1,85 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
import random
|
||||
import string
|
||||
import uuid
|
||||
|
||||
from flask import abort
|
||||
from flask import g
|
||||
|
||||
from api.extensions import db
|
||||
from api.lib.perm.acl.cache import UserCache
|
||||
from api.lib.perm.acl.role import RoleCRUD
|
||||
from api.models.acl import Role
|
||||
from api.models.acl import User
|
||||
|
||||
|
||||
class UserCRUD(object):
|
||||
@staticmethod
|
||||
def search(q, page=1, page_size=None):
|
||||
query = db.session.query(User).filter(User.deleted.is_(False))
|
||||
if q:
|
||||
query = query.filter(User.username.ilike('%{0}%'.format(q)))
|
||||
|
||||
numfound = query.count()
|
||||
|
||||
return numfound, query.offset((page - 1) * page_size).limit(page_size)
|
||||
|
||||
@staticmethod
|
||||
def _gen_key_secret():
|
||||
key = uuid.uuid4().hex
|
||||
secret = ''.join(random.sample(string.ascii_letters + string.digits + '~!@#$%^&*?', 32))
|
||||
|
||||
return key, secret
|
||||
|
||||
@classmethod
|
||||
def add(cls, **kwargs):
|
||||
existed = User.get_by(username=kwargs['username'], email=kwargs['email'])
|
||||
existed and abort(400, "User <{0}> is already existed".format(kwargs['username']))
|
||||
|
||||
kwargs['nickname'] = kwargs.get('nickname') or kwargs['username']
|
||||
kwargs['block'] = 0
|
||||
kwargs['key'], kwargs['secret'] = cls._gen_key_secret()
|
||||
|
||||
user = User.create(**kwargs)
|
||||
|
||||
RoleCRUD.add_role(user.username, uid=user.uid)
|
||||
|
||||
return user
|
||||
|
||||
@staticmethod
|
||||
def update(uid, **kwargs):
|
||||
user = User.get_by(uid=uid, to_dict=False, first=True) or abort(404, "User <{0}> does not exist".format(uid))
|
||||
|
||||
if kwargs.get("username"):
|
||||
other = User.get_by(username=kwargs['username'], first=True, to_dict=False)
|
||||
if other is not None and other.uid != user.uid:
|
||||
return abort(400, "User <{0}> cannot be duplicated".format(kwargs['username']))
|
||||
|
||||
UserCache.clean(user)
|
||||
|
||||
if kwargs.get("username") and kwargs['username'] != user.username:
|
||||
role = Role.get_by(name=user.username, first=True, to_dict=False)
|
||||
if role is not None:
|
||||
RoleCRUD.update_role(role.id, **dict(name=kwargs['name']))
|
||||
|
||||
return user.update(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def reset_key_secret(cls):
|
||||
key, secret = cls._gen_key_secret()
|
||||
g.user.update(key=key, secret=secret)
|
||||
|
||||
return key, secret
|
||||
|
||||
@classmethod
|
||||
def delete(cls, uid):
|
||||
if uid == g.user.uid:
|
||||
return abort(400, "You cannot delete yourself")
|
||||
|
||||
user = User.get_by(uid=uid, to_dict=False, first=True) or abort(404, "User <{0}> does not exist".format(uid))
|
||||
|
||||
UserCache.clean(user)
|
||||
|
||||
user.soft_delete()
|
@@ -13,8 +13,8 @@ from flask import request
|
||||
from flask import session
|
||||
from flask_login import login_user
|
||||
|
||||
from api.models.account import User
|
||||
from api.models.account import UserCache
|
||||
from api.lib.perm.acl.cache import UserCache
|
||||
from api.models.acl import User
|
||||
|
||||
|
||||
def _auth_with_key():
|
||||
@@ -47,12 +47,13 @@ def _auth_with_token():
|
||||
|
||||
try:
|
||||
token = auth_headers
|
||||
data = jwt.decode(token, current_app.config['SECRET_KEY'])
|
||||
data = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
|
||||
user = User.query.filter_by(email=data['sub']).first()
|
||||
if not user:
|
||||
return False
|
||||
|
||||
login_user(user)
|
||||
g.user = user
|
||||
return True
|
||||
except jwt.ExpiredSignatureError:
|
||||
return False
|
170
cmdb-api/api/lib/utils.py
Normal file
170
cmdb-api/api/lib/utils.py
Normal file
@@ -0,0 +1,170 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
import json
|
||||
|
||||
import redis
|
||||
import six
|
||||
from elasticsearch import Elasticsearch
|
||||
from flask import current_app
|
||||
|
||||
|
||||
def get_page(page):
|
||||
try:
|
||||
page = int(page)
|
||||
except ValueError:
|
||||
page = 1
|
||||
return page if page >= 1 else 1
|
||||
|
||||
|
||||
def get_page_size(page_size):
|
||||
if page_size == "all":
|
||||
return page_size
|
||||
|
||||
try:
|
||||
page_size = int(page_size)
|
||||
except (ValueError, TypeError):
|
||||
page_size = current_app.config.get("DEFAULT_PAGE_COUNT")
|
||||
return page_size if page_size >= 1 else current_app.config.get("DEFAULT_PAGE_COUNT")
|
||||
|
||||
|
||||
def handle_arg_list(arg):
|
||||
if isinstance(arg, six.string_types) and arg.startswith('['):
|
||||
return json.loads(arg)
|
||||
|
||||
return list(filter(lambda x: x != "", arg.strip().split(","))) if isinstance(arg, six.string_types) else arg
|
||||
|
||||
|
||||
class BaseEnum(object):
|
||||
_ALL_ = set() # type: Set[str]
|
||||
|
||||
@classmethod
|
||||
def is_valid(cls, item):
|
||||
return item in cls.all()
|
||||
|
||||
@classmethod
|
||||
def all(cls):
|
||||
if not cls._ALL_:
|
||||
cls._ALL_ = {
|
||||
getattr(cls, attr)
|
||||
for attr in dir(cls)
|
||||
if not attr.startswith("_") and not callable(getattr(cls, attr))
|
||||
}
|
||||
return cls._ALL_
|
||||
|
||||
|
||||
class RedisHandler(object):
|
||||
def __init__(self, flask_app=None):
|
||||
self.flask_app = flask_app
|
||||
self.r = None
|
||||
|
||||
def init_app(self, app):
|
||||
self.flask_app = app
|
||||
config = self.flask_app.config
|
||||
try:
|
||||
pool = redis.ConnectionPool(
|
||||
max_connections=config.get("REDIS_MAX_CONN"),
|
||||
host=config.get("CACHE_REDIS_HOST"),
|
||||
port=config.get("CACHE_REDIS_PORT"),
|
||||
db=config.get("REDIS_DB"))
|
||||
self.r = redis.Redis(connection_pool=pool)
|
||||
except Exception as e:
|
||||
current_app.logger.warning(str(e))
|
||||
current_app.logger.error("init redis connection failed")
|
||||
|
||||
def get(self, key_ids, prefix):
|
||||
try:
|
||||
value = self.r.hmget(prefix, key_ids)
|
||||
except Exception as e:
|
||||
current_app.logger.error("get redis error, {0}".format(str(e)))
|
||||
return
|
||||
return value
|
||||
|
||||
def _set(self, obj, prefix):
|
||||
try:
|
||||
self.r.hmset(prefix, obj)
|
||||
except Exception as e:
|
||||
current_app.logger.error("set redis error, {0}".format(str(e)))
|
||||
|
||||
def create_or_update(self, obj, prefix):
|
||||
self._set(obj, prefix)
|
||||
|
||||
def delete(self, key_id, prefix):
|
||||
try:
|
||||
ret = self.r.hdel(prefix, key_id)
|
||||
if not ret:
|
||||
current_app.logger.warn("[{0}] is not in redis".format(key_id))
|
||||
except Exception as e:
|
||||
current_app.logger.error("delete redis key error, {0}".format(str(e)))
|
||||
|
||||
|
||||
class ESHandler(object):
|
||||
def __init__(self, flask_app=None):
|
||||
self.flask_app = flask_app
|
||||
self.es = None
|
||||
self.index = "cmdb"
|
||||
|
||||
def init_app(self, app):
|
||||
self.flask_app = app
|
||||
config = self.flask_app.config
|
||||
self.es = Elasticsearch(config.get("ES_HOST"))
|
||||
if not self.es.indices.exists(index=self.index):
|
||||
self.es.indices.create(index=self.index)
|
||||
|
||||
def update_mapping(self, field, value_type, other):
|
||||
body = {
|
||||
"properties": {
|
||||
field: {"type": value_type},
|
||||
}}
|
||||
body['properties'][field].update(other)
|
||||
|
||||
self.es.indices.put_mapping(
|
||||
index=self.index,
|
||||
body=body
|
||||
)
|
||||
|
||||
def get_index_id(self, ci_id):
|
||||
query = {
|
||||
'query': {
|
||||
'match': {'ci_id': ci_id}
|
||||
},
|
||||
}
|
||||
res = self.es.search(index=self.index, body=query)
|
||||
if res['hits']['hits']:
|
||||
return res['hits']['hits'][-1].get('_id')
|
||||
|
||||
def create(self, body):
|
||||
return self.es.index(index=self.index, body=body).get("_id")
|
||||
|
||||
def update(self, ci_id, body):
|
||||
_id = self.get_index_id(ci_id)
|
||||
|
||||
if _id:
|
||||
return self.es.index(index=self.index, id=_id, body=body).get("_id")
|
||||
|
||||
def create_or_update(self, ci_id, body):
|
||||
try:
|
||||
self.update(ci_id, body) or self.create(body)
|
||||
except KeyError:
|
||||
self.create(body)
|
||||
|
||||
def delete(self, ci_id):
|
||||
try:
|
||||
_id = self.get_index_id(ci_id)
|
||||
except KeyError:
|
||||
return
|
||||
|
||||
if _id:
|
||||
self.es.delete(index=self.index, id=_id)
|
||||
|
||||
def read(self, query, filter_path=None):
|
||||
filter_path = filter_path or []
|
||||
if filter_path:
|
||||
filter_path.append('hits.total')
|
||||
|
||||
res = self.es.search(index=self.index, body=query, filter_path=filter_path)
|
||||
if res['hits'].get('hits'):
|
||||
return res['hits']['total']['value'], \
|
||||
[i['_source'] for i in res['hits']['hits']], \
|
||||
res.get("aggregations", {})
|
||||
else:
|
||||
return 0, [], {}
|
@@ -1,6 +1,5 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
from .account import User
|
||||
from .cmdb import *
|
||||
from .acl import *
|
217
cmdb-api/api/models/acl.py
Normal file
217
cmdb-api/api/models/acl.py
Normal file
@@ -0,0 +1,217 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
from datetime import datetime
|
||||
|
||||
import ldap
|
||||
from flask import current_app
|
||||
from flask_sqlalchemy import BaseQuery
|
||||
|
||||
from api.extensions import db
|
||||
from api.lib.database import CRUDModel
|
||||
from api.lib.database import Model
|
||||
from api.lib.database import SoftDeleteMixin
|
||||
|
||||
|
||||
class App(Model):
|
||||
__tablename__ = "acl_apps"
|
||||
|
||||
name = db.Column(db.String(64), index=True)
|
||||
description = db.Column(db.Text)
|
||||
app_id = db.Column(db.Text)
|
||||
secret_key = db.Column(db.Text)
|
||||
|
||||
|
||||
class UserQuery(BaseQuery):
|
||||
def _join(self, *args, **kwargs):
|
||||
super(UserQuery, self)._join(*args, **kwargs)
|
||||
|
||||
def authenticate(self, login, password):
|
||||
user = self.filter(db.or_(User.username == login,
|
||||
User.email == login)).filter(User.deleted.is_(False)).first()
|
||||
if user:
|
||||
current_app.logger.info(user)
|
||||
authenticated = user.check_password(password)
|
||||
else:
|
||||
authenticated = False
|
||||
|
||||
return user, authenticated
|
||||
|
||||
def authenticate_with_key(self, key, secret, args, path):
|
||||
user = self.filter(User.key == key).filter(User.deleted.is_(False)).filter(User.block == 0).first()
|
||||
if not user:
|
||||
return None, False
|
||||
if user and hashlib.sha1('{0}{1}{2}'.format(
|
||||
path, user.secret, "".join(args)).encode("utf-8")).hexdigest() == secret:
|
||||
authenticated = True
|
||||
else:
|
||||
authenticated = False
|
||||
|
||||
return user, authenticated
|
||||
|
||||
def authenticate_with_ldap(self, username, password):
|
||||
ldap_conn = ldap.initialize(current_app.config.get('LDAP_SERVER'))
|
||||
ldap_conn.protocol_version = 3
|
||||
ldap_conn.set_option(ldap.OPT_REFERRALS, 0)
|
||||
if '@' in username:
|
||||
who = '{0}@{1}'.format(username.split('@')[0], current_app.config.get('LDAP_DOMAIN'))
|
||||
else:
|
||||
who = '{0}@{1}'.format(username, current_app.config.get('LDAP_DOMAIN'))
|
||||
|
||||
username = username.split('@')[0]
|
||||
user = self.get_by_username(username)
|
||||
try:
|
||||
|
||||
if not password:
|
||||
raise ldap.INVALID_CREDENTIALS
|
||||
|
||||
ldap_conn.simple_bind_s(who, password)
|
||||
|
||||
if not user:
|
||||
from api.lib.perm.acl.user import UserCRUD
|
||||
user = UserCRUD.add(username=username, email=who)
|
||||
|
||||
return user, True
|
||||
except ldap.INVALID_CREDENTIALS:
|
||||
return user, False
|
||||
|
||||
def search(self, key):
|
||||
query = self.filter(db.or_(User.email == key,
|
||||
User.nickname.ilike('%' + key + '%'),
|
||||
User.username.ilike('%' + key + '%'))).filter(User.deleted.is_(False))
|
||||
return query
|
||||
|
||||
def get_by_username(self, username):
|
||||
user = self.filter(User.username == username).filter(User.deleted.is_(False)).first()
|
||||
|
||||
return user
|
||||
|
||||
def get_by_nickname(self, nickname):
|
||||
user = self.filter(User.nickname == nickname).filter(User.deleted.is_(False)).first()
|
||||
|
||||
return user
|
||||
|
||||
def get(self, uid):
|
||||
user = self.filter(User.uid == uid).filter(User.deleted.is_(False)).first()
|
||||
|
||||
return copy.deepcopy(user)
|
||||
|
||||
|
||||
class User(CRUDModel, SoftDeleteMixin):
|
||||
__tablename__ = 'users'
|
||||
# __bind_key__ = "user"
|
||||
query_class = UserQuery
|
||||
|
||||
uid = db.Column(db.Integer, primary_key=True, autoincrement=True)
|
||||
username = db.Column(db.String(32), unique=True)
|
||||
nickname = db.Column(db.String(20), nullable=True)
|
||||
department = db.Column(db.String(20))
|
||||
catalog = db.Column(db.String(64))
|
||||
email = db.Column(db.String(100), unique=True, nullable=False)
|
||||
mobile = db.Column(db.String(14), unique=True)
|
||||
_password = db.Column("password", db.String(80))
|
||||
key = db.Column(db.String(32), nullable=False)
|
||||
secret = db.Column(db.String(32), nullable=False)
|
||||
date_joined = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
last_login = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
block = db.Column(db.Boolean, default=False)
|
||||
has_logined = db.Column(db.Boolean, default=False)
|
||||
wx_id = db.Column(db.String(32))
|
||||
avatar = db.Column(db.String(128))
|
||||
|
||||
def __str__(self):
|
||||
return self.username
|
||||
|
||||
def is_active(self):
|
||||
return not self.block
|
||||
|
||||
def get_id(self):
|
||||
return self.uid
|
||||
|
||||
@staticmethod
|
||||
def is_authenticated():
|
||||
return True
|
||||
|
||||
def _get_password(self):
|
||||
return self._password
|
||||
|
||||
def _set_password(self, password):
|
||||
self._password = hashlib.md5(password.encode('utf-8')).hexdigest()
|
||||
|
||||
password = db.synonym("_password", descriptor=property(_get_password, _set_password))
|
||||
|
||||
def check_password(self, password):
|
||||
if self.password is None:
|
||||
return False
|
||||
return self.password == password
|
||||
|
||||
|
||||
class Role(Model):
|
||||
__tablename__ = "acl_roles"
|
||||
|
||||
name = db.Column(db.Text, nullable=False)
|
||||
is_app_admin = db.Column(db.Boolean, default=False)
|
||||
app_id = db.Column(db.Integer, db.ForeignKey("acl_apps.id"))
|
||||
uid = db.Column(db.Integer, db.ForeignKey("users.uid"))
|
||||
|
||||
|
||||
class RoleRelation(Model):
|
||||
__tablename__ = "acl_role_relations"
|
||||
|
||||
parent_id = db.Column(db.Integer, db.ForeignKey('acl_roles.id'))
|
||||
child_id = db.Column(db.Integer, db.ForeignKey('acl_roles.id'))
|
||||
|
||||
|
||||
class ResourceType(Model):
|
||||
__tablename__ = "acl_resource_types"
|
||||
|
||||
name = db.Column(db.String(64), index=True)
|
||||
description = db.Column(db.Text)
|
||||
app_id = db.Column(db.Integer, db.ForeignKey('acl_apps.id'))
|
||||
|
||||
|
||||
class ResourceGroup(Model):
|
||||
__tablename__ = "acl_resource_groups"
|
||||
|
||||
name = db.Column(db.String(64), index=True, nullable=False)
|
||||
resource_type_id = db.Column(db.Integer, db.ForeignKey("acl_resource_types.id"))
|
||||
|
||||
app_id = db.Column(db.Integer, db.ForeignKey('acl_apps.id'))
|
||||
|
||||
|
||||
class Resource(Model):
|
||||
__tablename__ = "acl_resources"
|
||||
|
||||
name = db.Column(db.String(128), nullable=False)
|
||||
resource_type_id = db.Column(db.Integer, db.ForeignKey("acl_resource_types.id"))
|
||||
|
||||
app_id = db.Column(db.Integer, db.ForeignKey("acl_apps.id"))
|
||||
|
||||
|
||||
class ResourceGroupItems(Model):
|
||||
__tablename__ = "acl_resource_group_items"
|
||||
|
||||
group_id = db.Column(db.Integer, db.ForeignKey('acl_resource_groups.id'), nullable=False)
|
||||
resource_id = db.Column(db.Integer, db.ForeignKey('acl_resources.id'), nullable=False)
|
||||
|
||||
|
||||
class Permission(Model):
|
||||
__tablename__ = "acl_permissions"
|
||||
|
||||
name = db.Column(db.String(64), nullable=False)
|
||||
resource_type_id = db.Column(db.Integer, db.ForeignKey("acl_resource_types.id"))
|
||||
|
||||
app_id = db.Column(db.Integer, db.ForeignKey("acl_apps.id"))
|
||||
|
||||
|
||||
class RolePermission(Model):
|
||||
__tablename__ = "acl_role_permissions"
|
||||
|
||||
rid = db.Column(db.Integer, db.ForeignKey('acl_roles.id'))
|
||||
resource_id = db.Column(db.Integer, db.ForeignKey('acl_resources.id'))
|
||||
group_id = db.Column(db.Integer, db.ForeignKey('acl_resource_groups.id'))
|
||||
perm_id = db.Column(db.Integer, db.ForeignKey('acl_permissions.id'))
|
||||
|
||||
perm = db.relationship("Permission", backref='acl_role_permissions.perm_id')
|
@@ -4,6 +4,9 @@
|
||||
import datetime
|
||||
|
||||
from api.extensions import db
|
||||
from api.lib.cmdb.const import CIStatusEnum
|
||||
from api.lib.cmdb.const import OperateType
|
||||
from api.lib.cmdb.const import ValueTypeEnum
|
||||
from api.lib.database import Model
|
||||
|
||||
|
||||
@@ -12,13 +15,13 @@ from api.lib.database import Model
|
||||
class RelationType(Model):
|
||||
__tablename__ = "c_relation_types"
|
||||
|
||||
name = db.Column(db.String(16), index=True)
|
||||
name = db.Column(db.String(16), index=True, nullable=False)
|
||||
|
||||
|
||||
class CITypeGroup(Model):
|
||||
__tablename__ = "c_ci_type_groups"
|
||||
|
||||
name = db.Column(db.String(32))
|
||||
name = db.Column(db.String(32), nullable=False)
|
||||
|
||||
|
||||
class CITypeGroupItem(Model):
|
||||
@@ -32,12 +35,12 @@ class CITypeGroupItem(Model):
|
||||
class CIType(Model):
|
||||
__tablename__ = "c_ci_types"
|
||||
|
||||
name = db.Column(db.String(32))
|
||||
alias = db.Column(db.String(32))
|
||||
name = db.Column(db.String(32), nullable=False)
|
||||
alias = db.Column(db.String(32), nullable=False)
|
||||
unique_id = db.Column(db.Integer, db.ForeignKey("c_attributes.id"), nullable=False)
|
||||
enabled = db.Column(db.Boolean, default=True, nullable=False)
|
||||
is_attached = db.Column(db.Boolean, default=False, nullable=False)
|
||||
icon_url = db.Column(db.String(256))
|
||||
icon_url = db.Column(db.String(256), default='', nullable=False)
|
||||
order = db.Column(db.SmallInteger, default=0, nullable=False)
|
||||
|
||||
unique_key = db.relationship("Attribute", backref="c_ci_types.unique_id")
|
||||
@@ -58,16 +61,9 @@ class CITypeRelation(Model):
|
||||
class Attribute(Model):
|
||||
__tablename__ = "c_attributes"
|
||||
|
||||
INT = "0"
|
||||
FLOAT = "1"
|
||||
TEXT = "2"
|
||||
DATETIME = "3"
|
||||
DATE = "4"
|
||||
TIME = "5"
|
||||
|
||||
name = db.Column(db.String(32), nullable=False)
|
||||
alias = db.Column(db.String(32), nullable=False)
|
||||
value_type = db.Column(db.Enum(INT, FLOAT, TEXT, DATETIME, DATE, TIME), default=TEXT, nullable=False)
|
||||
value_type = db.Column(db.Enum(*ValueTypeEnum.all()), default=ValueTypeEnum.TEXT, nullable=False)
|
||||
|
||||
is_choice = db.Column(db.Boolean, default=False)
|
||||
is_list = db.Column(db.Boolean, default=False)
|
||||
@@ -93,7 +89,7 @@ class CITypeAttribute(Model):
|
||||
class CITypeAttributeGroup(Model):
|
||||
__tablename__ = "c_ci_type_attribute_groups"
|
||||
|
||||
name = db.Column(db.String(64))
|
||||
name = db.Column(db.String(64), nullable=False)
|
||||
type_id = db.Column(db.Integer, db.ForeignKey("c_ci_types.id"), nullable=False)
|
||||
order = db.Column(db.SmallInteger, default=0)
|
||||
|
||||
@@ -111,11 +107,8 @@ class CITypeAttributeGroupItem(Model):
|
||||
class CI(Model):
|
||||
__tablename__ = "c_cis"
|
||||
|
||||
REVIEW = "0"
|
||||
VALIDATE = "1"
|
||||
|
||||
type_id = db.Column(db.Integer, db.ForeignKey("c_ci_types.id"), nullable=False)
|
||||
status = db.Column(db.Enum(REVIEW, VALIDATE, name="status"))
|
||||
status = db.Column(db.Enum(*CIStatusEnum.all(), name="status"))
|
||||
heartbeat = db.Column(db.DateTime, default=lambda: datetime.datetime.now())
|
||||
|
||||
ci_type = db.relationship("CIType", backref="c_cis.type_id")
|
||||
@@ -257,24 +250,31 @@ class CIValueDateTime(Model):
|
||||
attr = db.relationship("Attribute", backref="c_value_datetime.attr_id")
|
||||
|
||||
|
||||
class CIValueJson(Model):
|
||||
__tablename__ = "c_value_json"
|
||||
|
||||
ci_id = db.Column(db.Integer, db.ForeignKey('c_cis.id'), nullable=False)
|
||||
attr_id = db.Column(db.Integer, db.ForeignKey('c_attributes.id'), nullable=False)
|
||||
value = db.Column(db.JSON, nullable=False)
|
||||
|
||||
ci = db.relationship("CI", backref="c_value_json.ci_id")
|
||||
attr = db.relationship("Attribute", backref="c_value_json.attr_id")
|
||||
|
||||
|
||||
# history
|
||||
class OperationRecord(Model):
|
||||
__tablename__ = "c_records"
|
||||
|
||||
uid = db.Column(db.Integer, index=True, nullable=False)
|
||||
origin = db.Column(db.String(32))
|
||||
ticket_id = db.Column(db.String(32))
|
||||
origin = db.Column(db.String(32), nullable=True)
|
||||
ticket_id = db.Column(db.String(32), nullable=True)
|
||||
reason = db.Column(db.Text)
|
||||
|
||||
|
||||
class AttributeHistory(Model):
|
||||
__tablename__ = "c_attribute_histories"
|
||||
|
||||
ADD = "0"
|
||||
DELETE = "1"
|
||||
UPDATE = "2"
|
||||
|
||||
operate_type = db.Column(db.Enum(ADD, DELETE, UPDATE, name="operate_type"))
|
||||
operate_type = db.Column(db.Enum(*OperateType.all(), name="operate_type"))
|
||||
record_id = db.Column(db.Integer, db.ForeignKey("c_records.id"), nullable=False)
|
||||
ci_id = db.Column(db.Integer, index=True, nullable=False)
|
||||
attr_id = db.Column(db.Integer, index=True)
|
||||
@@ -285,10 +285,7 @@ class AttributeHistory(Model):
|
||||
class CIRelationHistory(Model):
|
||||
__tablename__ = "c_relation_histories"
|
||||
|
||||
ADD = "0"
|
||||
DELETE = "1"
|
||||
|
||||
operate_type = db.Column(db.Enum(ADD, DELETE, name="operate_type"))
|
||||
operate_type = db.Column(db.Enum(OperateType.ADD, OperateType.DELETE, name="operate_type"))
|
||||
record_id = db.Column(db.Integer, db.ForeignKey("c_records.id"), nullable=False)
|
||||
first_ci_id = db.Column(db.Integer)
|
||||
second_ci_id = db.Column(db.Integer)
|
||||
@@ -320,6 +317,5 @@ class PreferenceTreeView(Model):
|
||||
class PreferenceRelationView(Model):
|
||||
__tablename__ = "c_preference_relation_views"
|
||||
|
||||
name = db.Column(db.String(8), index=True, nullable=False)
|
||||
parent_id = db.Column(db.Integer, db.ForeignKey("c_ci_types.id"), nullable=False)
|
||||
child_id = db.Column(db.Integer, db.ForeignKey("c_ci_types.id"), nullable=False)
|
||||
name = db.Column(db.String(64), index=True, nullable=False)
|
||||
cr_ids = db.Column(db.TEXT) # [{parent_id: x, child_id: y}] TODO: JSON
|
@@ -13,4 +13,4 @@ def role_rebuild(rids):
|
||||
for rid in rids:
|
||||
RoleRelationCache.rebuild(rid)
|
||||
|
||||
current_app.logger.info("%d rebuild.........." % rids)
|
||||
current_app.logger.info("Role {0} rebuild..........".format(rids))
|
94
cmdb-api/api/tasks/cmdb.py
Normal file
94
cmdb-api/api/tasks/cmdb.py
Normal file
@@ -0,0 +1,94 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
import json
|
||||
import time
|
||||
|
||||
from flask import current_app
|
||||
|
||||
import api.lib.cmdb.ci
|
||||
from api.extensions import celery
|
||||
from api.extensions import db
|
||||
from api.extensions import es
|
||||
from api.extensions import rd
|
||||
from api.lib.cmdb.cache import CITypeAttributesCache
|
||||
from api.lib.cmdb.const import CMDB_QUEUE
|
||||
from api.lib.cmdb.const import REDIS_PREFIX_CI
|
||||
from api.lib.cmdb.const import REDIS_PREFIX_CI_RELATION
|
||||
from api.models.cmdb import CIRelation
|
||||
|
||||
|
||||
@celery.task(name="cmdb.ci_cache", queue=CMDB_QUEUE)
|
||||
def ci_cache(ci_id):
|
||||
time.sleep(0.01)
|
||||
db.session.close()
|
||||
|
||||
m = api.lib.cmdb.ci.CIManager()
|
||||
ci = m.get_ci_by_id_from_db(ci_id, need_children=False, use_master=False)
|
||||
if current_app.config.get("USE_ES"):
|
||||
es.create_or_update(ci_id, ci)
|
||||
else:
|
||||
rd.create_or_update({ci_id: json.dumps(ci)}, REDIS_PREFIX_CI)
|
||||
|
||||
current_app.logger.info("{0} flush..........".format(ci_id))
|
||||
|
||||
|
||||
@celery.task(name="cmdb.ci_delete", queue=CMDB_QUEUE)
|
||||
def ci_delete(ci_id):
|
||||
current_app.logger.info(ci_id)
|
||||
|
||||
if current_app.config.get("USE_ES"):
|
||||
es.delete(ci_id)
|
||||
else:
|
||||
rd.delete(ci_id, REDIS_PREFIX_CI)
|
||||
|
||||
current_app.logger.info("{0} delete..........".format(ci_id))
|
||||
|
||||
|
||||
@celery.task(name="cmdb.ci_relation_cache", queue=CMDB_QUEUE)
|
||||
def ci_relation_cache(parent_id, child_id):
|
||||
db.session.close()
|
||||
|
||||
children = rd.get([parent_id], REDIS_PREFIX_CI_RELATION)[0]
|
||||
children = json.loads(children) if children is not None else {}
|
||||
|
||||
cr = CIRelation.get_by(first_ci_id=parent_id, second_ci_id=child_id, first=True, to_dict=False)
|
||||
if str(child_id) not in children:
|
||||
children[str(child_id)] = cr.second_ci.type_id
|
||||
|
||||
rd.create_or_update({parent_id: json.dumps(children)}, REDIS_PREFIX_CI_RELATION)
|
||||
|
||||
current_app.logger.info("ADD ci relation cache: {0} -> {1}".format(parent_id, child_id))
|
||||
|
||||
|
||||
@celery.task(name="cmdb.ci_relation_delete", queue=CMDB_QUEUE)
|
||||
def ci_relation_delete(parent_id, child_id):
|
||||
children = rd.get([parent_id], REDIS_PREFIX_CI_RELATION)[0]
|
||||
children = json.loads(children) if children is not None else {}
|
||||
|
||||
if str(child_id) in children:
|
||||
children.pop(str(child_id))
|
||||
|
||||
rd.create_or_update({parent_id: json.dumps(children)}, REDIS_PREFIX_CI_RELATION)
|
||||
|
||||
current_app.logger.info("DELETE ci relation cache: {0} -> {1}".format(parent_id, child_id))
|
||||
|
||||
|
||||
@celery.task(name="cmdb.ci_type_attribute_order_rebuild", queue=CMDB_QUEUE)
|
||||
def ci_type_attribute_order_rebuild(type_id):
|
||||
current_app.logger.info('rebuild attribute order')
|
||||
db.session.remove()
|
||||
|
||||
from api.lib.cmdb.ci_type import CITypeAttributeGroupManager
|
||||
|
||||
attrs = CITypeAttributesCache.get(type_id)
|
||||
id2attr = {attr.attr_id: attr for attr in attrs}
|
||||
|
||||
res = CITypeAttributeGroupManager.get_by_type_id(type_id, True)
|
||||
order = 0
|
||||
for group in res:
|
||||
for _attr in group.get('attributes'):
|
||||
if order != id2attr.get(_attr['id']) and id2attr.get(_attr['id']):
|
||||
id2attr.get(_attr['id']).update(order=order)
|
||||
|
||||
order += 1
|
@@ -6,8 +6,7 @@ from flask import Blueprint
|
||||
from flask_restful import Api
|
||||
|
||||
from api.resource import register_resources
|
||||
from .permission import GetResourcesView, HasPermissionView, GetUserInfoView
|
||||
from .account import LoginView, LogoutView
|
||||
from api.views.account import LoginView, LogoutView
|
||||
|
||||
HERE = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
@@ -17,13 +16,6 @@ account_rest = Api(blueprint_account)
|
||||
account_rest.add_resource(LoginView, LoginView.url_prefix)
|
||||
account_rest.add_resource(LogoutView, LogoutView.url_prefix)
|
||||
|
||||
# permission
|
||||
blueprint_perm_v01 = Blueprint('permission_api', __name__, url_prefix='/api/v1/perms')
|
||||
perm_rest = Api(blueprint_perm_v01)
|
||||
perm_rest.add_resource(GetResourcesView, GetResourcesView.url_prefix)
|
||||
perm_rest.add_resource(HasPermissionView, HasPermissionView.url_prefix)
|
||||
perm_rest.add_resource(GetUserInfoView, GetUserInfoView.url_prefix)
|
||||
|
||||
|
||||
# cmdb
|
||||
blueprint_cmdb_v01 = Blueprint('cmdb_api_v01', __name__, url_prefix='/api/v0.1')
|
||||
@@ -32,6 +24,6 @@ register_resources(os.path.join(HERE, "cmdb"), rest)
|
||||
|
||||
|
||||
# acl
|
||||
blueprint_acl_v1 = Blueprint('cmdb_acl_v1', __name__, url_prefix='/api/v1/acl')
|
||||
blueprint_acl_v1 = Blueprint('acl_api_v1', __name__, url_prefix='/api/v1/acl')
|
||||
rest = Api(blueprint_acl_v1)
|
||||
register_resources(os.path.join(HERE, "acl"), rest)
|
@@ -6,12 +6,15 @@ import jwt
|
||||
from flask import abort
|
||||
from flask import current_app
|
||||
from flask import request
|
||||
from flask import session
|
||||
from flask_login import login_user, logout_user
|
||||
|
||||
from api.lib.decorator import args_required
|
||||
from api.lib.perm.auth import auth_abandoned
|
||||
from api.models.account import User
|
||||
from api.models.acl import User, Role
|
||||
from api.resource import APIView
|
||||
from api.lib.perm.acl.role import RoleRelationCRUD
|
||||
from api.lib.perm.acl.cache import RoleCache
|
||||
|
||||
|
||||
class LoginView(APIView):
|
||||
@@ -23,7 +26,12 @@ class LoginView(APIView):
|
||||
def post(self):
|
||||
username = request.values.get("username") or request.values.get("email")
|
||||
password = request.values.get("password")
|
||||
user, authenticated = User.query.authenticate(username, password)
|
||||
if current_app.config.get('AUTH_WITH_LDAP'):
|
||||
user, authenticated = User.query.authenticate_with_ldap(username, password)
|
||||
else:
|
||||
user, authenticated = User.query.authenticate(username, password)
|
||||
if not user:
|
||||
return abort(403, "User <{0}> does not exist".format(username))
|
||||
if not authenticated:
|
||||
return abort(403, "invalid username or password")
|
||||
|
||||
@@ -35,6 +43,18 @@ class LoginView(APIView):
|
||||
'exp': datetime.datetime.now() + datetime.timedelta(minutes=24 * 60 * 7)},
|
||||
current_app.config['SECRET_KEY'])
|
||||
|
||||
role = Role.get_by(uid=user.uid, first=True, to_dict=False)
|
||||
if role:
|
||||
parent_ids = RoleRelationCRUD.recursive_parent_ids(role.id)
|
||||
parent_roles = [RoleCache.get(i).name for i in parent_ids]
|
||||
else:
|
||||
parent_roles = []
|
||||
session["acl"] = dict(uid=user.uid,
|
||||
avatar=user.avatar,
|
||||
userName=user.username,
|
||||
nickName=user.nickname,
|
||||
parentRoles=parent_roles)
|
||||
|
||||
return self.jsonify(token=token.decode())
|
||||
|
||||
|
1
cmdb-api/api/views/acl/__init__.py
Normal file
1
cmdb-api/api/views/acl/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# -*- coding:utf-8 -*-
|
40
cmdb-api/api/views/acl/permission.py
Normal file
40
cmdb-api/api/views/acl/permission.py
Normal file
@@ -0,0 +1,40 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
from flask import request
|
||||
|
||||
from api.lib.decorator import args_required
|
||||
from api.lib.perm.acl.permission import PermissionCRUD
|
||||
from api.lib.utils import handle_arg_list
|
||||
from api.resource import APIView
|
||||
|
||||
|
||||
class ResourcePermissionView(APIView):
|
||||
url_prefix = ("/resources/<int:resource_id>/permissions", "/resource_groups/<int:group_id>/permissions")
|
||||
|
||||
def get(self, resource_id=None, group_id=None):
|
||||
return self.jsonify(PermissionCRUD.get_all(resource_id, group_id))
|
||||
|
||||
|
||||
class RolePermissionGrantView(APIView):
|
||||
url_prefix = ('/roles/<int:rid>/resources/<int:resource_id>/grant',
|
||||
'/roles/<int:rid>/resource_groups/<int:group_id>/grant')
|
||||
|
||||
@args_required('perms')
|
||||
def post(self, rid, resource_id=None, group_id=None):
|
||||
perms = handle_arg_list(request.values.get("perms"))
|
||||
PermissionCRUD.grant(rid, perms, resource_id=resource_id, group_id=group_id)
|
||||
|
||||
return self.jsonify(rid=rid, resource_id=resource_id, group_id=group_id, perms=perms)
|
||||
|
||||
|
||||
class RolePermissionRevokeView(APIView):
|
||||
url_prefix = ('/roles/<int:rid>/resources/<int:resource_id>/revoke',
|
||||
'/roles/<int:rid>/resource_groups/<int:group_id>/revoke')
|
||||
|
||||
@args_required('perms')
|
||||
def post(self, rid, resource_id=None, group_id=None):
|
||||
perms = handle_arg_list(request.values.get("perms"))
|
||||
PermissionCRUD.revoke(rid, perms, resource_id=resource_id, group_id=group_id)
|
||||
|
||||
return self.jsonify(rid=rid, resource_id=resource_id, group_id=group_id, perms=perms)
|
@@ -3,25 +3,80 @@
|
||||
from flask import request
|
||||
|
||||
from api.lib.decorator import args_required
|
||||
from api.lib.perm.acl import validate_app
|
||||
from api.lib.perm.acl.resource import ResourceCRUD
|
||||
from api.lib.perm.acl.resource import ResourceGroupCRUD
|
||||
from api.lib.perm.acl.resource import ResourceTypeCRUD
|
||||
from api.lib.utils import get_page
|
||||
from api.lib.utils import get_page_size
|
||||
from api.lib.utils import handle_arg_list
|
||||
from api.resource import APIView
|
||||
|
||||
|
||||
class ResourceView(APIView):
|
||||
url_prefix = ("/resources", "/resources/<int:resource_id>")
|
||||
class ResourceTypeView(APIView):
|
||||
url_prefix = ("/resource_types", "/resource_types/<int:type_id>")
|
||||
|
||||
@args_required('app_id')
|
||||
@validate_app
|
||||
def get(self):
|
||||
page = get_page(request.values.get("page", 1))
|
||||
page_size = get_page_size(request.values.get("page_size"))
|
||||
q = request.values.get('q')
|
||||
app_id = request.values.get('app_id')
|
||||
|
||||
numfound, res = ResourceCRUD.search(q, app_id, page, page_size)
|
||||
numfound, res, id2perms = ResourceTypeCRUD.search(q, app_id, page, page_size)
|
||||
|
||||
return self.jsonify(numfound=numfound,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
groups=[i.to_dict() for i in res],
|
||||
id2perms=id2perms)
|
||||
|
||||
@args_required('name')
|
||||
@args_required('app_id')
|
||||
@args_required('perms')
|
||||
@validate_app
|
||||
def post(self):
|
||||
name = request.values.get('name')
|
||||
app_id = request.values.get('app_id')
|
||||
description = request.values.get('description', '')
|
||||
perms = request.values.get('perms')
|
||||
|
||||
rt = ResourceTypeCRUD.add(app_id, name, description, perms)
|
||||
|
||||
return self.jsonify(rt.to_dict())
|
||||
|
||||
def put(self, type_id):
|
||||
rt = ResourceTypeCRUD.update(type_id, **request.values)
|
||||
|
||||
return self.jsonify(rt.to_dict())
|
||||
|
||||
def delete(self, type_id):
|
||||
ResourceTypeCRUD.delete(type_id)
|
||||
|
||||
return self.jsonify(type_id=type_id)
|
||||
|
||||
|
||||
class ResourceTypePermsView(APIView):
|
||||
url_prefix = "/resource_types/<int:type_id>/perms"
|
||||
|
||||
def get(self, type_id):
|
||||
return self.jsonify(ResourceTypeCRUD.get_perms(type_id))
|
||||
|
||||
|
||||
class ResourceView(APIView):
|
||||
url_prefix = ("/resources", "/resources/<int:resource_id>")
|
||||
|
||||
@args_required('app_id')
|
||||
@validate_app
|
||||
def get(self):
|
||||
page = get_page(request.values.get("page", 1))
|
||||
page_size = get_page_size(request.values.get("page_size"))
|
||||
q = request.values.get('q')
|
||||
resource_type_id = request.values.get('resource_type_id')
|
||||
app_id = request.values.get('app_id')
|
||||
|
||||
numfound, res = ResourceCRUD.search(q, app_id, resource_type_id, page, page_size)
|
||||
|
||||
return self.jsonify(numfound=numfound,
|
||||
page=page,
|
||||
@@ -31,6 +86,7 @@ class ResourceView(APIView):
|
||||
@args_required('name')
|
||||
@args_required('type_id')
|
||||
@args_required('app_id')
|
||||
@validate_app
|
||||
def post(self):
|
||||
name = request.values.get('name')
|
||||
type_id = request.values.get('type_id')
|
||||
@@ -57,6 +113,8 @@ class ResourceView(APIView):
|
||||
class ResourceGroupView(APIView):
|
||||
url_prefix = ("/resource_groups", "/resource_groups/<int:group_id>")
|
||||
|
||||
@args_required('app_id')
|
||||
@validate_app
|
||||
def get(self):
|
||||
page = get_page(request.values.get("page", 1))
|
||||
page_size = get_page_size(request.values.get("page_size"))
|
||||
@@ -73,6 +131,7 @@ class ResourceGroupView(APIView):
|
||||
@args_required('name')
|
||||
@args_required('type_id')
|
||||
@args_required('app_id')
|
||||
@validate_app
|
||||
def post(self):
|
||||
name = request.values.get('name')
|
||||
type_id = request.values.get('type_id')
|
@@ -1,9 +1,12 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
from flask import current_app
|
||||
from flask import request
|
||||
|
||||
from api.lib.decorator import args_required
|
||||
from api.lib.perm.acl import validate_app
|
||||
from api.lib.perm.acl.role import RoleCRUD
|
||||
from api.lib.perm.acl.role import RoleRelationCRUD
|
||||
from api.lib.utils import get_page
|
||||
from api.lib.utils import get_page_size
|
||||
from api.resource import APIView
|
||||
@@ -13,21 +16,28 @@ class RoleView(APIView):
|
||||
url_prefix = ("/roles", "/roles/<int:rid>")
|
||||
|
||||
@args_required('app_id')
|
||||
@validate_app
|
||||
def get(self):
|
||||
page = get_page(request.values.get("page", 1))
|
||||
page_size = get_page_size(request.values.get("page_size"))
|
||||
q = request.values.get('q')
|
||||
app_id = request.values.get('app_id')
|
||||
user_role = request.values.get('user_role', True)
|
||||
user_role = True if user_role in current_app.config.get("BOOL_TRUE") else False
|
||||
|
||||
numfound, roles = RoleCRUD.search(q, app_id, page, page_size)
|
||||
numfound, roles = RoleCRUD.search(q, app_id, page, page_size, user_role)
|
||||
|
||||
id2parents = RoleRelationCRUD.get_parents([i.id for i in roles])
|
||||
|
||||
return self.jsonify(numfound=numfound,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
id2parents=id2parents,
|
||||
roles=[i.to_dict() for i in roles])
|
||||
|
||||
@args_required('name')
|
||||
@args_required('app_id')
|
||||
@validate_app
|
||||
def post(self):
|
||||
name = request.values.get('name')
|
||||
app_id = request.values.get('app_id')
|
||||
@@ -46,3 +56,22 @@ class RoleView(APIView):
|
||||
RoleCRUD.delete_role(rid)
|
||||
|
||||
return self.jsonify(rid=rid)
|
||||
|
||||
|
||||
class RoleRelationView(APIView):
|
||||
url_prefix = "/roles/<int:child_id>/parents"
|
||||
|
||||
@args_required('parent_id')
|
||||
def post(self, child_id):
|
||||
parent_id = request.values.get('parent_id')
|
||||
res = RoleRelationCRUD.add(parent_id, child_id)
|
||||
|
||||
return self.jsonify(res.to_dict())
|
||||
|
||||
@args_required('parent_id')
|
||||
def delete(self, child_id):
|
||||
parent_id = request.values.get('parent_id')
|
||||
|
||||
RoleRelationCRUD.delete2(parent_id, child_id)
|
||||
|
||||
return self.jsonify(parent_id=parent_id, child_id=child_id)
|
78
cmdb-api/api/views/acl/user.py
Normal file
78
cmdb-api/api/views/acl/user.py
Normal file
@@ -0,0 +1,78 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
from flask import request
|
||||
from flask import session
|
||||
from flask_login import current_user
|
||||
|
||||
from api.lib.decorator import args_required
|
||||
from api.lib.perm.acl.role import RoleRelationCRUD
|
||||
from api.lib.perm.acl.user import UserCRUD
|
||||
from api.lib.utils import get_page
|
||||
from api.lib.utils import get_page_size
|
||||
from api.resource import APIView
|
||||
|
||||
|
||||
class GetUserInfoView(APIView):
|
||||
url_prefix = "/users/info"
|
||||
|
||||
def get(self):
|
||||
name = session.get("CAS_USERNAME") or current_user.nickname
|
||||
role = dict(permissions=session.get("acl", {}).get("parentRoles", []))
|
||||
avatar = current_user.avatar
|
||||
|
||||
return self.jsonify(result=dict(name=name,
|
||||
role=role,
|
||||
avatar=avatar))
|
||||
|
||||
|
||||
class UserView(APIView):
|
||||
url_prefix = ("/users", "/users/<int:uid>")
|
||||
|
||||
def get(self):
|
||||
page = get_page(request.values.get('page', 1))
|
||||
page_size = get_page_size(request.values.get('page_size'))
|
||||
q = request.values.get("q")
|
||||
numfound, users = UserCRUD.search(q, page, page_size)
|
||||
id2parents = RoleRelationCRUD.get_parents(uids=[i.uid for i in users])
|
||||
|
||||
users = [i.to_dict() for i in users]
|
||||
for u in users:
|
||||
u.pop('password', None)
|
||||
u.pop('key', None)
|
||||
u.pop('secret', None)
|
||||
|
||||
return self.jsonify(numfound=numfound,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
id2parents=id2parents,
|
||||
users=users)
|
||||
|
||||
@args_required('username')
|
||||
@args_required('email')
|
||||
def post(self):
|
||||
user = UserCRUD.add(**request.values)
|
||||
|
||||
return self.jsonify(user.to_dict())
|
||||
|
||||
def put(self, uid):
|
||||
user = UserCRUD.update(uid, **request.values)
|
||||
|
||||
return self.jsonify(user.to_dict())
|
||||
|
||||
def delete(self, uid):
|
||||
UserCRUD.delete(uid)
|
||||
|
||||
return self.jsonify(uid=uid)
|
||||
|
||||
|
||||
class UserResetKeySecretView(APIView):
|
||||
url_prefix = "/users/reset_key_secret"
|
||||
|
||||
def post(self):
|
||||
key, secret = UserCRUD.reset_key_secret()
|
||||
|
||||
return self.jsonify(key=key, secret=secret)
|
||||
|
||||
def put(self):
|
||||
return self.post()
|
@@ -10,10 +10,11 @@ from flask import request
|
||||
from api.lib.cmdb.cache import CITypeCache
|
||||
from api.lib.cmdb.ci import CIManager
|
||||
from api.lib.cmdb.const import ExistPolicy
|
||||
from api.lib.cmdb.const import ResourceType, PermEnum
|
||||
from api.lib.cmdb.const import ResourceTypeEnum, PermEnum
|
||||
from api.lib.cmdb.const import RetKey
|
||||
from api.lib.cmdb.search import Search
|
||||
from api.lib.cmdb.search import SearchError
|
||||
from api.lib.cmdb.search.ci.db.search import Search as SearchFromDB
|
||||
from api.lib.cmdb.search.ci.es.search import Search as SearchFromES
|
||||
from api.lib.perm.acl.acl import has_perm_from_args
|
||||
from api.lib.perm.auth import auth_abandoned
|
||||
from api.lib.utils import get_page
|
||||
@@ -72,7 +73,7 @@ class CIView(APIView):
|
||||
ci_dict[k] = v.strip() if isinstance(v, six.string_types) else v
|
||||
return ci_dict
|
||||
|
||||
@has_perm_from_args("ci_type", ResourceType.CI, PermEnum.ADD)
|
||||
@has_perm_from_args("ci_type", ResourceTypeEnum.CI, PermEnum.ADD, lambda x: CITypeCache.get(x).name)
|
||||
def post(self):
|
||||
ci_type = request.values.get("ci_type")
|
||||
_no_attribute_policy = request.values.get("_no_attribute_policy", ExistPolicy.IGNORE)
|
||||
@@ -86,7 +87,7 @@ class CIView(APIView):
|
||||
_no_attribute_policy=_no_attribute_policy, **ci_dict)
|
||||
return self.jsonify(ci_id=ci_id)
|
||||
|
||||
@has_perm_from_args("ci_id", ResourceType.CI, PermEnum.UPDATE, CIManager.get_type_name)
|
||||
@has_perm_from_args("ci_id", ResourceTypeEnum.CI, PermEnum.UPDATE, CIManager.get_type_name)
|
||||
def put(self, ci_id=None):
|
||||
args = request.values
|
||||
ci_type = args.get("ci_type")
|
||||
@@ -103,7 +104,7 @@ class CIView(APIView):
|
||||
**ci_dict)
|
||||
return self.jsonify(ci_id=ci_id)
|
||||
|
||||
@has_perm_from_args("ci_id", ResourceType.CI, PermEnum.DELETE, CIManager.get_type_name)
|
||||
@has_perm_from_args("ci_id", ResourceTypeEnum.CI, PermEnum.DELETE, CIManager.get_type_name)
|
||||
def delete(self, ci_id):
|
||||
manager = CIManager()
|
||||
manager.delete(ci_id)
|
||||
@@ -125,13 +126,13 @@ class CISearchView(APIView):
|
||||
def get(self):
|
||||
"""@params: q: query statement
|
||||
fl: filter by column
|
||||
count: the number of ci
|
||||
count/page_size: the number of ci
|
||||
ret_key: id, name, alias
|
||||
facet: statistic
|
||||
"""
|
||||
|
||||
page = get_page(request.values.get("page", 1))
|
||||
count = get_page_size(request.values.get("count"))
|
||||
count = get_page_size(request.values.get("count") or request.values.get("page_size"))
|
||||
|
||||
query = request.values.get('q', "")
|
||||
fl = handle_arg_list(request.values.get('fl', ""))
|
||||
@@ -139,19 +140,17 @@ class CISearchView(APIView):
|
||||
if ret_key not in (RetKey.NAME, RetKey.ALIAS, RetKey.ID):
|
||||
ret_key = RetKey.NAME
|
||||
facet = handle_arg_list(request.values.get("facet", ""))
|
||||
fl = list(filter(lambda x: x != "", fl))
|
||||
facet = list(filter(lambda x: x != "", facet))
|
||||
sort = request.values.get("sort")
|
||||
|
||||
start = time.time()
|
||||
s = Search(query, fl, facet, page, ret_key, count, sort)
|
||||
if current_app.config.get("USE_ES"):
|
||||
s = SearchFromES(query, fl, facet, page, ret_key, count, sort)
|
||||
else:
|
||||
s = SearchFromDB(query, fl, facet, page, ret_key, count, sort)
|
||||
try:
|
||||
response, counter, total, page, numfound, facet = s.search()
|
||||
except SearchError as e:
|
||||
return abort(400, str(e))
|
||||
except Exception as e:
|
||||
current_app.logger.error(str(e))
|
||||
return abort(500, "search unknown error")
|
||||
current_app.logger.debug("search time is :{0}".format(time.time() - start))
|
||||
return self.jsonify(numfound=numfound,
|
||||
total=total,
|
||||
@@ -164,7 +163,7 @@ class CISearchView(APIView):
|
||||
class CIUnique(APIView):
|
||||
url_prefix = "/ci/<int:ci_id>/unique"
|
||||
|
||||
@has_perm_from_args("ci_id", ResourceType.CI, PermEnum.UPDATE, CIManager.get_type_name)
|
||||
@has_perm_from_args("ci_id", ResourceTypeEnum.CI, PermEnum.UPDATE, CIManager.get_type_name)
|
||||
def put(self, ci_id):
|
||||
params = request.values
|
||||
unique_name = params.keys()[0]
|
162
cmdb-api/api/views/cmdb/ci_relation.py
Normal file
162
cmdb-api/api/views/cmdb/ci_relation.py
Normal file
@@ -0,0 +1,162 @@
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
|
||||
import time
|
||||
|
||||
from flask import abort
|
||||
from flask import current_app
|
||||
from flask import request
|
||||
|
||||
from api.lib.cmdb.cache import RelationTypeCache
|
||||
from api.lib.cmdb.ci import CIRelationManager
|
||||
from api.lib.cmdb.search import SearchError
|
||||
from api.lib.cmdb.search.ci_relation.search import Search
|
||||
from api.lib.decorator import args_required
|
||||
from api.lib.perm.auth import auth_abandoned
|
||||
from api.lib.utils import get_page
|
||||
from api.lib.utils import get_page_size
|
||||
from api.lib.utils import handle_arg_list
|
||||
from api.resource import APIView
|
||||
|
||||
|
||||
class CIRelationSearchView(APIView):
|
||||
url_prefix = ("/ci_relations/s", "/ci_relations/search")
|
||||
|
||||
@auth_abandoned
|
||||
def get(self):
|
||||
"""@params: q: query statement
|
||||
fl: filter by column
|
||||
count: the number of ci
|
||||
root_id: ci id
|
||||
level: default is 1
|
||||
facet: statistic
|
||||
"""
|
||||
|
||||
page = get_page(request.values.get("page", 1))
|
||||
count = get_page_size(request.values.get("count") or request.values.get("page_size"))
|
||||
|
||||
root_id = request.values.get('root_id')
|
||||
level = list(map(int, handle_arg_list(request.values.get('level', '1'))))
|
||||
|
||||
query = request.values.get('q', "")
|
||||
fl = handle_arg_list(request.values.get('fl', ""))
|
||||
facet = handle_arg_list(request.values.get("facet", ""))
|
||||
sort = request.values.get("sort")
|
||||
|
||||
start = time.time()
|
||||
s = Search(root_id, level, query, fl, facet, page, count, sort)
|
||||
try:
|
||||
response, counter, total, page, numfound, facet = s.search()
|
||||
except SearchError as e:
|
||||
return abort(400, str(e))
|
||||
current_app.logger.debug("search time is :{0}".format(time.time() - start))
|
||||
|
||||
return self.jsonify(numfound=numfound,
|
||||
total=total,
|
||||
page=page,
|
||||
facet=facet,
|
||||
counter=counter,
|
||||
result=response)
|
||||
|
||||
|
||||
class CIRelationStatisticsView(APIView):
|
||||
url_prefix = "/ci_relations/statistics"
|
||||
|
||||
@auth_abandoned
|
||||
def get(self):
|
||||
root_ids = list(map(int, handle_arg_list(request.values.get('root_ids'))))
|
||||
level = request.values.get('level', 1)
|
||||
type_ids = set(map(int, handle_arg_list(request.values.get('type_ids', []))))
|
||||
|
||||
start = time.time()
|
||||
s = Search(root_ids, level)
|
||||
try:
|
||||
result = s.statistics(type_ids)
|
||||
except SearchError as e:
|
||||
return abort(400, str(e))
|
||||
current_app.logger.debug("search time is :{0}".format(time.time() - start))
|
||||
|
||||
return self.jsonify(result)
|
||||
|
||||
|
||||
class GetSecondCIsView(APIView):
|
||||
url_prefix = "/ci_relations/<int:first_ci_id>/second_cis"
|
||||
|
||||
def get(self, first_ci_id):
|
||||
page = get_page(request.values.get("page", 1))
|
||||
count = get_page_size(request.values.get("count"))
|
||||
relation_type = request.values.get("relation_type")
|
||||
try:
|
||||
relation_type_id = RelationTypeCache.get(relation_type).id if relation_type else None
|
||||
except AttributeError:
|
||||
return abort(400, "invalid relation type <{0}>".format(relation_type))
|
||||
|
||||
manager = CIRelationManager()
|
||||
numfound, total, second_cis = manager.get_second_cis(
|
||||
first_ci_id, page=page, per_page=count, relation_type_id=relation_type_id)
|
||||
|
||||
return self.jsonify(numfound=numfound,
|
||||
total=total,
|
||||
page=page,
|
||||
second_cis=second_cis)
|
||||
|
||||
|
||||
class GetFirstCIsView(APIView):
|
||||
url_prefix = "/ci_relations/<int:second_ci_id>/first_cis"
|
||||
|
||||
def get(self, second_ci_id):
|
||||
page = get_page(request.values.get("page", 1))
|
||||
count = get_page_size(request.values.get("count"))
|
||||
|
||||
manager = CIRelationManager()
|
||||
numfound, total, first_cis = manager.get_first_cis(second_ci_id, per_page=count, page=page)
|
||||
|
||||
return self.jsonify(numfound=numfound,
|
||||
total=total,
|
||||
page=page,
|
||||
first_cis=first_cis)
|
||||
|
||||
|
||||
class CIRelationView(APIView):
|
||||
url_prefix = "/ci_relations/<int:first_ci_id>/<int:second_ci_id>"
|
||||
|
||||
def post(self, first_ci_id, second_ci_id):
|
||||
manager = CIRelationManager()
|
||||
res = manager.add(first_ci_id, second_ci_id)
|
||||
|
||||
return self.jsonify(cr_id=res)
|
||||
|
||||
def delete(self, first_ci_id, second_ci_id):
|
||||
manager = CIRelationManager()
|
||||
manager.delete_2(first_ci_id, second_ci_id)
|
||||
|
||||
return self.jsonify(message="CIType Relation is deleted")
|
||||
|
||||
|
||||
class DeleteCIRelationView(APIView):
|
||||
url_prefix = "/ci_relations/<int:cr_id>"
|
||||
|
||||
def delete(self, cr_id):
|
||||
manager = CIRelationManager()
|
||||
manager.delete(cr_id)
|
||||
|
||||
return self.jsonify(message="CIType Relation is deleted")
|
||||
|
||||
|
||||
class BatchCreateOrUpdateCIRelationView(APIView):
|
||||
url_prefix = "/ci_relations/batch"
|
||||
|
||||
@args_required('ci_ids')
|
||||
@args_required('parents')
|
||||
def post(self):
|
||||
ci_ids = request.values.get('ci_ids')
|
||||
parents = request.values.get('parents')
|
||||
|
||||
CIRelationManager.batch_update(ci_ids, parents)
|
||||
|
||||
return self.jsonify(code=200)
|
||||
|
||||
@args_required('ci_ids')
|
||||
@args_required('parents')
|
||||
def put(self):
|
||||
return self.post()
|
@@ -164,6 +164,34 @@ class CITypeAttributeView(APIView):
|
||||
return self.jsonify(attributes=attr_id_list)
|
||||
|
||||
|
||||
class CITypeAttributeTransferView(APIView):
|
||||
url_prefix = "/ci_types/<int:type_id>/attributes/transfer"
|
||||
|
||||
@args_required('from')
|
||||
@args_required('to')
|
||||
def post(self, type_id):
|
||||
_from = request.values.get('from') # {'attr_id': xx, 'group_id': xx}
|
||||
_to = request.values.get('to') # {'group_id': xx, 'order': xxx}
|
||||
|
||||
CITypeAttributeManager.transfer(type_id, _from, _to)
|
||||
|
||||
return self.jsonify(code=200)
|
||||
|
||||
|
||||
class CITypeAttributeGroupTransferView(APIView):
|
||||
url_prefix = "/ci_types/<int:type_id>/attribute_groups/transfer"
|
||||
|
||||
@args_required('from')
|
||||
@args_required('to')
|
||||
def post(self, type_id):
|
||||
_from = request.values.get('from') # group_id
|
||||
_to = request.values.get('to') # group_id
|
||||
|
||||
CITypeAttributeGroupManager.transfer(type_id, _from, _to)
|
||||
|
||||
return self.jsonify(code=200)
|
||||
|
||||
|
||||
class CITypeAttributeGroupView(APIView):
|
||||
url_prefix = ("/ci_types/<int:type_id>/attribute_groups",
|
||||
"/ci_types/attribute_groups/<int:group_id>")
|
@@ -25,18 +25,26 @@ class GetParentsView(APIView):
|
||||
|
||||
|
||||
class CITypeRelationView(APIView):
|
||||
url_prefix = "/ci_type_relations/<int:parent_id>/<int:child_id>"
|
||||
url_prefix = ("/ci_type_relations", "/ci_type_relations/<int:parent_id>/<int:child_id>")
|
||||
|
||||
@role_required(RoleEnum.CONFIG)
|
||||
def get(self):
|
||||
res = CITypeRelationManager.get()
|
||||
|
||||
return self.jsonify(res)
|
||||
|
||||
@role_required(RoleEnum.CONFIG)
|
||||
@args_required("relation_type_id")
|
||||
def post(self, parent_id, child_id):
|
||||
relation_type_id = request.values.get("relation_type_id")
|
||||
ctr_id = CITypeRelationManager.add(parent_id, child_id, relation_type_id)
|
||||
|
||||
return self.jsonify(ctr_id=ctr_id)
|
||||
|
||||
@role_required(RoleEnum.CONFIG)
|
||||
def delete(self, parent_id, child_id):
|
||||
CITypeRelationManager.delete_2(parent_id, child_id)
|
||||
|
||||
return self.jsonify(code=200, parent_id=parent_id, child_id=child_id)
|
||||
|
||||
|
||||
@@ -46,4 +54,5 @@ class CITypeRelationDelete2View(APIView):
|
||||
@role_required(RoleEnum.CONFIG)
|
||||
def delete(self, ctr_id):
|
||||
CITypeRelationManager.delete(ctr_id)
|
||||
|
||||
return self.jsonify(code=200, ctr_id=ctr_id)
|
@@ -4,10 +4,11 @@
|
||||
from flask import request
|
||||
|
||||
from api.lib.cmdb.ci_type import CITypeManager
|
||||
from api.lib.cmdb.const import ResourceType, PermEnum
|
||||
from api.lib.cmdb.const import ResourceTypeEnum, PermEnum, RoleEnum
|
||||
from api.lib.cmdb.preference import PreferenceManager
|
||||
from api.lib.decorator import args_required
|
||||
from api.lib.perm.acl.acl import has_perm_from_args
|
||||
from api.lib.perm.acl.acl import role_required
|
||||
from api.lib.utils import handle_arg_list
|
||||
from api.resource import APIView
|
||||
|
||||
@@ -18,6 +19,7 @@ class PreferenceShowCITypesView(APIView):
|
||||
def get(self):
|
||||
instance = request.values.get("instance")
|
||||
tree = request.values.get("tree")
|
||||
|
||||
return self.jsonify(PreferenceManager.get_types(instance, tree))
|
||||
|
||||
|
||||
@@ -26,21 +28,23 @@ class PreferenceShowAttributesView(APIView):
|
||||
|
||||
def get(self, id_or_name):
|
||||
is_subscribed, attributes = PreferenceManager.get_show_attributes(id_or_name)
|
||||
|
||||
return self.jsonify(attributes=attributes, is_subscribed=is_subscribed)
|
||||
|
||||
@has_perm_from_args("id_or_name", ResourceType.CI, PermEnum.READ, CITypeManager.get_name_by_id)
|
||||
@has_perm_from_args("id_or_name", ResourceTypeEnum.CI, PermEnum.READ, CITypeManager.get_name_by_id)
|
||||
@args_required("attr")
|
||||
def post(self, id_or_name):
|
||||
id_or_name = int(id_or_name)
|
||||
attr_list = handle_arg_list(request.values.get("attr", ""))
|
||||
orders = list(range(len(attr_list)))
|
||||
PreferenceManager.create_or_update_show_attributes(id_or_name, list(zip(attr_list, orders)))
|
||||
|
||||
return self.jsonify(type_id=id_or_name,
|
||||
attr_order=list(zip(attr_list, orders)))
|
||||
|
||||
@has_perm_from_args("id_or_name", ResourceType.CI, PermEnum.READ, CITypeManager.get_name_by_id)
|
||||
@has_perm_from_args("id_or_name", ResourceTypeEnum.CI, PermEnum.READ, CITypeManager.get_name_by_id)
|
||||
def put(self, id_or_name):
|
||||
self.post(id_or_name)
|
||||
return self.post(id_or_name)
|
||||
|
||||
|
||||
class PreferenceTreeApiView(APIView):
|
||||
@@ -49,40 +53,46 @@ class PreferenceTreeApiView(APIView):
|
||||
def get(self):
|
||||
return self.jsonify(PreferenceManager.get_tree_view())
|
||||
|
||||
@has_perm_from_args("type_id", ResourceType.CI, PermEnum.READ, CITypeManager.get_name_by_id)
|
||||
@has_perm_from_args("type_id", ResourceTypeEnum.CI, PermEnum.READ, CITypeManager.get_name_by_id)
|
||||
@args_required("type_id")
|
||||
@args_required("levels")
|
||||
def post(self):
|
||||
type_id = request.values.get("type_id")
|
||||
levels = handle_arg_list(request.values.get("levels"))
|
||||
res = PreferenceManager.create_or_update_tree_view(type_id, levels)
|
||||
|
||||
return self.jsonify(res and res.to_dict() or {})
|
||||
|
||||
def put(self):
|
||||
self.post()
|
||||
return self.post()
|
||||
|
||||
|
||||
class PreferenceRelationApiView(APIView):
|
||||
url_prefix = "/preference/relation/view"
|
||||
|
||||
def get(self):
|
||||
return self.jsonify(PreferenceManager.get_relation_view())
|
||||
views, id2type, name2id = PreferenceManager.get_relation_view()
|
||||
|
||||
@has_perm_from_args("parent_id", ResourceType.CI, PermEnum.READ, CITypeManager.get_name_by_id)
|
||||
@has_perm_from_args("child_id", ResourceType.CI, PermEnum.READ, CITypeManager.get_name_by_id)
|
||||
return self.jsonify(views=views, id2type=id2type, name2id=name2id)
|
||||
|
||||
@role_required(RoleEnum.CONFIG)
|
||||
@args_required("name")
|
||||
@args_required("cr_ids")
|
||||
def post(self):
|
||||
name = request.values.get("name")
|
||||
parent_id = request.values.get("parent_id")
|
||||
child_id = request.values.get("child_id")
|
||||
res = PreferenceManager.create_or_update_relation_view(name, parent_id, child_id)
|
||||
return self.jsonify(res.to_dict())
|
||||
cr_ids = request.values.get("cr_ids")
|
||||
views, id2type, name2id = PreferenceManager.create_or_update_relation_view(name, cr_ids)
|
||||
|
||||
return self.jsonify(views=views, id2type=id2type, name2id=name2id)
|
||||
|
||||
@role_required(RoleEnum.CONFIG)
|
||||
def put(self):
|
||||
self.post()
|
||||
return self.post()
|
||||
|
||||
@role_required(RoleEnum.CONFIG)
|
||||
@args_required("name")
|
||||
def delete(self):
|
||||
name = request.values.get("name")
|
||||
PreferenceManager.delete_relation_view(name)
|
||||
|
||||
return self.jsonify(name=name)
|
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""Create an application instance."""
|
||||
|
||||
from flask import g
|
||||
from flask_login import current_user
|
||||
|
@@ -3,7 +3,8 @@
|
||||
from api.app import create_app
|
||||
from api.extensions import celery
|
||||
|
||||
# celery worker -A celery_worker.celery -l DEBUG -E -Q xxxx
|
||||
# celery worker -A celery_worker.celery -l DEBUG -E -Q <queue_name> --concurrency=1
|
||||
print(celery)
|
||||
|
||||
app = create_app()
|
||||
app.app_context().push()
|
17
cmdb-api/local_test.py
Normal file
17
cmdb-api/local_test.py
Normal file
@@ -0,0 +1,17 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""For debugging in ide"""
|
||||
|
||||
from tests.conftest import *
|
||||
from pytest_mock import mocker
|
||||
from _pytest.config import _prepareconfig
|
||||
|
||||
from tests.test_cmdb_attribute import test_create_attribute
|
||||
|
||||
|
||||
for a in app():
|
||||
for d in database(a):
|
||||
for s in session(d, a):
|
||||
for c in client(a):
|
||||
for m in mocker(_prepareconfig()):
|
||||
clean_db()
|
||||
test_create_attribute(s, c)
|
7
cmdb-api/requirements-test.txt
Normal file
7
cmdb-api/requirements-test.txt
Normal file
@@ -0,0 +1,7 @@
|
||||
-i https://mirrors.aliyun.com/pypi/simple
|
||||
pytest==4.0.2
|
||||
attrs==19.1.0
|
||||
coverage==4.4.2
|
||||
pytest-cov==2.5.1
|
||||
pytest-html==1.16.1
|
||||
pytest-mock==1.10.0
|
40
cmdb-api/requirements.txt
Normal file
40
cmdb-api/requirements.txt
Normal file
@@ -0,0 +1,40 @@
|
||||
-i https://mirrors.aliyun.com/pypi/simple
|
||||
# Flask
|
||||
Flask == 1.0.3
|
||||
Werkzeug >= 0.15.5
|
||||
click >= 5.0
|
||||
# Api
|
||||
Flask-RESTful == 0.3.7
|
||||
# Database
|
||||
Flask-SQLAlchemy == 2.4.0
|
||||
SQLAlchemy == 1.3.5
|
||||
PyMySQL == 0.9.3
|
||||
redis == 3.2.1
|
||||
# Migrations
|
||||
Flask-Migrate == 2.5.2
|
||||
# Deployment
|
||||
gevent == 1.4.0
|
||||
gunicorn == 19.5.0
|
||||
supervisor == 4.0.3
|
||||
# Auth
|
||||
Flask-Login == 0.4.1
|
||||
Flask-Bcrypt == 0.7.1
|
||||
Flask-Cors >= 3.0.8
|
||||
python-ldap == 3.2.0
|
||||
# Caching
|
||||
Flask-Caching >= 1.0.0
|
||||
# Environment variable parsing
|
||||
environs == 4.2.0
|
||||
marshmallow == 2.20.2
|
||||
# async tasks
|
||||
celery == 4.3.0
|
||||
more-itertools == 5.0.0
|
||||
kombu == 4.4.0
|
||||
# other
|
||||
six == 1.12.0
|
||||
bs4 >= 0.0.1
|
||||
toposort >= 1.5
|
||||
requests >= 2.22.0
|
||||
PyJWT >= 1.7.1
|
||||
elasticsearch == 7.0.4
|
||||
future == 0.18.2
|
@@ -69,9 +69,21 @@ CAS_VALIDATE_ROUTE = "/cas/serviceValidate"
|
||||
CAS_AFTER_LOGIN = "/"
|
||||
DEFAULT_SERVICE = "http://127.0.0.1:8000"
|
||||
|
||||
# # ldap
|
||||
AUTH_WITH_LDAP = False
|
||||
LDAP_SERVER = ''
|
||||
LDAP_DOMAIN = ''
|
||||
|
||||
# # pagination
|
||||
DEFAULT_PAGE_COUNT = 50
|
||||
|
||||
# # permission
|
||||
WHITE_LIST = ["127.0.0.1"]
|
||||
USE_ACL = False
|
||||
|
||||
# # elastic search
|
||||
ES_HOST = '127.0.0.1'
|
||||
USE_ES = False
|
||||
|
||||
|
||||
BOOL_TRUE = ['true', 'TRUE', 'True', True, '1', 1, "Yes", "YES", "yes", 'Y', 'y']
|
12
cmdb-api/setup.cfg
Normal file
12
cmdb-api/setup.cfg
Normal file
@@ -0,0 +1,12 @@
|
||||
[flake8]
|
||||
ignore = D401,D202,E226,E302,E41
|
||||
max-line-length = 120
|
||||
exclude = migrations/*
|
||||
max-complexity = 10
|
||||
|
||||
|
||||
[isort]
|
||||
line_length = 88
|
||||
multi_line_output = 3
|
||||
skip = migrations/*
|
||||
include_trailing_comma = true
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user