Selaa lähdekoodia

项目雏形初见

James Iter 9 vuotta sitten
sitoutus
e59cf944d7

+ 57 - 0
.gitignore

@@ -0,0 +1,57 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+env/
+# build/
+develop-eggs/
+# dist/
+downloads/
+eggs/
+# lib/
+lib64/
+parts/
+sdist/
+var/
+*.egg-info/
+.installed.cfg
+*.egg
+
+# PyInstaller
+#  Usually these files are written by a python script from a template
+#  before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.coverage
+.cache
+nosetests.xml
+coverage.xml
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+# PyCharm IDE
+.idea/

+ 675 - 0
LICENSE

@@ -0,0 +1,675 @@
+GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    {one line to give the program's name and a brief idea of what it does.}
+    Copyright (C) {year}  {name of author}
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    {project}  Copyright (C) {year}  {fullname}
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+

+ 191 - 0
README.md

@@ -0,0 +1,191 @@
+[![License](https://img.shields.io/badge/License-GPL3-blue.svg)](http://www.gnu.org/licenses/gpl-3.0.html)
+[![Format](https://img.shields.io/badge/Format-JSON-blue.svg)](http://www.json.org/json-zh.html)
+[![Python versions](https://img.shields.io/badge/Python-2.7.10-blue.svg)](https://www.python.org)
+[![API](https://img.shields.io/badge/API-RESTful-blue.svg)](http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm)
+
+
+## 项目描述
+> JimV-C 是 JimV 的控制节点。JimV 是一个轻量级的 KVM 虚拟化环境管理平台。
+* 纯 HTTP 的交互方式;
+
+
+## 未来计划
+>
+* 加入移动端的支持;
+
+
+## 安装
+### 创建web用户
+``` bash
+useradd -m www
+```
+
+### 创建站点发布目录
+``` bash
+su - www
+mkdir ~/sites
+```
+
+### 克隆JimID项目
+``` bash
+git clone https://github.com/jamesiter/JimV-C.git ~/sites/JimV-C
+```
+
+### 安装所需库
+``` bash
+# 创建 python 虚拟环境
+virtualenv --system-site-packages venv
+# 导入 python 虚拟环境
+source ~/venv/bin/activate
+# 安装JimID所需扩展库
+pip install -r ~/sites/JimV-C/requirements.txt
+# 安装Python连接MySQL的适配器
+git clone https://github.com/mysql/mysql-connector-python.git; cd ~/mysql-connector-python; python setup.py install; cd ..; rm -rf mysql-connector-python
+```
+
+### 初始化JimV MySQL数据库
+``` bash
+# 建立 JimV 数据库专属用户
+mysql -u root -pyour_db_password -e 'grant all on jimv.* to jimv@localhost identified by "your_jimv_db_password"; flush privileges'
+# 初始化数据库
+mysql -u jimv -pyour_jimv_db_password < sites/jimv/misc/init.sql
+# 确认是否初始化成功
+mysql -u jimv -pyour_jimv_db_password -e 'show databases'
+```
+
+### 修改配置文件
+配置文件路径:`sites/JimV-C/config.json`
+<br>
+**提示:**
+> 下表中凸显的配置项,需要用户根据自己的环境手动修改。
+
+|配置项|默认值|说明|
+|:--|:--|:--|
+|db_name|jimv|数据库名称|
+|db_host|localhost|数据库地址|
+|db_port|3306|数据库端口|
+|db_user|jimv|连接数控的用户名|
+|**`db_password`**|jimid.pswd.com|连接数控的密码|
+|db_pool_size|10|连接池|
+|db_charset|utf8|默认字符集|
+|redis_host|localhost|redis数据库地址|
+|redis_port|2501|redis数据库端口|
+|**`redis_password`**||redis数据库密码|
+|redis_dbid|0|连接的redis数据库|
+|debug|false|是否为调试模式|
+|log_cycle|D|日志轮转周期|
+|token_ttl|604800|token有效期|
+|**`jwt_secret`**||token安全码|
+|jwt_algorithm|HS512|token哈希算法|
+|SESSION_TYPE|filesystem|session存放类型|
+|SESSION_PERMANENT|true|session是否持久化存储|
+|SESSION_USE_SIGNER|true|session是否使用并校验签名|
+|SESSION_FILE_DIR|../cache|session存放路径|
+|SESSION_FILE_THRESHOLD|1000|存放的session超过该数量,之前的将被删除|
+|SESSION_COOKIE_NAME|sid|session id在客户端cookie中的存放名称|
+|SESSION_COOKIE_SECURE|false|cookie的传输是否只在https的环境中进行|
+|**`SECRET_KEY`**||session安全码|
+|PERMANENT_SESSION_LIFETIME|604800|cookie在客户端的持久化时间。该值需与token_ttl相同|
+|vm_create_queue|Q:VMCreate|创建虚拟机的队列|
+|host_event_report_queue|Q:HostEvent|宿主机事件上抛队列|
+|ip_available_set|S:IP:Available|虚拟化环境中可用 IP 集合|
+|ip_used_set|S:IP:Used|虚拟化环境中已用 IP 地址集合|
+|vnc_port_available_set|S:VNCPort:Available|虚拟化环境中可用 VNC 端口集合|
+|vnc_port_used_set|S:VNCPort:Used|虚拟化环境中已用 VNC 端口集合|
+
+### 启动服务
+``` bash
+# 进入JimV-C目录
+cd ~/sites/JimV-C
+# 启动JimV-C
+gunicorn -c gunicorn_config.py main:app
+```
+
+### Nginx 参考配置
+``` nginx
+    gzip on;
+    gzip_min_length 1100;
+    gzip_buffers 4 8k;
+    gzip_types text/plain application/javascript text/css;
+
+    autoindex off;
+    add_header X-Frame-Options SAMEORIGIN;
+    add_header X-Content-Type-Options: nosniff;
+
+    server {
+        listen 443;
+        server_name jimv.your-domain;
+
+        access_log  /var/log/nginx/jimv.access.log;
+        error_log  /var/log/nginx/jimv.error.log;
+
+        ssl on;
+        ssl_certificate /opt/pki/tls/certs/jimv.your.crt;
+        ssl_certificate_key /opt/pki/tls/certs/jimv.your.key;
+        ssl_session_timeout 5m;
+        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
+        ssl_ciphers AESGCM:ALL:!DH:!EXPORT:!RC4:+HIGH:!MEDIUM:!LOW:!aNULL:!eNULL;
+        ssl_prefer_server_ciphers on;
+
+        root /home/www/sites/jimv/html;
+
+        # 拒绝访问隐藏文件(如:.git、.svn等目录)
+        location ~ /\..* {
+            return 403;
+        }
+        location ~ .(sql|py|pyc|ini|conf|log|svn|git|cfg)$ {
+            return 403;
+        }
+        location ~ /$ {
+            rewrite http://$host/index.html break;
+        }
+        location / {
+            try_files $uri @inner;
+        }
+
+        location @inner {
+            proxy_pass         http://127.0.0.1:8001;
+            proxy_redirect     off;
+            proxy_set_header   Host             $host;
+            proxy_set_header   X-Real-IP        $remote_addr;
+            proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
+        }
+    }
+```
+
+
+## API
+> 默认数据交互格式 Content-Type: application/json
+
+### [状态码参考列表](docs/state_code.md)
+### [过滤器操作符原语](docs/filter_primitive.md)
+
+
+## 流程图
+
+
+## Web端
+[Web端项目地址](https://github.com/jamesiter/JimV-C-web)
+
+
+## 问题反馈
+[提交Bug](https://github.com/jamesiter/JimV-C/issues)
+<br>
+技术交流 QQ 群: 377907881
+
+
+## 项目成员
+<pre>
+姓名:    James Iter
+E-Mail: james.iter.cn@gmail.com
+</pre>
+
+
+## Web端程序截图
+[Web端程序截图](docs/screenshot.md)
+
+
+## Demo
+[demo.jimv.org](https://demo.jimv.org)
+<br>
+管理员账密 `admin`:`admin`

+ 36 - 0
config.json

@@ -0,0 +1,36 @@
+{
+  "jimv_listen": "0.0.0.0",
+  "jimv_port": 8008,
+  "db_name": "jimv",
+  "db_host": "localhost",
+  "db_port": 3306,
+  "db_user": "root",
+  "db_password": "jimpswd.com",
+  "db_pool_size": 10,
+  "db_charset": "utf8",
+  "redis_host": "localhost",
+  "redis_port": 2501,
+  "redis_password": "IwNAQSew5FDlmjcL7LlvAurl3gqpFKxu7FCYK0CN0xKErYlew78R2ZNV9lsiFbPaMByHmTygScndOWhlDY8lhTJGqyp9RHMqnxMwlYgE375N0GddYV2AEDZsfarfE0T0",
+  "redis_dbid": 0,
+  "debug": false,
+  "log_file_dir": "logs",
+  "log_cycle": "D",
+  "token_ttl": 604800,
+  "jwt_secret": "kcMsj4qj0EAvAvj3nlFlPZd2x7P9kBBQ$deae64883a03982913e6c5f0ba265c2c5dfd0cfx'",
+  "jwt_algorithm": "HS512",
+  "SESSION_TYPE": "filesystem",
+  "SESSION_PERMANENT": true,
+  "SESSION_USE_SIGNER": true,
+  "SESSION_FILE_DIR": "../cache",
+  "SESSION_FILE_THRESHOLD": 100,
+  "SESSION_COOKIE_NAME": "sid",
+  "SESSION_COOKIE_SECURE": false,
+  "SECRET_KEY": "QSYI73re6x553wmcNwT9tk4OCNK9OUS9xNUulDShEcvRw00YhCKaqHhEGYOGKOSB",
+  "PERMANENT_SESSION_LIFETIME": 604800,
+  "vm_create_queue": "Q:VMCreate",
+  "host_event_report_queue": "Q:HostEvent",
+  "ip_available_set": "S:IP:Available",
+  "ip_used_set": "S:IP:Used",
+  "vnc_port_available_set": "S:VNCPort:Available",
+  "vnc_port_used_set": "S:VNCPort:Used"
+}

+ 76 - 0
docs/filter_primitive.md

@@ -0,0 +1,76 @@
+# 过滤器操作符原语
+
+## 原语说明
+|操作符原语|示例|说明|
+|:--|:--|:--|
+|eq|id:eq:5|过滤出`id`字段`等于` `5`的条目。|
+|gt|create_time:gt:1487236163783548|过滤出时间戳字段`create_time` `大于` `1487236163783548`的条目。|
+|lt|create_time:gt:1487246163783548|过滤出时间戳字段`create_time` `小于` `1487246163783548`的条目。|
+|ne|role_id:ne:0|过滤出角色字段`role_id` `不等于` `1`的条目。|
+|in|id:in:6o3H13DqJOiTu53v,UuAsvSbVTsyHpqvF|过滤出应用id字段`id` `为` `6o3H13DqJOiTu53v`或`UuAsvSbVTsyHpqvF`的条目。|
+|notin|id:notin:6o3H13DqJOiTu53v,UuAsvSbVTsyHpqvF|过滤出应用id字段`id` `不为` `6o3H13DqJOiTu53v`且`UuAsvSbVTsyHpqvF`的条目。|
+|like|mobile_phone:like:156|过滤出用户手机号码字段`mobile_phone` `包含` `156`的条目。|
+|\:|id:eq:5|过滤语句中,主、谓、宾的分隔符。|
+|,|id:in:6o3H13DqJOiTu53v,UuAsvSbVTsyHpqvF|一个过滤语句中,多个值之间的分隔符。|
+|;|mobile_phone:like:156;create_time:gt:1487054296057012|多个过滤语句间的分隔符。|
+
+
+## 组合操作示例
+> 过滤出用户手机号码包含156,且创建时间大于1487054296057012的用户。
+
+``` http
+GET http://jimauth.dev.iit.im
+  /api/users_mgmt?filter=mobile_phone:like:156;create_time:gt:1487054296057012
+```
+
+响应示例
+``` json
+{
+    "state": {
+        "code": "200",
+        "zh-cn": "成功",
+        "en-us": "OK"
+    },
+    "data": [{
+        "mobile_phone": "15600000000",
+        "login_name": "mm5h5pao3r",
+        "mobile_phone_verified": 0,
+        "email_verified": 0,
+        "enabled": 1,
+        "id": 373,
+        "role_id": 0,
+        "manager": 0,
+        "create_time": 1487140251278993,
+        "email": ""
+    }, {
+        "mobile_phone": "15600000010",
+        "login_name": "uz6hp2hd5x",
+        "mobile_phone_verified": 0,
+        "email_verified": 0,
+        "enabled": 1,
+        "id": 376,
+        "role_id": 0,
+        "manager": 0,
+        "create_time": 1487140279849145,
+        "email": ""
+    }],
+    "paging": {
+        "first": "http://jimauth.dev.iit.im/api/users_mgmt?page=1&page_size=50&filter=mobile_phone:like:156;create_time:gt:1487054296057012&order=asc&order_by=id",
+        "prev": "http://jimauth.dev.iit.im/api/users_mgmt?page=1&page_size=50&filter=mobile_phone:like:156;create_time:gt:1487054296057012&order=asc&order_by=id",
+        "limit": 50,
+        "offset": 0,
+        "last": "http://jimauth.dev.iit.im/api/users_mgmt?page=1&page_size=50&filter=mobile_phone:like:156;create_time:gt:1487054296057012&order=asc&order_by=id",
+        "total": 2,
+        "page": 1,
+        "page_size": 50,
+        "next": "http://jimauth.dev.iit.im/api/users_mgmt?page=1&page_size=50&filter=mobile_phone:like:156;create_time:gt:1487054296057012&order=asc&order_by=id"
+    }
+}
+```
+
+
+**`提示`**
+<br>
+**in** 包含 `等于` 及 `或等于` 的意思;
+<br>
+**not in** 包含 `不等于` 及 `且不等于` 的意思。

+ 52 - 0
docs/state_code.md

@@ -0,0 +1,52 @@
+# 状态码
+## 干状态码
+|CODE|zh-cn|en-us|
+|:--:|:--|:--|
+|200|成功|OK|
+|201|已创建|Created|
+|202|已接受|Accepted|
+|204|没有内容|No Content|
+|400|坏请求|Bad request|
+|401|未授权|Unauthorized|
+|403|禁止|Forbidden|
+|404|未找到|Not found|
+|405|不允许使用的方法|Method Not Allowed|
+|409|请求冲突|Conflict|
+|412|先决条件失败|Precondition Failed|
+|500|内部服务器错误|Internal Server Error|
+|501|未实现|Not Implemented|
+|503|服务不可用|Service Unavailable|
+
+## 枝状态码
+|CODE|zh-cn|
+|:--:|:--|
+|40101|未授权|
+|40301|禁止(无权)访问|
+|40401|目标不存在|
+|40450|目标操作系统模板未找到|
+|40451|目标操作系统初始化操作未找到|
+|40901|目标已存在|
+|41201|缺少参数|
+|41202|参数类型未达预期|
+|41203|参数值超出合理范围|
+|41204|预检策略原语类型有误,期待tuple类型|
+|41205|预检策略原语参数有误,期待3个|
+|41206|预检策略原语取值范围描述有误|
+|41207|预检策略原语字段描述有误,字段标识必须为basestring类型|
+|41208|无效的token|
+|41209|正则匹配失败|
+|41250|验证签名失败|
+|41251|起止IP必须在同一个网段中|
+|41252|网关必须与将分配给Guest的IP,处于同一个网段中|
+|41253|网关不能是网络地址或广播地址|
+|41254|起始的可用IP地址必须小于结束的可用IP地址|
+|50000|参见父描述|
+|50001|错误码类型错误|
+|50002|未定义的错误码|
+|50003|SQL对象序列化为json失败|
+|50004|计算文件hash失败|
+|50050|MySQL 链接或执行出错|
+|50350|无可用IP地址,请联系 JimV 管理员|
+
+[返回上一级](../README.md)
+===

+ 1 - 0
docs/todo.md

@@ -0,0 +1 @@
+

+ 38 - 0
generate_state_code_doc.py

@@ -0,0 +1,38 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+    Usage: python generate_state_code_doc.py > docs/state_code.md
+"""
+
+
+from collections import OrderedDict
+
+import jimit as ji
+from state_code import *
+
+
+__author__ = 'James Iter'
+__date__ = '16/8/21'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2016 by James Iter.'
+
+
+ji.index_state['branch'] = dict(ji.index_state['branch'], **own_state_branch)
+
+print '# 状态码'
+print '## 干状态码'
+print '|CODE|zh-cn|en-us|'
+print '|:--:|:--|:--|'
+for k, v in OrderedDict(sorted(ji.index_state['trunk'].items(), key=lambda t: t[0])).items():
+    print '|' + '|'.join([v['code'], v['zh-cn'], v['en-us']]) + '|'
+
+print ''
+print '## 枝状态码'
+print '|CODE|zh-cn|'
+print '|:--:|:--|'
+for k, v in OrderedDict(sorted(ji.index_state['branch'].items(), key=lambda t: t[0])).items():
+    print '|' + '|'.join([v['code'], v['zh-cn']]) + '|'
+
+print ''
+print '[返回上一级](../README.md)'
+print '==='

+ 33 - 0
gunicorn_config.py

@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import os
+import json
+import multiprocessing
+
+
+__author__ = 'James Iter'
+__date__ = '2017/2/20'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+with open('./config.json', 'r') as f:
+    _config = json.load(f)
+
+if not os.path.isdir(_config['log_file_dir']):
+    os.makedirs(_config['log_file_dir'], 0755)
+
+
+bind = _config['jimid_listen'] + ':' + _config['jimid_port'].__str__()
+workers = multiprocessing.cpu_count() * 2 + 1
+worker_class = 'eventlet'
+worker_connections = 1000
+daemon = True
+
+accesslog = './logs/access.log'
+errorlog = './logs/error.log'
+loglevel = 'info'
+
+pidfile = './jimid.pid'

+ 43 - 0
main.py

@@ -0,0 +1,43 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import traceback
+import thread
+
+from models.initialize import app, logger
+import route_table
+from models import Database as db
+from views.os_init import blueprint as os_init_blueprint
+from views.os_init_write import blueprint as os_init_write_blueprint
+from views.os_template import blueprint as os_template_blueprint
+from views.guest import blueprint as guest_blueprint
+from views.config import blueprint as config_blueprint
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/31'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+# noinspection PyBroadException
+try:
+    db.init_conn_mysql()
+    thread.start_new_thread(db.keepalived_mysql, ())
+    db.init_conn_redis()
+
+    app.register_blueprint(os_init_blueprint)
+    app.register_blueprint(os_init_write_blueprint)
+    app.register_blueprint(os_template_blueprint)
+    app.register_blueprint(guest_blueprint)
+    app.register_blueprint(config_blueprint)
+except:
+    logger.error(traceback.format_exc())
+
+if __name__ == '__main__':
+    # noinspection PyBroadException
+    try:
+        app.run(host=app.config['jimv_listen'], port=app.config['jimv_port'], use_reloader=False, threaded=True)
+    except:
+        logger.error(traceback.format_exc())

+ 91 - 0
misc/init.sql

@@ -0,0 +1,91 @@
+DROP DATABASE IF EXISTS jimv;
+CREATE DATABASE IF NOT EXISTS jimv CHARACTER SET utf8;
+USE jimv;
+
+
+CREATE TABLE IF NOT EXISTS guest(
+    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
+    uuid CHAR(36) NOT NULL,
+    name VARCHAR(64) NOT NULL UNIQUE,
+    password VARCHAR(255) NOT NULL,
+    remark VARCHAR(255) NOT NULL DEFAULT '',
+    os_template_id BIGINT UNSIGNED NOT NULL,
+    create_time BIGINT UNSIGNED NOT NULL,
+    status TINYINT UNSIGNED NOT NULL DEFAULT 0,
+    cpu TINYINT UNSIGNED NOT NULL,
+    memory INT UNSIGNED NOT NULL,
+    ip CHAR(15) NOT NULL,
+    network VARCHAR(64) NOT NULL,
+    manage_network VARCHAR(64) NOT NULL,
+    vnc_port INT UNSIGNED NOT NULL,
+    vnc_password VARCHAR(255) NOT NULL,
+    xml TEXT NOT NULL,
+    PRIMARY KEY (id))
+    ENGINE=InnoDB
+    DEFAULT CHARSET=utf8;
+
+ALTER TABLE guest ADD INDEX (name);
+
+
+CREATE TABLE IF NOT EXISTS guest_disk(
+    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
+    label VARCHAR(255) NOT NULL,
+    size INT UNSIGNED NOT NULL,
+    sequence TINYINT UNSIGNED NOT NULL,
+    format CHAR(16) NOT NULL DEFAULT 'qcow2',
+    guest_uuid CHAR(36) NOT NULL,
+    PRIMARY KEY (id))
+    ENGINE=InnoDB
+    DEFAULT CHARSET=utf8;
+
+ALTER TABLE guest_disk ADD INDEX (size);
+ALTER TABLE guest_disk ADD INDEX (guest_uuid);
+
+
+CREATE TABLE IF NOT EXISTS os_template(
+    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
+    label VARCHAR(255) NOT NULL,
+    name VARCHAR(255) NOT NULL,
+    active BOOLEAN NOT NULL DEFAULT TRUE,
+    os_init_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
+    PRIMARY KEY (id))
+    ENGINE=InnoDB
+    DEFAULT CHARSET=utf8;
+
+
+CREATE TABLE IF NOT EXISTS os_init(
+    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
+    name VARCHAR(255) NOT NULL,
+    remark TEXT NOT NULL DEFAULT '',
+    PRIMARY KEY (id))
+    ENGINE=InnoDB
+    DEFAULT CHARSET=utf8;
+
+
+CREATE TABLE IF NOT EXISTS os_init_write(
+    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
+    os_init_id BIGINT UNSIGNED NOT NULL,
+    path VARCHAR(255) NOT NULL,
+    content TEXT NOT NULL DEFAULT '',
+    PRIMARY KEY (id))
+    ENGINE=InnoDB
+    DEFAULT CHARSET=utf8;
+
+
+CREATE TABLE IF NOT EXISTS config(
+    id BIGINT UNSIGNED NOT NULL DEFAULT 1,
+    glusterfs_volume VARCHAR(255) NOT NULL,
+    vm_network VARCHAR(255) NOT NULL,
+    vm_manage_network VARCHAR(255) NOT NULL,
+    start_ip CHAR(15) NOT NULL,
+    end_ip CHAR(15) NOT NULL,
+    start_vnc_port INT UNSIGNED NOT NULL,
+    netmask CHAR(15) NOT NULL,
+    gateway CHAR(15) NOT NULL,
+    dns1 CHAR(15) NOT NULL DEFAULT '223.5.5.5',
+    dns2 CHAR(15) NOT NULL DEFAULT '8.8.8.8',
+    rsa_private text NOT NULL DEFAULT '',
+    rsa_public text NOT NULL DEFAULT '',
+    PRIMARY KEY (id))
+    ENGINE=InnoDB
+    DEFAULT CHARSET=utf8;

+ 65 - 0
models/__init__.py

@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+from rules import (
+    Rules
+)
+
+from utils import (
+    Utils
+)
+
+from initialize import (
+    Init
+)
+
+from database import (
+    Database
+)
+
+from filter import (
+    FilterFieldType,
+    Filter
+)
+
+from orm import (
+    ORM
+)
+
+from config import (
+    Config
+)
+
+from guest import (
+    Guest, GuestDisk
+)
+
+from guest_xml import (
+    GuestXML
+)
+
+from os_init import (
+    OSInit, OSInitWrite
+)
+
+from os_template import (
+    OSTemplate
+)
+
+from status import (
+    GuestStatus
+)
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/21'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+__all__ = [
+    'Rules', 'Utils', 'Init', 'Database', 'FilterFieldType', 'Filter', 'GuestStatus', 'ORM', 'Config',
+    'Guest', 'GuestDisk', 'OSInit', 'OSInitWrite', 'OSTemplate', 'GuestXML'
+]
+

+ 104 - 0
models/config.py

@@ -0,0 +1,104 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import json
+import jimit as ji
+from IPy import IP, intToIp
+
+from initialize import app
+from models import Database as db
+from models import ORM
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/21'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+class Config(ORM):
+
+    _table_name = 'config'
+    _primary_key = 'id'
+
+    def __init__(self):
+        super(Config, self).__init__()
+        # 配置条目的 id 只会是 1
+        self.id = 1
+        self.glusterfs_volume = ''
+        self.vm_network = ''
+        self.vm_manage_network = ''
+        self.start_ip = ''
+        self.end_ip = ''
+        self.start_vnc_port = None
+        self.netmask = ''
+        self.gateway = ''
+        self.dns1 = ''
+        self.dns2 = ''
+        self.rsa_private = ''
+        self.rsa_public = ''
+
+    @staticmethod
+    def get_filter_keywords():
+        return {}
+
+    @staticmethod
+    def get_allow_update_keywords():
+        return []
+
+    @staticmethod
+    def get_allow_content_search_keywords():
+        return []
+
+    def check_ip(self):
+        network_segment = IP(self.start_ip + '/' + self.netmask, make_net=True)
+
+        ret = dict()
+        # 起止IP必须在同一个网段中
+        if IP(self.end_ip) not in network_segment:
+            ret['state'] = ji.Common.exchange_state(41251)
+            raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
+
+        # 网关必须与将分配给Guest的IP,处于同一个网段中
+        if IP(self.gateway) not in network_segment:
+            ret['state'] = ji.Common.exchange_state(41252)
+            raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
+
+        # 网关不能是网络地址或广播地址
+        if IP(self.gateway) in [network_segment[i] for i in (0, -1)]:
+            ret['state'] = ji.Common.exchange_state(41253)
+            raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
+
+        # 当用户输入的起始IP为网络地址时,自动重置其为该网段中第一个可用IP
+        if self.start_ip == network_segment[0].__str__():
+            self.start_ip = intToIp((int(IP(self.start_ip).strDec()) + 1).__str__(), 4)
+
+        # 当用户输入的结束IP为广播地址时,自动重置其为该网段中最后一个可用IP
+        if self.end_ip == network_segment[-1].__str__():
+            self.end_ip = intToIp((int(IP(self.end_ip).strDec()) - 1).__str__(), 4)
+
+        # 起始的可用IP地址必须小于结束的可用IP地址
+        if IP(self.start_ip) >= IP(self.end_ip):
+            ret['state'] = ji.Common.exchange_state(41254)
+            raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
+
+        return True
+
+    def generate_available_ip2set(self):
+        # 删除现有的可用IP集合
+        db.r.delete(app.config['ip_available_set'])
+
+        for ip_dec in range(int(IP(self.start_ip).strDec()), int(IP(self.end_ip).strDec()) + 1):
+            db.r.sadd(app.config['ip_available_set'], intToIp(ip_dec, 4))
+
+    def generate_available_vnc_port(self):
+        # 删除现有的可用 vnc 端口集合
+        db.r.delete(app.config['vnc_port_available_set'])
+
+        i = 0
+        # 借用可用 IP 范围生成需要的 vnc 端口集合
+        for ip_dec in range(int(IP(self.start_ip).strDec()), int(IP(self.end_ip).strDec()) + 1):
+            i += 1
+            db.r.sadd(app.config['vnc_port_available_set'], self.start_vnc_port + i)
+

+ 87 - 0
models/database.py

@@ -0,0 +1,87 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import mysql.connector
+import mysql.connector.pooling
+import redis
+from mysql.connector import errorcode
+import time
+
+from initialize import app, logger
+
+
+__author__ = 'James Iter'
+__date__ = '16/6/8'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2016 by James Iter.'
+
+
+class Database(object):
+
+    cnxpool = None
+    r = None
+
+    def __init__(self):
+        pass
+
+    @classmethod
+    def init_conn_mysql(cls):
+        try:
+            cls.cnxpool = mysql.connector.pooling.MySQLConnectionPool(
+                host=app.config["db_host"],
+                user=app.config["db_user"],
+                password=app.config["db_password"],
+                port=app.config["db_port"],
+                database=app.config["db_name"],
+                raise_on_warnings=app.config["debug"],
+                pool_size=app.config["db_pool_size"],
+                charset=app.config["db_charset"]
+            )
+        except mysql.connector.Error as err:
+            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
+                e_msg = u'用户名或密码错误'
+            elif err.errno == errorcode.ER_BAD_DB_ERROR:
+                e_msg = u'数据库不存在'
+            else:
+                e_msg = err.msg
+
+            print(e_msg)
+            exit(err.errno)
+
+    @classmethod
+    def keepalived_mysql(cls):
+        def ping(label='', _cnxpool=None):
+            if _cnxpool is None:
+                logger.critical(''.join(['cnxpool must not None by ', label]))
+                return
+
+            try:
+                _cnx = _cnxpool.get_connection()
+                _cnx.ping(attempts=1, delay=0)
+            except mysql.connector.errors.InterfaceError as err:
+                logger.critical(err.msg)
+            except mysql.connector.Error as err:
+                logger.error(err)
+            else:
+                _cnx.close()
+
+        while True:
+            time.sleep(5)
+            ping(label='', _cnxpool=cls.cnxpool)
+
+    @classmethod
+    def init_conn_redis(cls):
+        cls.r = redis.StrictRedis(host=app.config.get('redis_host', '127.0.0.1'),
+                                  port=app.config.get('redis_port', 6379),
+                                  db=app.config.get('redis_dbid', 0), decode_responses=True)
+
+        try:
+            cls.r.ping()
+        except redis.exceptions.ResponseError as e:
+            logger.warn(e.message)
+            cls.r = redis.StrictRedis(host=app.config.get('redis_host', '127.0.0.1'),
+                                      port=app.config.get('redis_port', 6379),
+                                      db=app.config.get('redis_dbid', 0), password=app.config.get('redis_password', ''),
+                                      decode_responses=True)
+

+ 93 - 0
models/filter.py

@@ -0,0 +1,93 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+from enum import Enum
+
+from initialize import regex_sql_str, regex_dsl_str
+
+
+__author__ = 'James Iter'
+__date__ = '2016/10/3'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2016 by James Iter.'
+
+
+class FilterFieldType(Enum):
+    INT = 'int'
+    STR = 'str'
+    BOOL = 'bool'
+
+
+class Filter(object):
+    operator = {'eq': '=',
+                'gt': '>',
+                'lt': '<',
+                'ne': '!=',
+                'in': 'in',
+                'notin': 'in',
+                'like': 'like'}
+
+    def __init__(self):
+        pass
+
+    @staticmethod
+    def get_fit_statement(field_type=None, value=''):
+        if field_type == FilterFieldType.INT.value:
+            if not value.isdigit():
+                raise TypeError(''.join(['Value: ', str(value), ' should be digit']))
+            return value
+        elif field_type == FilterFieldType.STR.value:
+            _s = regex_sql_str.sub('"', str(value)).strip('"')
+            return ''.join(['"', _s.replace('"', '\\"'), '"'])
+        elif field_type == FilterFieldType.BOOL.value:
+            return str(False) if value.lower() == 'false' else str(True)
+        else:
+            raise TypeError(''.join(['unknown type ', str(field_type)]))
+
+    @classmethod
+    def dsl_to_sql(cls, allow_keywords=None, dsl=''):
+        sql_stmt = ''
+
+        if regex_dsl_str.match(dsl) is None:
+            return sql_stmt
+
+        keyword, operator, value = dsl.split(':')
+        operator = operator.lower()
+
+        if keyword not in allow_keywords.keys():
+            return sql_stmt
+        field_type = allow_keywords[keyword]
+
+        if operator in ['eq', 'gt', 'lt', 'ne']:
+            sql_stmt = keyword + cls.operator[operator] + cls.get_fit_statement(field_type=field_type, value=value)
+
+        elif operator == 'in':
+            # from itertools import repeat
+            # _sql_stmt = map(cls.get_fit_statement, repeat(field_type, len(value.split(','))), value.split(','))
+            # 上面为通过map实现的方式
+            _sql_stmt = [cls.get_fit_statement(field_type=field_type, value=v) for v in value.split(',')]
+            sql_stmt = keyword + ' in (' + ','.join(_sql_stmt) + ')'
+
+        elif operator == 'notin':
+            _sql_stmt = [cls.get_fit_statement(field_type=field_type, value=v) for v in value.split(',')]
+            sql_stmt = keyword + ' not in (' + ','.join(_sql_stmt) + ')'
+
+        elif operator == 'like':
+            sql_stmt = keyword + ' like "%' + cls.get_fit_statement(
+                field_type=field_type, value=value).strip('"') + '%"'
+
+        return sql_stmt
+
+    @classmethod
+    def filter_str_to_sql(cls, allow_keywords=None, filter_str=''):
+        sql_stmts = []
+        for dsl in filter_str.split(';'):
+            sql_stmt = cls.dsl_to_sql(allow_keywords=allow_keywords, dsl=dsl)
+            if sql_stmt == '':
+                continue
+
+            sql_stmts.append(sql_stmt)
+
+        return ' AND '.join(sql_stmts)
+

+ 90 - 0
models/guest.py

@@ -0,0 +1,90 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import jimit as ji
+
+from filter import FilterFieldType
+from orm import ORM
+from status import GuestStatus
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/22'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+class Guest(ORM):
+
+    _table_name = 'guest'
+    _primary_key = 'id'
+
+    def __init__(self):
+        super(Guest, self).__init__()
+        self.id = 0
+        self.uuid = None
+        self.name = None
+        self.password = None
+        self.remark = None
+        self.os_template_id = None
+        self.create_time = ji.Common.tus()
+        self.status = GuestStatus.shutdown.value
+        self.cpu = None
+        self.memory = None
+        self.ip = None
+        self.network = None
+        self.manage_network = None
+        self.vnc_port = None
+        self.vnc_password = None
+        self.xml = None
+
+    @staticmethod
+    def get_filter_keywords():
+        return {
+            'name': FilterFieldType.STR.value,
+            'remark': FilterFieldType.INT.value,
+            'ip': FilterFieldType.INT.value
+        }
+
+    @staticmethod
+    def get_allow_update_keywords():
+        return ['remark', 'cpu', 'memory', 'network', 'manage_network', 'vnc_password']
+
+    @staticmethod
+    def get_allow_content_search_keywords():
+        return ['name', 'remark', 'ip']
+
+
+class GuestDisk(ORM):
+
+    _table_name = 'guest_disk'
+    _primary_key = 'id'
+
+    def __init__(self):
+        super(GuestDisk, self).__init__()
+        self.id = 0
+        self.label = None
+        self.size = None
+        self.sequence = None
+        self.format = 'qcow2'
+        self.guest_uuid = None
+
+    @staticmethod
+    def get_filter_keywords():
+        return {
+            'label': FilterFieldType.STR.value,
+            'size': FilterFieldType.INT.value,
+            'guest_id': FilterFieldType.INT.value
+        }
+
+    @staticmethod
+    def get_allow_update_keywords():
+        return []
+
+    @staticmethod
+    def get_allow_content_search_keywords():
+        return ['label', 'size']
+
+
+

+ 158 - 0
models/guest_xml.py

@@ -0,0 +1,158 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+from models import Config
+from models import Guest
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/25'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+class GuestXML(object):
+    """
+    <?xml version="1.0" encoding="utf-8"?>
+    <domain type="kvm">
+      <features>
+        <acpi/>
+        <apic/>
+      </features>
+      <name>10v022</name>
+      <vcpu>16</vcpu>
+      <memory unit="GiB">64</memory>
+      <os>
+        <boot dev="hd"/>
+        <type arch="x86_64">hvm</type>
+        <bootmenu timeout="3000" enable="yes"/>
+      </os>
+      <devices>
+        <interface type='network'>
+          <source network='net-br0'/>
+          <model type='virtio'/>
+        </interface>
+        <disk type='network' device='disk'>
+            <driver name='qemu' type='qcow2' cache='none'/>
+            <source protocol='gluster' name='gv0/VMs/disk_pool/10v01251/L_10v01251.qcow2'>
+                <host name='127.0.0.1' port='24007'/>
+            </source>
+            <target dev='vda' bus='virtio'/>
+        </disk>
+        <graphics passwd="000000" keymap="en-us" port="6002" type="vnc">
+          <listen network="net-br0" type="network"/>
+        </graphics>
+        <serial type='pty'>
+            <target port='0'/>
+        </serial>
+        <console type='pty'>
+            <target type='serial' port='0'/>
+        </console>
+      </devices>
+    </domain>
+    """
+
+    def __init__(self, guest=None, disks=None, g_config=None):
+        assert isinstance(guest, Guest)
+        assert isinstance(disks, list)
+        assert isinstance(g_config, Config)
+
+        self.guest = guest
+        self.disks = disks
+        self.g_config = g_config
+
+    def get_domain(self):
+        return """
+            <?xml version="1.0" encoding="utf-8"?>
+            <domain type="kvm">
+            {0}
+            {1}
+            {2}
+            {3}
+            {4}
+            {5}
+            </domain>
+        """.format(self.get_features(), self.get_name(), self.get_vcpu(), self.get_memory(), self.get_os(),
+                   self.get_devices())
+
+    @staticmethod
+    def get_features():
+        return """
+            <features>
+                <acpi/>
+                <apic/>
+            </features>
+        """
+
+    def get_name(self):
+        return """<name>{0}</name>""".format(self.guest.name)
+
+    def get_vcpu(self):
+        return """<vcpu>{0}</vcpu>""".format(self.guest.cpu.__str__())
+
+    def get_memory(self):
+        return """<memory unit="GiB">{0}</memory>""".format(self.guest.memory.__str__())
+
+    @staticmethod
+    def get_os():
+        return """
+            <os>
+                <boot dev="hd"/>
+                <type arch="x86_64">hvm</type>
+                <bootmenu timeout="3000" enable="yes"/>
+            </os>
+        """
+
+    def get_devices(self):
+        return """
+            <devices>
+                {0}
+                {1}
+                {2}
+                {3}
+            </devices>
+        """.format(self.get_interface(), self.get_disks(), self.get_graphics(), self.get_console())
+
+    def get_interface(self):
+        return """
+            <interface type='network'>
+                <source network='{0}'/>
+                <model type='virtio'/>
+            </interface>
+        """.format(self.guest.network)
+
+    def get_disks(self):
+
+        disks = []
+        dev_table = ['vda', 'vdb', 'vdc', 'vdd']
+
+        for i, disk in self.disks:
+            disks.append("""
+                <disk type='network' device='disk'>
+                    <driver name='qemu' type='qcow2' cache='none'/>
+                    <source protocol='gluster' name='{0}/VMs/{1}/{2}.{3}'>
+                        <host name='127.0.0.1' port='24007'/>
+                    </source>
+                    <target dev='{4}' bus='virtio'/>
+                </disk>
+            """.format(self.g_config.glusterfs_volume, self.guest.name, disk['label'], disk['format'], dev_table[i]))
+
+        return ''.join(disks)
+
+    def get_graphics(self):
+        return """
+            <graphics passwd="{0}" keymap="en-us" port="{1}" type="vnc">
+                <listen network="{2}" type="network"/>
+            </graphics>
+        """.format(self.guest.vnc_password, self.guest.vnc_port, self.guest.manage_network)
+
+    @staticmethod
+    def get_console():
+        return """
+            <serial type='pty'>
+                <target port='0'/>
+            </serial>
+            <console type='pty'>
+                <target type='serial' port='0'/>
+            </console>
+        """
+

+ 105 - 0
models/initialize.py

@@ -0,0 +1,105 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+from flask import Flask, g
+import logging
+from logging.handlers import TimedRotatingFileHandler
+import json
+import os
+import sys
+import re
+import getopt
+import jimit as ji
+
+from jimvc_exception import PathNotExist
+from state_code import own_state_branch
+
+
+reload(sys)
+sys.setdefaultencoding('utf8')
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/21'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+app = Flask(__name__)
+
+
+class Init(object):
+    config = {
+        'config_file': '/etc/jimvc.conf'
+    }
+
+    @classmethod
+    def load_config(cls):
+
+        def usage():
+            print "Usage:%s [-c] [--config]" % sys.argv[0]
+
+        opts = None
+        try:
+            opts, args = getopt.getopt(sys.argv[1:], 'hc:',
+                                       ['help', 'config='])
+        except getopt.GetoptError as e:
+            print str(e)
+            usage()
+            exit(e.message.__len__())
+
+        for k, v in opts:
+            if k in ("-h", "--help"):
+                usage()
+                exit()
+            elif k in ("-c", "--config"):
+                cls.config['config_file'] = v
+            else:
+                print "unhandled option"
+
+        if not os.path.isfile(cls.config['config_file']):
+            raise PathNotExist(u'配置文件不存在, 请配置 --> ', cls.config['config_file'])
+
+        with open(cls.config['config_file'], 'r') as f:
+            cls.config.update(json.load(f))
+
+        return cls.config
+
+    @classmethod
+    def init_logger(cls):
+        cls.config['log_file_base'] = '/'.join([sys.path[0], cls.config['log_file_dir'], 'log'])
+        log_dir = os.path.dirname(cls.config['log_file_base'])
+        if not os.path.isdir(log_dir):
+            os.makedirs(log_dir, 0755)
+
+        process_title = 'JimV-C'
+        log_file_path = '.'.join([cls.config['log_file_base'], process_title])
+        _logger = logging.getLogger(log_file_path)
+
+        if cls.config['debug']:
+            cls.config['DEBUG'] = True
+            _logger.setLevel(logging.DEBUG)
+        else:
+            cls.config['DEBUG'] = False
+            _logger.setLevel(logging.INFO)
+
+        fh = TimedRotatingFileHandler(log_file_path, when=cls.config['log_cycle'], interval=1, backupCount=7)
+        formatter = logging.Formatter(
+            '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(lineno)s - %(message)s')
+        fh.setFormatter(formatter)
+        _logger.addHandler(fh)
+        return _logger
+
+
+# 预编译效率更高
+regex_sql_str = re.compile('\\\+"')
+regex_dsl_str = re.compile('^\w+:\w+:\S+$')
+
+config = Init.load_config()
+logger = Init.init_logger()
+
+app.config = dict(app.config, **config)
+
+ji.index_state['branch'] = dict(ji.index_state['branch'], **own_state_branch)
+

+ 21 - 0
models/jimvc_exception.py

@@ -0,0 +1,21 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/21'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+class JimVCException(Exception):
+    pass
+
+
+class PathExist(JimVCException):
+    pass
+
+
+class PathNotExist(JimVCException):
+    pass
+

+ 316 - 0
models/orm.py

@@ -0,0 +1,316 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import json
+import jimit as ji
+from mysql.connector import errorcode, errors
+
+from database import Database as db
+from models import Filter
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/23'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+class ORM(object):
+
+    _table_name = None
+    _primary_key = None
+
+    def __init__(self):
+        pass
+
+    def create(self):
+        sql_stmt = ("INSERT INTO " + self._table_name + " (" +
+                    ', '.join(filter(lambda _key: _key != self._primary_key, self.__dict__.keys())) +
+                    ") VALUES (" +
+                    ', '.join(['%({0})s'.format(key)
+                               for key in filter(lambda _key: _key != self._primary_key, self.__dict__.keys())]) + ")")
+
+        cnx = db.cnxpool.get_connection()
+        cursor = cnx.cursor(dictionary=True, buffered=True)
+        try:
+            cursor.execute(sql_stmt, self.__dict__)
+            cnx.commit()
+        except errors.IntegrityError, e:
+            if e.errno == errorcode.ER_DUP_ENTRY:
+                ret = dict()
+                ret['state'] = ji.Common.exchange_state(40901)
+                ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], ': ', e.msg])
+                raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
+        finally:
+            cursor.close()
+            cnx.close()
+
+    def update(self):
+
+        if not self.exist():
+            ret = dict()
+            ret['state'] = ji.Common.exchange_state(40401)
+            ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], ': ', self._primary_key.__str__()])
+            raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
+
+        sql_stmt = ("UPDATE " + self._table_name + " SET " +
+                    ', '.join(['{0} = %({0})s'.format(key)
+                               for key in filter(lambda _key: _key != self._primary_key, self.__dict__.keys())]) +
+                    " WHERE " + '{0} = %({0})s'.format(self._primary_key))
+
+        cnx = db.cnxpool.get_connection()
+        cursor = cnx.cursor(dictionary=True, buffered=True)
+        try:
+            cursor.execute(sql_stmt, self.__dict__)
+            cnx.commit()
+        except errors.IntegrityError, e:
+            if e.errno == errorcode.ER_DUP_ENTRY:
+                ret = dict()
+                ret['state'] = ji.Common.exchange_state(40901)
+                ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], ': ', e.msg])
+                raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
+        finally:
+            cursor.close()
+            cnx.close()
+
+    def delete(self):
+        if not self.exist():
+            ret = dict()
+            ret['state'] = ji.Common.exchange_state(40401)
+            ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], ': ', self._primary_key.__str__()])
+            raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
+
+        sql_stmt = ("DELETE FROM " + self._table_name + " WHERE " + '{0} = %({0})s'.format(self._primary_key))
+
+        cnx = db.cnxpool.get_connection()
+        cursor = cnx.cursor(dictionary=True, buffered=True)
+        try:
+            cursor.execute(sql_stmt, self.__dict__)
+            cnx.commit()
+        finally:
+            cursor.close()
+            cnx.close()
+
+    def get(self):
+        sql_stmt = ("SELECT " + ', '.join(self.__dict__.keys()) + " FROM " + self._table_name +
+                    " WHERE " + '{0} = %({0})s'.format(self._primary_key) +
+                    " LIMIT 1")
+
+        cnx = db.cnxpool.get_connection()
+        cursor = cnx.cursor(dictionary=True, buffered=True)
+        try:
+            cursor.execute(sql_stmt, self.__dict__)
+            row = cursor.fetchone()
+        finally:
+            cursor.close()
+            cnx.close()
+
+        if isinstance(row, dict):
+            self.__dict__ = row
+        else:
+            ret = dict()
+            ret['state'] = ji.Common.exchange_state(40401)
+            ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], ': ', self._primary_key.__str__()])
+            raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
+
+    def exist(self):
+        sql_stmt = ("SELECT " + self._primary_key + " FROM " + self._table_name +
+                    " WHERE " + '{0} = %({0})s'.format(self._primary_key) + " LIMIT 1")
+
+        cnx = db.cnxpool.get_connection()
+        cursor = cnx.cursor(dictionary=True, buffered=True)
+        try:
+            cursor.execute(sql_stmt, self.__dict__)
+            row = cursor.fetchone()
+        finally:
+            cursor.close()
+            cnx.close()
+
+        if isinstance(row, dict):
+            return True
+
+        return False
+
+    def get_by(self, field):
+        sql_stmt = ("SELECT " + ', '.join(self.__dict__.keys()) +
+                    " FROM " + self._table_name + " WHERE " + '{0} = %({0})s'.format(field) + " LIMIT 1")
+
+        cnx = db.cnxpool.get_connection()
+        cursor = cnx.cursor(dictionary=True, buffered=True)
+        try:
+            cursor.execute(sql_stmt, self.__dict__)
+            row = cursor.fetchone()
+        finally:
+            cursor.close()
+            cnx.close()
+
+        if isinstance(row, dict):
+            self.__dict__ = row
+        else:
+            ret = dict()
+            ret['state'] = ji.Common.exchange_state(40401)
+            ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], ': ', self._primary_key.__str__()])
+            raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
+
+    def exist_by(self, field):
+        sql_field = field + ' = %(' + field + ')s'
+        sql_stmt = ("SELECT " + self._primary_key + " FROM " + self._table_name + " WHERE " + sql_field + " LIMIT 1")
+
+        cnx = db.cnxpool.get_connection()
+        cursor = cnx.cursor(dictionary=True, buffered=True)
+        try:
+            cursor.execute(sql_stmt, self.__dict__)
+            row = cursor.fetchone()
+        finally:
+            cursor.close()
+            cnx.close()
+
+        if isinstance(row, dict):
+            return True
+
+        return False
+
+    @staticmethod
+    def get_filter_keywords():
+        # 指定参与过滤的关键字及其数据库对应字段类型
+        """
+        使用示例
+        return {
+            'name': FilterFieldType.STR.value,
+            'remark': FilterFieldType.STR.value,
+            'age': FilterFieldType.INT.value
+        }
+        """
+        raise NotImplementedError()
+
+    @classmethod
+    def get_by_filter(cls, offset=0, limit=1000, order_by=None, order='asc', filter_str=''):
+        if order_by is None:
+            order_by = cls._primary_key
+
+        sql_stmt = ("SELECT * FROM " + cls._table_name + " ORDER BY " + order_by + " " + order +
+                    " LIMIT %(offset)s, %(limit)s")
+        sql_stmt_count = ("SELECT count(" + cls._primary_key + ") FROM " + cls._table_name)
+
+        where_str = Filter.filter_str_to_sql(allow_keywords=cls.get_filter_keywords(), filter_str=filter_str)
+        if where_str != '':
+            sql_stmt = ("SELECT * FROM " + cls._table_name + " WHERE " + where_str + " ORDER BY " + order_by + " " +
+                        order + " LIMIT %(offset)s, %(limit)s")
+            sql_stmt_count = ("SELECT count(" + cls._primary_key + ") FROM " + cls._table_name + " WHERE " + where_str)
+
+        cnx = db.cnxpool.get_connection()
+        cursor = cnx.cursor(dictionary=True, buffered=True)
+        try:
+            cursor.execute(sql_stmt, {'offset': offset, 'limit': limit})
+            rows = cursor.fetchall()
+            cursor.execute(sql_stmt_count)
+            count = cursor.fetchone()
+            return rows, count["count(" + cls._primary_key + ")"]
+        finally:
+            cursor.close()
+            cnx.close()
+
+    @staticmethod
+    def get_allow_update_keywords():
+        # 指定允许批量更新的字段
+        """
+        使用示例
+        return ['remark', 'age']
+        """
+        raise NotImplementedError()
+
+    @classmethod
+    def update_by_filter(cls, kv, filter_str=''):
+        # 过滤掉不予支持批量更新的字段
+        _kv = {}
+        for k, v in kv.iteritems():
+            if k in cls.get_allow_update_keywords():
+                _kv[k] = v
+
+        if _kv.__len__() < 1:
+            return
+
+        # set_str = ', '.join(map(lambda x: x + ' = %(' + x + ')s', _kv.keys()))
+        # 上面为通过map实现的方式
+        set_str = ', '.join(['{0} = %({0})s'.format(key) for key in _kv.keys()])
+        where_str = Filter.filter_str_to_sql(allow_keywords=cls.get_filter_keywords(), filter_str=filter_str)
+        sql_stmt = ("UPDATE " + cls._table_name + " SET " + set_str + " WHERE " + where_str)
+
+        cnx = db.cnxpool.get_connection()
+        cursor = cnx.cursor(dictionary=True, buffered=True)
+        try:
+            cursor.execute(sql_stmt, _kv)
+            cnx.commit()
+        finally:
+            cursor.close()
+            cnx.close()
+
+    @classmethod
+    def delete_by_filter(cls, filter_str=''):
+        where_str = Filter.filter_str_to_sql(allow_keywords=cls.get_filter_keywords(), filter_str=filter_str)
+        sql_stmt = ("DELETE FROM " + cls._table_name + " WHERE " + where_str)
+
+        cnx = db.cnxpool.get_connection()
+        cursor = cnx.cursor(dictionary=True, buffered=True)
+        try:
+            cursor.execute(sql_stmt)
+            cnx.commit()
+        finally:
+            cursor.close()
+            cnx.close()
+
+    @staticmethod
+    def get_allow_content_search_keywords():
+        # 指定允许全文检索的字段
+        """
+        使用示例
+        return ['name', 'remark']
+        """
+        raise NotImplementedError()
+
+    @classmethod
+    def content_search(cls, offset=0, limit=1000, order_by=None, order='asc', keyword=''):
+        if order_by is None:
+            order_by = cls._primary_key
+
+        _kv = dict()
+        _kv = _kv.fromkeys(cls.get_allow_content_search_keywords(), '%{0}%'.format(keyword))
+        where_str = ' OR '.join([k + ' LIKE %(' + k + ')s' for k in _kv.keys()])
+        sql_stmt = ("SELECT * FROM " + cls._table_name + " WHERE " + where_str + " ORDER BY " + order_by + " " + order +
+                    " LIMIT %(offset)s, %(limit)s")
+        sql_stmt_count = ("SELECT count(" + cls._primary_key + ") FROM " + cls._table_name + " WHERE " + where_str)
+
+        _kv.update({'offset': offset, 'limit': limit})
+        cnx = db.cnxpool.get_connection()
+        cursor = cnx.cursor(dictionary=True, buffered=True)
+        try:
+            cursor.execute(sql_stmt, _kv)
+            rows = cursor.fetchall()
+            cursor.execute(sql_stmt_count, _kv)
+            count = cursor.fetchone()
+            return rows, count["count(" + cls._primary_key + ")"]
+        finally:
+            cursor.close()
+            cnx.close()
+
+    @classmethod
+    def get_all(cls, order_by=None, order='asc'):
+        if order_by is None:
+            order_by = cls._primary_key
+
+        sql_stmt = ("SELECT * FROM " + cls._table_name + " ORDER BY " + order_by + " " + order)
+        sql_stmt_count = ("SELECT count(" + cls._primary_key + ") FROM " + cls._table_name)
+
+        cnx = db.cnxpool.get_connection()
+        cursor = cnx.cursor(dictionary=True, buffered=True)
+        try:
+            cursor.execute(sql_stmt)
+            rows = cursor.fetchall()
+            cursor.execute(sql_stmt_count)
+            count = cursor.fetchone()
+            return rows, count["count(" + cls._primary_key + ")"]
+        finally:
+            cursor.close()
+            cnx.close()
+

+ 68 - 0
models/os_init.py

@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+from models import FilterFieldType
+from models import ORM
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/23'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+class OSInit(ORM):
+
+    _table_name = 'os_init'
+    _primary_key = 'id'
+
+    def __init__(self):
+        super(OSInit, self).__init__()
+        self.id = 0
+        self.name = None
+        self.remark = ''
+
+    @staticmethod
+    def get_filter_keywords():
+        return {
+            'name': FilterFieldType.STR.value,
+            'remark': FilterFieldType.STR.value
+        }
+
+    @staticmethod
+    def get_allow_update_keywords():
+        return ['remark']
+
+    @staticmethod
+    def get_allow_content_search_keywords():
+        return ['name', 'remark']
+
+
+class OSInitWrite(ORM):
+
+    _table_name = 'os_init_write'
+    _primary_key = 'id'
+
+    def __init__(self):
+        super(OSInitWrite, self).__init__()
+        self.id = 0
+        self.os_init_id = None
+        self.path = ''
+        self.content = ''
+
+    @staticmethod
+    def get_filter_keywords():
+        return {
+            'os_init_id': FilterFieldType.STR.value,
+            'path': FilterFieldType.STR.value
+        }
+
+    @staticmethod
+    def get_allow_update_keywords():
+        return ['os_init_id', 'path']
+
+    @staticmethod
+    def get_allow_content_search_keywords():
+        return ['path', 'content']
+

+ 43 - 0
models/os_template.py

@@ -0,0 +1,43 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+from models import FilterFieldType
+from models import ORM
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/23'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+class OSTemplate(ORM):
+
+    _table_name = 'os_template'
+    _primary_key = 'id'
+
+    def __init__(self):
+        super(OSTemplate, self).__init__()
+        self.id = 0
+        self.label = None
+        self.name = None
+        self.active = None
+        self.os_init_id = None
+
+    @staticmethod
+    def get_filter_keywords():
+        return {
+            'name': FilterFieldType.STR.value,
+            'active': FilterFieldType.BOOL.value,
+            'os_init_id': FilterFieldType.INT.value
+        }
+
+    @staticmethod
+    def get_allow_update_keywords():
+        return ['active', 'os_init_id']
+
+    @staticmethod
+    def get_allow_content_search_keywords():
+        return ['name']
+

+ 58 - 0
models/rules.py

@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+from enum import Enum
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/21'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+class Rules(Enum):
+    OFFSET = ('regex:^\d{1,17}$', 'offset')
+    LIMIT = ('regex:^\d{1,17}$', 'limit')
+    PAGE = ('regex:^\d{1,17}$', 'page')
+    PAGE_SIZE = ('regex:^\d{1,17}$', 'page_size')
+    ORDER_BY = (basestring, 'order_by', (1, 30))
+    ORDER = (basestring, 'order', ['asc', 'desc'])
+    KEYWORD = (basestring, 'keyword')
+
+    ID = ('regex:^\d{1,17}$', 'id')
+
+    # 正则表达式方便校验其来自URL的参数
+    IP = 'regex:^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))$'
+
+    CONFIG_ID = (int, 'id')
+    GLUSTERFS_VOLUME = (basestring, 'glusterfs_volume')
+    VM_NETWORK = (basestring, 'vm_network')
+    VM_MANAGE_NETWORK = (basestring, 'vm_manage_network')
+    START_IP = (IP, 'start_ip')
+    END_IP = (IP, 'end_ip')
+    START_VNC_PORT = (int, 'start_vnc_port')
+    NETMASK = (IP, 'netmask')
+    GATEWAY = (IP, 'gateway')
+    DNS1 = (IP, 'dns1')
+    DNS2 = (IP, 'dns2')
+    RSA_PRIVATE = (basestring, 'rsa_private')
+    RSA_PUBLIC = (basestring, 'rsa_public')
+
+    CPU = (int, 'cpu')
+    MEMORY = (int, 'memory')
+    OS_TEMPLATE_ID = (basestring, 'os_template_id')
+    DISKS = (list, 'disks')
+    QUANTITY = (int, 'quantity')
+    NAME = (basestring, 'name')
+    PASSWORD = (basestring, 'password')
+    LEASE_TERM = (basestring, 'lease_term')
+
+    REMARK = (basestring, 'remark')
+    LABEL = (basestring, 'label')
+    ACTIVE = (bool, 'active')
+
+    OS_INIT_ID_EXT = (int, 'os_init_id')
+    OS_INIT_WRITE_PATH = (basestring, 'path')
+    OS_INIT_WRITE_CONTENT = (basestring, 'content')
+

+ 19 - 0
models/status.py

@@ -0,0 +1,19 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+from enum import Enum, IntEnum
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/22'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+class GuestStatus(IntEnum):
+    shutdown = 0
+    booting = 1
+    running = 2
+    rebooting = 3
+

+ 109 - 0
models/utils.py

@@ -0,0 +1,109 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from functools import wraps
+
+from flask import make_response, g, request
+from flask.wrappers import Response
+from werkzeug.utils import import_string, cached_property
+import jwt
+
+from models.initialize import *
+
+
+__author__ = 'James Iter'
+__date__ = '16/06/08'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2016 by James Iter.'
+
+
+class Utils(object):
+
+    @staticmethod
+    def dumps2response(func):
+        """
+        视图装饰器
+        http://dormousehole.readthedocs.org/en/latest/patterns/viewdecorators.html
+        """
+        @wraps(func)
+        def _dumps2response(*args, **kwargs):
+            ret = func(*args, **kwargs)
+
+            if func.func_name != 'r_before_request' and ret is None:
+                ret = dict()
+                ret['state'] = ji.Common.exchange_state(20000)
+
+            if isinstance(ret, dict) and 'state' in ret:
+                response = make_response()
+                response.data = json.dumps(ret, ensure_ascii=False)
+                response.status_code = int(ret['state']['code'])
+                if 'redirect' in ret and request.args.get('auto_redirect', 'True') == 'True':
+                    response.status_code = int(ret['redirect'].get('code', ret['state']['code']))
+                    response.headers['location'] = ret['redirect'].get('location', request.host_url)
+                    # 参考链接:
+                    # http://werkzeug.pocoo.org/docs/0.11/wrappers/#werkzeug.wrappers.BaseResponse.autocorrect_location_header
+                    # 变量操纵位置 werkzeug/wrappers.py
+                    response.autocorrect_location_header = False
+                return response
+
+            if isinstance(ret, Response):
+                return ret
+
+        return _dumps2response
+
+    @staticmethod
+    def superuser(func):
+        @wraps(func)
+        def _superuser(*args, **kwargs):
+            if not g.superuser:
+                ret = dict()
+                ret['state'] = ji.Common.exchange_state(40301)
+                return ret
+
+            return func(*args, **kwargs)
+
+        return _superuser
+
+    @staticmethod
+    def generate_token(uid):
+        payload = {
+            'iat': ji.Common.ts(),                                                  # 创建于
+            'nbf': ji.Common.ts(),                                                  # 在此之前不可用
+            'exp': ji.Common.ts() + app.config['token_ttl'],                        # 过期时间
+            'uid': uid
+        }
+        return jwt.encode(payload=payload, key=app.config['jwt_secret'], algorithm=app.config['jwt_algorithm'])
+
+    @staticmethod
+    def verify_token(token):
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        try:
+            payload = jwt.decode(jwt=token, key=app.config['jwt_secret'], algorithms=app.config['jwt_algorithm'])
+            return payload
+        except jwt.InvalidTokenError, e:
+            logger.error(e.message)
+        ret['state'] = ji.Common.exchange_state(41208)
+        raise ji.JITError(json.dumps(ret))
+
+
+class LazyView(object):
+    """
+    惰性载入视图
+    http://dormousehole.readthedocs.org/en/latest/patterns/lazyloading.html
+    """
+
+    def __init__(self, import_name):
+        self.__module__, self.__name__ = import_name.rsplit('.', 1)
+        self.import_name = import_name
+
+    @cached_property
+    def view(self):
+        return import_string(self.import_name)
+
+    def __call__(self, *args, **kwargs):
+        return self.view(*args, **kwargs)
+
+
+def add_rule(blueprint, rule, view_func=None, **options):
+    blueprint.add_url_rule(rule=rule, view_func=LazyView(''.join(['views.', view_func])), **options)

+ 10 - 0
requirements.txt

@@ -0,0 +1,10 @@
+Flask==0.10.1
+# mysql-connector-python
+enum34==1.1.2
+jimit==0.62
+requests==2.9.1
+PyJWT==1.4.1
+Flask-Session==0.3.0
+gunicorn
+eventlet
+redis

+ 45 - 0
route_table.py

@@ -0,0 +1,45 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+from models.utils import add_rule
+from views import config
+from views import guest
+from views import os_init
+from views import os_init_write
+from views import os_template
+
+
+__author__ = 'James Iter'
+__date__ = '2017/03/30'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+# JimV 配置操作
+add_rule(config.blueprint, '', view_func='config.r_create', methods=['POST'])
+# 只有一条记录,所以不指定 id
+add_rule(config.blueprint, '', view_func='config.r_update', methods=['PATCH'])
+add_rule(config.blueprint, '', view_func='config.r_get', methods=['GET'])
+
+# 系统初始化配置操作
+add_rule(os_init.blueprint, '', view_func='os_init.r_create', methods=['POST'])
+add_rule(os_init.blueprint, '/<_id>', view_func='os_init.r_update', methods=['PATCH'])
+add_rule(os_init.blueprint, '/<_id>', view_func='os_init.r_delete', methods=['DELETE'])
+add_rule(os_init.blueprint, '', view_func='os_init.r_get_by_filter', methods=['GET'])
+
+add_rule(os_init_write.blueprint, '', view_func='os_init_write.r_create', methods=['POST'])
+add_rule(os_init_write.blueprint, '/<_id>', view_func='os_init_write.r_update', methods=['PATCH'])
+add_rule(os_init_write.blueprint, '/<_id>', view_func='os_init_write.r_delete', methods=['DELETE'])
+add_rule(os_init_write.blueprint, '', view_func='os_init_write.r_get_by_filter', methods=['GET'])
+
+# 系统模板操作
+add_rule(os_template.blueprint, '', view_func='os_template.r_create', methods=['POST'])
+add_rule(os_template.blueprint, '/<_id>', view_func='os_template.r_update', methods=['PATCH'])
+add_rule(os_template.blueprint, '/<_id>', view_func='os_template.r_delete', methods=['DELETE'])
+add_rule(os_template.blueprint, '', view_func='os_template.r_get_by_filter', methods=['GET'])
+
+# Guest操作
+# 创建虚拟机
+add_rule(guest.blueprint, '', view_func='guest.r_create', methods=['POST'])
+

+ 48 - 0
state_code.py

@@ -0,0 +1,48 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+__author__ = 'James Iter'
+__date__ = '16/06/08'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2016 by James Iter.'
+
+
+own_state_branch = {
+    # ----------以上将集成至jimit库中------------
+    '40450': {
+        'code': '40450',
+        'zh-cn': u'目标操作系统模板未找到'
+    },
+    '40451': {
+        'code': '40451',
+        'zh-cn': u'目标操作系统初始化操作未找到'
+    },
+    '41250': {
+        'code': '41250',
+        'zh-cn': u'验证签名失败'
+    },
+    '41251': {
+        'code': '41251',
+        'zh-cn': u'起止IP必须在同一个网段中'
+    },
+    '41252': {
+        'code': '41252',
+        'zh-cn': u'网关必须与将分配给Guest的IP,处于同一个网段中'
+    },
+    '41253': {
+        'code': '41253',
+        'zh-cn': u'网关不能是网络地址或广播地址'
+    },
+    '41254': {
+        'code': '41254',
+        'zh-cn': u'起始的可用IP地址必须小于结束的可用IP地址'
+    },
+    '50050': {
+        'code': '50050',
+        'zh-cn': u'MySQL 链接或执行出错'
+    },
+    '50350': {
+        'code': '50350',
+        'zh-cn': u'无可用IP地址,请联系 JimV 管理员'
+    },
+}

+ 19 - 0
tests/__init__.py

@@ -0,0 +1,19 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import os
+
+
+__author__ = 'James Iter'
+__date__ = '2017/03/31'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+def load_tests(loader, standard_tests, pattern='test_*.py'):
+    # top level directory cached on loader instance
+    this_dir = os.path.dirname(__file__)
+    package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
+    standard_tests.addTests(package_tests)
+    return standard_tests

+ 18 - 0
tests/main.py

@@ -0,0 +1,18 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import tests
+import unittest
+
+
+__author__ = 'James Iter'
+__date__ = '2017/03/31'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+if __name__ == '__main__':
+    suite = tests.load_tests(unittest.TestLoader(), unittest.TestSuite())
+    unittest.TextTestRunner(verbosity=2).run(suite)
+

+ 94 - 0
tests/test_config.py

@@ -0,0 +1,94 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import requests
+import json
+import unittest
+
+
+__author__ = 'James Iter'
+__date__ = '2017/4/3'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+class TestConfig(unittest.TestCase):
+
+    base_url = 'http://127.0.0.1:8008/api'
+    config_id = 0
+
+    def setUp(self):
+        pass
+
+    def tearDown(self):
+        pass
+
+    # 创建 JimV 配置
+    def test_11_create(self):
+        payload = {
+            "glusterfs_volume": "gv0",
+            "vm_network": "net-br0",
+            "vm_manage_network": "net-br0",
+            "start_ip": "10.10.3.1",
+            "end_ip": "10.10.6.254",
+            "start_vnc_port": 15900,
+            "netmask": "255.255.240.0",
+            "gateway": "10.10.15.254",
+            "dns1": "10.1.17.1",
+            "dns2": "223.5.5.5",
+            "rsa_private": "",
+            "rsa_public": ""
+        }
+
+        url = TestConfig.base_url + '/config'
+        headers = {'content-type': 'application/json'}
+        r = requests.post(url, data=json.dumps(payload), headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        TestConfig.config_id = j_r['data']['id']
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 获取配置
+    def test_12_get(self):
+        url = TestConfig.base_url + '/config'
+        headers = {'content-type': 'application/json'}
+        r = requests.get(url, headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 更新配置
+    def test_13_update(self):
+        payload = {
+            "rsa_public": "what?"
+        }
+
+        url = TestConfig.base_url + '/config'
+        headers = {'content-type': 'application/json'}
+        r = requests.patch(url, data=json.dumps(payload), headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 校验更新结果
+    def test_14_get(self):
+        url = TestConfig.base_url + '/config'
+        headers = {'content-type': 'application/json'}
+        r = requests.get(url, headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+        self.assertEqual('what?', j_r['data']['rsa_public'])
+
+    # 删除配置
+    def test_15_delete(self):
+        url = TestConfig.base_url + '/config'
+        headers = {'content-type': 'application/json'}
+        r = requests.delete(url, headers=headers)
+        self.assertEqual(405, r.status_code)
+
+
+if __name__ == '__main__':
+    unittest.main()
+

+ 86 - 0
tests/test_os_init.py

@@ -0,0 +1,86 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import requests
+import json
+import unittest
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/31'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+class TestOSInit(unittest.TestCase):
+
+    base_url = 'http://127.0.0.1:8008/api'
+    os_init_id = 0
+
+    def setUp(self):
+        pass
+
+    def tearDown(self):
+        pass
+
+    # 创建系统初始化组
+    def test_11_create(self):
+        payload = {
+            "name": 'CentOS-Systemd',
+            "remark": u'用作红帽 Systemd 系列的系统初始化。初始化操作依据 CentOS 7 来实现。'
+        }
+
+        url = TestOSInit.base_url + '/os_init'
+        headers = {'content-type': 'application/json'}
+        r = requests.post(url, data=json.dumps(payload), headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 获取系统初始化组列表
+    def test_12_get(self):
+        url = TestOSInit.base_url + '/os_init'
+        headers = {'content-type': 'application/json'}
+        r = requests.get(url, headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        TestOSInit.os_init_id = j_r['data'][0]['id']
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 创建更新系统初始化组
+    def test_13_update(self):
+        payload = {
+            "name": 'RedHat-Systemd'
+        }
+
+        url = TestOSInit.base_url + '/os_init/' + TestOSInit.os_init_id.__str__()
+        headers = {'content-type': 'application/json'}
+        r = requests.patch(url, data=json.dumps(payload), headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 校验系统初始化组列表更新结果
+    def test_14_get(self):
+        url = TestOSInit.base_url + '/os_init'
+        headers = {'content-type': 'application/json'}
+        r = requests.get(url, headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+        self.assertEqual('RedHat-Systemd', j_r['data'][0]['name'])
+
+    # 删除系统初始化组列表更新结果
+    def test_15_delete(self):
+        url = TestOSInit.base_url + '/os_init/' + TestOSInit.os_init_id.__str__()
+        headers = {'content-type': 'application/json'}
+        r = requests.delete(url, headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+
+if __name__ == '__main__':
+    unittest.main()
+

+ 161 - 0
tests/test_os_init_write.py

@@ -0,0 +1,161 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import requests
+import json
+import unittest
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/31'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+class TestOSInitWrite(unittest.TestCase):
+
+    base_url = 'http://127.0.0.1:8008/api'
+    os_init_id = 0
+    os_init_write_id = 0
+
+    def setUp(self):
+        pass
+
+    def tearDown(self):
+        pass
+
+    # 创建系统初始化组
+    def test_11_create(self):
+        payload = {
+            "name": "CentOS-Systemd",
+            "remark": u"用作红帽 Systemd 系列的系统初始化。初始化操作依据 CentOS 7 来实现。"
+        }
+
+        url = TestOSInitWrite.base_url + '/os_init'
+        headers = {'content-type': 'application/json'}
+        r = requests.post(url, data=json.dumps(payload), headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        TestOSInitWrite.os_init_id = j_r['data']['id']
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 添加系统初始化操作
+    def test_21_create(self):
+        payload = {
+            "os_init_id": TestOSInitWrite.os_init_id,
+            "path": "/etc/resolv.conf",
+            "content": "".join([
+                "nameserver {DNS1}",
+                "nameserver {DNS2}"
+            ])
+        }
+
+        url = TestOSInitWrite.base_url + '/os_init_write'
+        headers = {'content-type': 'application/json'}
+        r = requests.post(url, data=json.dumps(payload), headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 添加系统初始化操作
+    def test_22_create(self):
+        payload = {
+            "os_init_id": TestOSInitWrite.os_init_id,
+            "path": "/etc/sysconfig/network-scripts/ifcfg-eth0",
+            "content": "\n".join([
+                "DEVICE=eth0",
+                "TYPE=Ethernet",
+                "ONBOOT=yes",
+                "BOOTPROTO=\"static\"",
+                "IPADDR={IP}",
+                "NETMASK={NETMASK}",
+                "GATEWAY={GATEWAY}",
+                "DNS1={DNS1}",
+                "DNS2={DNS2}",
+                "IPV6INIT=no",
+                "NAME=eth0"
+            ])
+        }
+
+        url = TestOSInitWrite.base_url + '/os_init_write'
+        headers = {'content-type': 'application/json'}
+        r = requests.post(url, data=json.dumps(payload), headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 添加系统初始化操作
+    def test_23_create(self):
+        payload = {
+            "os_init_id": TestOSInitWrite.os_init_id,
+            "path": "/etc/hostname",
+            "content": "{HOSTNAME}"
+        }
+
+        url = TestOSInitWrite.base_url + '/os_init_write'
+        headers = {'content-type': 'application/json'}
+        r = requests.post(url, data=json.dumps(payload), headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        TestOSInitWrite.os_init_write_id = j_r['data']['id']
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 添加系统初始化操作
+    def test_24_create(self):
+        payload = {
+            "os_init_id": TestOSInitWrite.os_init_id,
+            "path": "/etc/hostname",
+            "content": "{HOSTNAME}"
+        }
+
+        url = TestOSInitWrite.base_url + '/os_init_write'
+        headers = {'content-type': 'application/json'}
+        r = requests.post(url, data=json.dumps(payload), headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('40901', j_r['state']['sub']['code'])
+
+    def test_25_get(self):
+        url = TestOSInitWrite.base_url + '/os_init_write'
+        headers = {'content-type': 'application/json'}
+        r = requests.get(url, headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+    def test_26_update(self):
+        payload = {
+            "os_init_id": TestOSInitWrite.os_init_id,
+            "path": "/etc/hostname",
+            "content": "hostname"
+        }
+
+        url = TestOSInitWrite.base_url + '/os_init_write/' + TestOSInitWrite.os_init_write_id.__str__()
+        headers = {'content-type': 'application/json'}
+        r = requests.patch(url, data=json.dumps(payload), headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+    def test_27_delete(self):
+        url = TestOSInitWrite.base_url + '/os_init_write/' + TestOSInitWrite.os_init_write_id.__str__()
+        headers = {'content-type': 'application/json'}
+        r = requests.delete(url, headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 删除系统初始化组列表更新结果
+    def test_31_delete(self):
+        url = TestOSInitWrite.base_url + '/os_init/' + TestOSInitWrite.os_init_id.__str__()
+        headers = {'content-type': 'application/json'}
+        r = requests.delete(url, headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+
+if __name__ == '__main__':
+    unittest.main()
+

+ 87 - 0
tests/test_os_template.py

@@ -0,0 +1,87 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import requests
+import json
+import unittest
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/31'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+class TestOSTemplate(unittest.TestCase):
+
+    base_url = 'http://127.0.0.1:8008/api'
+    os_template_id = 0
+
+    def setUp(self):
+        pass
+
+    def tearDown(self):
+        pass
+
+    # 创建系统模板
+    def test_11_create(self):
+        payload = {
+            "label": "CentOS-7.2",
+            "name": "centos72_multi-user_2016-09-15_128G.qcow2",
+            "active": True
+        }
+
+        url = TestOSTemplate.base_url + '/os_template'
+        headers = {'content-type': 'application/json'}
+        r = requests.post(url, data=json.dumps(payload), headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        TestOSTemplate.os_template_id = j_r['data']['id']
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 获取系统模板列表
+    def test_12_get(self):
+        url = TestOSTemplate.base_url + '/os_template'
+        headers = {'content-type': 'application/json'}
+        r = requests.get(url, headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 更新系统模板
+    def test_13_update(self):
+        payload = {
+            "label": 'CentOS-72'
+        }
+
+        url = TestOSTemplate.base_url + '/os_template/' + TestOSTemplate.os_template_id.__str__()
+        headers = {'content-type': 'application/json'}
+        r = requests.patch(url, data=json.dumps(payload), headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+    # 校验系统模板更新结果
+    def test_14_get(self):
+        url = TestOSTemplate.base_url + '/os_template'
+        headers = {'content-type': 'application/json'}
+        r = requests.get(url, headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+        self.assertEqual('CentOS-72', j_r['data'][0]['label'])
+
+    # 删除系统模板
+    def test_15_delete(self):
+        url = TestOSTemplate.base_url + '/os_template/' + TestOSTemplate.os_template_id.__str__()
+        headers = {'content-type': 'application/json'}
+        r = requests.delete(url, headers=headers)
+        j_r = json.loads(r.content)
+        print json.dumps(j_r, ensure_ascii=False)
+        self.assertEqual('200', j_r['state']['code'])
+
+
+if __name__ == '__main__':
+    unittest.main()
+

+ 7 - 0
views/__init__.py

@@ -0,0 +1,7 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+__author__ = 'James Iter'
+__date__ = '2017/3/21'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'

+ 203 - 0
views/config.py

@@ -0,0 +1,203 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+from flask import Blueprint, g
+from flask import request
+import jimit as ji
+import json
+
+from models import Config
+from models import Rules
+from models import Utils
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/21'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+blueprint = Blueprint(
+    'config',
+    __name__,
+    url_prefix='/api/config'
+)
+
+
+@Utils.dumps2response
+def r_create():
+
+    config = Config()
+
+    args_rules = [
+        Rules.GLUSTERFS_VOLUME.value,
+        Rules.VM_NETWORK.value,
+        Rules.VM_MANAGE_NETWORK.value,
+        Rules.START_IP.value,
+        Rules.END_IP.value,
+        Rules.START_VNC_PORT.value,
+        Rules.NETMASK.value,
+        Rules.GATEWAY.value,
+        Rules.DNS1.value,
+        Rules.DNS2.value,
+        Rules.RSA_PRIVATE.value,
+        Rules.RSA_PUBLIC.value
+    ]
+
+    config.id = 1
+    config.glusterfs_volume = request.json.get('glusterfs_volume')
+    config.vm_network = request.json.get('vm_network')
+    config.vm_manage_network = request.json.get('vm_manage_network')
+    config.start_ip = request.json.get('start_ip')
+    config.end_ip = request.json.get('end_ip')
+    config.start_vnc_port = request.json.get('start_vnc_port')
+    config.netmask = request.json.get('netmask')
+    config.gateway = request.json.get('gateway')
+    config.dns1 = request.json.get('dns1')
+    config.dns2 = request.json.get('dns2')
+    config.rsa_private = request.json.get('rsa_private')
+    config.rsa_public = request.json.get('rsa_public')
+
+    try:
+        ji.Check.previewing(args_rules, config.__dict__)
+
+        config.check_ip()
+        config.generate_available_ip2set()
+        config.generate_available_vnc_port()
+        config.create()
+        g.config = None
+
+        config.id = 1
+        config.get()
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        ret['data'] = config.__dict__
+        return ret
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+
+@Utils.dumps2response
+def r_update():
+
+    config = Config()
+
+    args_rules = [
+    ]
+
+    if 'glusterfs_volume' in request.json:
+        args_rules.append(
+            Rules.GLUSTERFS_VOLUME.value,
+        )
+
+    if 'vm_network' in request.json:
+        args_rules.append(
+            Rules.VM_NETWORK.value,
+        )
+
+    if 'vm_manage_network' in request.json:
+        args_rules.append(
+            Rules.VM_MANAGE_NETWORK.value,
+        )
+
+    if 'start_ip' in request.json:
+        args_rules.append(
+            Rules.START_IP.value,
+        )
+
+    if 'end_ip' in request.json:
+        args_rules.append(
+            Rules.END_IP.value,
+        )
+
+    if 'start_vnc_port' in request.json:
+        args_rules.append(
+            Rules.START_VNC_PORT.value,
+        )
+
+    if 'netmask' in request.json:
+        args_rules.append(
+            Rules.NETMASK.value,
+        )
+
+    if 'gateway' in request.json:
+        args_rules.append(
+            Rules.GATEWAY.value,
+        )
+
+    if 'dns1' in request.json:
+        args_rules.append(
+            Rules.DNS1.value,
+        )
+
+    if 'dns2' in request.json:
+        args_rules.append(
+            Rules.DNS2.value,
+        )
+
+    if 'rsa_private' in request.json:
+        args_rules.append(
+            Rules.RSA_PRIVATE.value,
+        )
+
+    if 'rsa_public' in request.json:
+        args_rules.append(
+            Rules.RSA_PUBLIC.value
+        )
+
+    if args_rules.__len__() < 1:
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        return ret
+
+    try:
+        config.id = 1
+        ji.Check.previewing(args_rules, request.json)
+        config.get()
+
+        config.glusterfs_volume = request.json.get('glusterfs_volume', config.glusterfs_volume)
+        config.vm_network = request.json.get('vm_network', config.vm_network)
+        config.vm_manage_network = request.json.get('vm_manage_network', config.vm_manage_network)
+        config.start_ip = request.json.get('start_ip', config.start_ip)
+        config.end_ip = request.json.get('end_ip', config.end_ip)
+        config.start_vnc_port = request.json.get('start_vnc_port', config.start_vnc_port)
+        config.netmask = request.json.get('netmask', config.netmask)
+        config.gateway = request.json.get('gateway', config.gateway)
+        config.dns1 = request.json.get('dns1', config.dns1)
+        config.dns2 = request.json.get('dns2', config.dns2)
+        config.rsa_private = request.json.get('rsa_private', config.rsa_private)
+        config.rsa_public = request.json.get('rsa_public', config.rsa_public)
+
+        config.check_ip()
+        config.generate_available_ip2set()
+        config.generate_available_vnc_port()
+        config.update()
+        g.config = None
+
+        config.get()
+
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        ret['data'] = config.__dict__
+        return ret
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+
+@Utils.dumps2response
+def r_get():
+
+    config = Config()
+
+    try:
+        config.id = 1
+        config.get()
+
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        ret['data'] = config.__dict__
+        return ret
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+

+ 158 - 0
views/guest.py

@@ -0,0 +1,158 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import copy
+from flask import Blueprint
+from flask import request, g
+import json
+from uuid import uuid4
+import jimit as ji
+
+from models import OSInitWrite
+from models.initialize import app
+from models import Config
+from models import GuestDisk
+from models import Rules
+from models import Utils
+from models import Guest
+from models import OSTemplate
+from models import GuestXML
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/22'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+blueprint = Blueprint(
+    'guest',
+    __name__,
+    url_prefix='/api/guest'
+)
+
+
+@Utils.dumps2response
+def r_create():
+
+    args_rules = [
+        Rules.CPU.value,
+        Rules.MEMORY.value,
+        Rules.OS_TEMPLATE_ID.value,
+        Rules.DISKS.value,
+        Rules.QUANTITY.value,
+        Rules.NAME.value,
+        Rules.PASSWORD.value,
+        Rules.LEASE_TERM.value
+    ]
+
+    try:
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+
+        ji.Check.previewing(args_rules, request.json)
+
+        if g.config is None:
+            config = Config()
+            config.id = 1
+            config.get()
+            g.config = config
+
+        assert isinstance(g.config, Config)
+
+        os_template = OSTemplate()
+        os_template.id = request.json.get('os_template_id')
+        if not os_template.exist():
+            ret['state'] = ji.Common.exchange_state(40450)
+            ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], ': ', os_template.id])
+            return ret
+
+        os_template.get()
+
+        os_init_writes = OSInitWrite.get_by_filter(
+            filter_str='os_init_id:in:' + os_template.os_init_id.__str__())
+
+        if g.r.scard(app.config['ip_available_set']) < 1:
+            ret['state'] = ji.Common.exchange_state(50350)
+            return ret
+
+        quantity = request.json.get('quantity')
+
+        while quantity:
+            quantity -= 1
+            guest = Guest()
+            guest.uuid = uuid4().__str__()
+            guest.cpu = request.json.get('cpu')
+            # 虚拟机内存单位默认KiB,所以这个乘1024的平方,使得用户填入的单位变为GiB
+            guest.memory = request.json.get('memory') * 1024 * 1024
+            guest.os_template_id = request.json.get('os_template_id')
+            guest.name = request.json.get('name')
+
+            guest.password = request.json.get('password')
+            if guest.password is None or guest.password.__len__() < 1:
+                guest.password = ji.Common.generate_random_code(length=16)
+
+            while guest.name.__len__() < 1 or guest.exist_by('name'):
+                guest.name = ji.Common.generate_random_code(length=8)
+
+            guest.ip = g.r.spop(app.config['ip_available_set'])
+            g.r.sadd(app.config['ip_used_set'], guest.ip)
+
+            guest.network = g.config.vm_network
+            guest.manage_network = g.config.vm_manage_network
+
+            guest.vnc_port = g.r.spop(app.config['vnc_port_available_set'])
+            g.r.sadd(app.config['vnc_port_used_set'], guest.vnc_port)
+
+            guest.vnc_password = ji.Common.generate_random_code(length=16)
+
+            guest_disks = list()
+            guest_disks.append({'label': uuid4(), 'size': -1, 'format': 'qcow2'})
+
+            for i, disk in enumerate(request.json.get('disks')):
+                guest_disk = GuestDisk()
+
+                guest_disk.size = disk.get('size')
+                # TODO: 设定磁盘最大大小
+                if not isinstance(guest_disk.size, int) or guest_disk.size < 1:
+                    continue
+
+                guest_disk.guest_uuid = guest.uuid
+                guest_disk.label = uuid4()
+                guest_disk.sequence = i + 1
+                guest_disk.format = 'qcow2'
+                guest_disk.create()
+
+                guest_disks.append({'label': guest_disk.label, 'size': guest_disk.size, 'format': guest_disk.format})
+
+            guest.create()
+            guest_xml = GuestXML(guest=guest, disks=guest_disks, g_config=g.config)
+            guest_xml.get_domain()
+
+            # 替换占位符为有效内容
+            _os_init_writes = copy.deepcopy(os_init_writes)
+            for k, v in _os_init_writes:
+                _os_init_writes[k] = v.replace('{IP}', guest.ip).\
+                    replace('{HOSTNAME}', guest.name).\
+                    replace('{NETMASK}', g.config.netmask).\
+                    replace('{GATEWAY}', g.config.gateway).\
+                    replace('{DNS1}', g.config.dns1).\
+                    replace('{DNS2}', g.config.dns2)
+
+            create_vm_msg = {
+                'uuid': guest.uuid,
+                'glusterfs_volume': g.config.glusterfs_volume,
+                'template_path': 'template_pool/' + os_template.name,
+                'guest_disks': guest_disks,
+                'writes': _os_init_writes,
+                'password': guest.password,
+                'xml': guest_xml.get_domain()
+            }
+            g.r.rpush(app.config['vm_create_queue'], json.dumps(create_vm_msg, ensure_ascii=False))
+
+        return ret
+
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+

+ 205 - 0
views/os_init.py

@@ -0,0 +1,205 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+from flask import Blueprint
+from flask import request, g
+import jimit as ji
+import json
+
+from models import OSInit
+from models import OSInitWrite
+from models import Rules
+from models import Utils
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/30'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+blueprint = Blueprint(
+    'os_init',
+    __name__,
+    url_prefix='/api/os_init'
+)
+
+
+@Utils.dumps2response
+def r_create():
+
+    os_init = OSInit()
+
+    args_rules = [
+        Rules.NAME.value,
+        Rules.REMARK.value
+    ]
+
+    os_init.name = request.json.get('name')
+    os_init.remark = request.json.get('remark')
+
+    try:
+        ji.Check.previewing(args_rules, os_init.__dict__)
+
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+
+        if os_init.exist_by('name'):
+            ret['state'] = ji.Common.exchange_state(40901)
+            ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], ': ', os_init.name])
+            return ret
+
+        os_init.create()
+        os_init.get_by('name')
+        ret['data'] = os_init.__dict__
+        return ret
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+
+@Utils.dumps2response
+def r_update(_id):
+
+    os_init = OSInit()
+
+    args_rules = [
+        Rules.ID.value
+    ]
+
+    if 'name' in request.json:
+        args_rules.append(
+            Rules.NAME.value,
+        )
+
+    if 'remark' in request.json:
+        args_rules.append(
+            Rules.REMARK.value,
+        )
+
+    if args_rules.__len__() < 2:
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        return ret
+
+    request.json['id'] = _id
+
+    try:
+        ji.Check.previewing(args_rules, request.json)
+        os_init.id = request.json.get('id')
+        os_init.get()
+        os_init.name = request.json.get('name', os_init.name)
+        os_init.remark = request.json.get('remark', os_init.remark)
+
+        os_init.update()
+        g.config = None
+
+        os_init.get()
+
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        ret['data'] = os_init.__dict__
+        return ret
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+
+@Utils.dumps2response
+def r_delete(_id):
+    os_init = OSInit()
+
+    args_rules = [
+        Rules.ID.value
+    ]
+    os_init.id = _id
+
+    try:
+        ji.Check.previewing(args_rules, os_init.__dict__)
+
+        if os_init.exist():
+            os_init.delete()
+            OSInitWrite.delete_by_filter(filter_str='os_init_id:in:' + os_init.id.__str__())
+        else:
+            ret = dict()
+            ret['state'] = ji.Common.exchange_state(40401)
+            return ret
+
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+
+@Utils.dumps2response
+def r_get_by_filter():
+    page = str(request.args.get('page', 1))
+    page_size = str(request.args.get('page_size', 50))
+
+    args_rules = [
+        Rules.PAGE.value,
+        Rules.PAGE_SIZE.value
+    ]
+
+    try:
+        ji.Check.previewing(args_rules, {'page': page, 'page_size': page_size})
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+    page = int(page)
+    page_size = int(page_size)
+
+    # 把page和page_size换算成offset和limit
+    offset = (page - 1) * page_size
+    # offset, limit将覆盖page及page_size的影响
+    offset = str(request.args.get('offset', offset))
+    limit = str(request.args.get('limit', page_size))
+
+    order_by = request.args.get('order_by', 'id')
+    order = request.args.get('order', 'asc')
+    filter_str = request.args.get('filter', '')
+
+    args_rules = [
+        Rules.OFFSET.value,
+        Rules.LIMIT.value,
+        Rules.ORDER_BY.value,
+        Rules.ORDER.value
+    ]
+
+    try:
+        ji.Check.previewing(args_rules, {'offset': offset, 'limit': limit, 'order_by': order_by, 'order': order})
+        offset = int(offset)
+        limit = int(limit)
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        ret['data'] = list()
+        ret['paging'] = {'total': 0, 'offset': offset, 'limit': limit, 'page': page, 'page_size': page_size,
+                         'next': '', 'prev': '', 'first': '', 'last': ''}
+
+        ret['data'], ret['paging']['total'] = OSInit.get_by_filter(offset=offset, limit=limit, order_by=order_by,
+                                                                   order=order, filter_str=filter_str)
+
+        host_url = request.host_url.rstrip('/')
+        other_str = '&filter=' + filter_str + '&order=' + order + '&order_by=' + order_by
+        last_pagination = (ret['paging']['total'] + page_size - 1) / page_size
+
+        if page <= 1:
+            ret['paging']['prev'] = host_url + blueprint.url_prefix + '?page=1&page_size=' + page_size.__str__() + \
+                                    other_str
+        else:
+            ret['paging']['prev'] = host_url + blueprint.url_prefix + '?page=' + str(page-1) + '&page_size=' + \
+                                    page_size.__str__() + other_str
+
+        if page >= last_pagination:
+            ret['paging']['next'] = host_url + blueprint.url_prefix + '?page=' + last_pagination.__str__() + \
+                                    '&page_size=' + page_size.__str__() + other_str
+        else:
+            ret['paging']['next'] = host_url + blueprint.url_prefix + '?page=' + str(page+1) + '&page_size=' + \
+                                    page_size.__str__() + other_str
+
+        ret['paging']['first'] = host_url + blueprint.url_prefix + '?page=1&page_size=' + \
+            page_size.__str__() + other_str
+        ret['paging']['last'] = \
+            host_url + blueprint.url_prefix + '?page=' + last_pagination.__str__() + '&page_size=' + \
+            page_size.__str__() + other_str
+
+        return ret
+    except ji.PreviewingError, e:
+        return json.loads(e.message)

+ 211 - 0
views/os_init_write.py

@@ -0,0 +1,211 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+from flask import Blueprint
+from flask import request
+import jimit as ji
+import json
+
+from models import OSInit
+from models import OSInitWrite
+from models import Rules
+from models import Utils
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/30'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+blueprint = Blueprint(
+    'os_init_write',
+    __name__,
+    url_prefix='/api/os_init_write'
+)
+
+
+@Utils.dumps2response
+def r_create():
+
+    os_init = OSInit()
+    os_init_write = OSInitWrite()
+
+    args_rules = [
+        Rules.OS_INIT_ID_EXT.value,
+        Rules.OS_INIT_WRITE_PATH.value,
+        Rules.OS_INIT_WRITE_CONTENT.value
+    ]
+
+    os_init_write.os_init_id = request.json.get('os_init_id')
+    os_init_write.path = request.json.get('path')
+    os_init_write.content = request.json.get('content')
+
+    try:
+        ji.Check.previewing(args_rules, os_init_write.__dict__)
+
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+
+        os_init.id = os_init_write.os_init_id
+        if not os_init.exist():
+            ret['state'] = ji.Common.exchange_state(40401)
+            ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], ': ', os_init.id])
+            return ret
+
+        if os_init_write.exist_by('path'):
+            ret['state'] = ji.Common.exchange_state(40901)
+            ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], ': ', os_init_write.path])
+            return ret
+
+        os_init_write.create()
+        os_init_write.get_by('path')
+        ret['data'] = os_init_write.__dict__
+        return ret
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+
+@Utils.dumps2response
+def r_update(_id):
+
+    os_init_write = OSInitWrite()
+
+    args_rules = [
+        Rules.ID.value
+    ]
+
+    if 'path' in request.json:
+        args_rules.append(
+            Rules.OS_INIT_WRITE_PATH.value,
+        )
+
+    if 'content' in request.json:
+        args_rules.append(
+            Rules.OS_INIT_WRITE_CONTENT.value,
+        )
+
+    if args_rules.__len__() < 2:
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        return ret
+
+    request.json['id'] = _id
+
+    try:
+        ji.Check.previewing(args_rules, request.json)
+        os_init_write.id = request.json.get('id')
+        os_init_write.get()
+        os_init_write.path = request.json.get('path', os_init_write.path)
+        os_init_write.content = request.json.get('content', os_init_write.content)
+
+        os_init_write.update()
+        os_init_write.get()
+
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        ret['data'] = os_init_write.__dict__
+        return ret
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+
+@Utils.dumps2response
+def r_delete(_id):
+    os_init_write = OSInitWrite()
+
+    args_rules = [
+        Rules.ID.value
+    ]
+    os_init_write.id = _id
+
+    try:
+        ji.Check.previewing(args_rules, os_init_write.__dict__)
+
+        if os_init_write.exist():
+            os_init_write.delete()
+        else:
+            ret = dict()
+            ret['state'] = ji.Common.exchange_state(40401)
+            return ret
+
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+
+@Utils.dumps2response
+def r_get_by_filter():
+    page = str(request.args.get('page', 1))
+    page_size = str(request.args.get('page_size', 50))
+
+    args_rules = [
+        Rules.PAGE.value,
+        Rules.PAGE_SIZE.value
+    ]
+
+    try:
+        ji.Check.previewing(args_rules, {'page': page, 'page_size': page_size})
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+    page = int(page)
+    page_size = int(page_size)
+
+    # 把page和page_size换算成offset和limit
+    offset = (page - 1) * page_size
+    # offset, limit将覆盖page及page_size的影响
+    offset = str(request.args.get('offset', offset))
+    limit = str(request.args.get('limit', page_size))
+
+    order_by = request.args.get('order_by', 'id')
+    order = request.args.get('order', 'asc')
+    filter_str = request.args.get('filter', '')
+
+    args_rules = [
+        Rules.OFFSET.value,
+        Rules.LIMIT.value,
+        Rules.ORDER_BY.value,
+        Rules.ORDER.value
+    ]
+
+    try:
+        ji.Check.previewing(args_rules, {'offset': offset, 'limit': limit, 'order_by': order_by, 'order': order})
+        offset = int(offset)
+        limit = int(limit)
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        ret['data'] = list()
+        ret['paging'] = {'total': 0, 'offset': offset, 'limit': limit, 'page': page, 'page_size': page_size,
+                         'next': '', 'prev': '', 'first': '', 'last': ''}
+
+        ret['data'], ret['paging']['total'] = OSInitWrite.get_by_filter(offset=offset, limit=limit, order_by=order_by,
+                                                                        order=order, filter_str=filter_str)
+
+        host_url = request.host_url.rstrip('/')
+        other_str = '&filter=' + filter_str + '&order=' + order + '&order_by=' + order_by
+        last_pagination = (ret['paging']['total'] + page_size - 1) / page_size
+
+        if page <= 1:
+            ret['paging']['prev'] = host_url + blueprint.url_prefix + '?page=1&page_size=' + page_size.__str__() + \
+                                    other_str
+        else:
+            ret['paging']['prev'] = host_url + blueprint.url_prefix + '?page=' + str(page-1) + '&page_size=' + \
+                                    page_size.__str__() + other_str
+
+        if page >= last_pagination:
+            ret['paging']['next'] = host_url + blueprint.url_prefix + '?page=' + last_pagination.__str__() + \
+                                    '&page_size=' + page_size.__str__() + other_str
+        else:
+            ret['paging']['next'] = host_url + blueprint.url_prefix + '?page=' + str(page+1) + '&page_size=' + \
+                                    page_size.__str__() + other_str
+
+        ret['paging']['first'] = host_url + blueprint.url_prefix + '?page=1&page_size=' + \
+            page_size.__str__() + other_str
+        ret['paging']['last'] = \
+            host_url + blueprint.url_prefix + '?page=' + last_pagination.__str__() + '&page_size=' + \
+            page_size.__str__() + other_str
+
+        return ret
+    except ji.PreviewingError, e:
+        return json.loads(e.message)

+ 218 - 0
views/os_template.py

@@ -0,0 +1,218 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+from flask import Blueprint
+from flask import request
+import jimit as ji
+import json
+
+from models import OSTemplate
+from models import Rules
+from models import Utils
+
+
+__author__ = 'James Iter'
+__date__ = '2017/3/30'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+blueprint = Blueprint(
+    'os_template',
+    __name__,
+    url_prefix='/api/os_template'
+)
+
+
+@Utils.dumps2response
+def r_create():
+
+    os_template = OSTemplate()
+
+    args_rules = [
+        Rules.LABEL.value,
+        Rules.NAME.value,
+        Rules.ACTIVE.value,
+        Rules.OS_INIT_ID_EXT.value
+    ]
+
+    os_template.label = request.json.get('label')
+    os_template.name = request.json.get('name')
+    os_template.active = request.json.get('active')
+    os_template.os_init_id = request.json.get('os_init_id', 0)
+
+    try:
+        ji.Check.previewing(args_rules, os_template.__dict__)
+
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+
+        if os_template.exist_by('name'):
+            ret['state'] = ji.Common.exchange_state(40901)
+            ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], ': ', os_template.name])
+            return ret
+
+        os_template.create()
+        os_template.get_by('name')
+        ret['data'] = os_template.__dict__
+        return ret
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+
+@Utils.dumps2response
+def r_update(_id):
+
+    os_template = OSTemplate()
+
+    args_rules = [
+        Rules.ID.value
+    ]
+
+    if 'label' in request.json:
+        args_rules.append(
+            Rules.LABEL.value,
+        )
+
+    if 'name' in request.json:
+        args_rules.append(
+            Rules.NAME.value,
+        )
+
+    if 'active' in request.json:
+        args_rules.append(
+            Rules.ACTIVE.value,
+        )
+
+    if 'os_init_id' in request.json:
+        args_rules.append(
+            Rules.OS_INIT_ID_EXT.value,
+        )
+
+    if args_rules.__len__() < 2:
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        return ret
+
+    request.json['id'] = _id
+
+    try:
+        ji.Check.previewing(args_rules, request.json)
+        os_template.id = request.json.get('id')
+
+        os_template.get()
+        os_template.label = request.json.get('label', os_template.label)
+        os_template.name = request.json.get('name', os_template.name)
+        os_template.active = request.json.get('active', os_template.active)
+        os_template.os_init_id = request.json.get('os_init_id', os_template.os_init_id)
+
+        os_template.update()
+        os_template.get()
+
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        ret['data'] = os_template.__dict__
+        return ret
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+
+@Utils.dumps2response
+def r_delete(_id):
+    os_template = OSTemplate()
+
+    args_rules = [
+        Rules.ID.value
+    ]
+    os_template.id = _id
+
+    try:
+        ji.Check.previewing(args_rules, os_template.__dict__)
+
+        if os_template.exist():
+            os_template.delete()
+        else:
+            ret = dict()
+            ret['state'] = ji.Common.exchange_state(40401)
+            return ret
+
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+
+@Utils.dumps2response
+def r_get_by_filter():
+    page = str(request.args.get('page', 1))
+    page_size = str(request.args.get('page_size', 50))
+
+    args_rules = [
+        Rules.PAGE.value,
+        Rules.PAGE_SIZE.value
+    ]
+
+    try:
+        ji.Check.previewing(args_rules, {'page': page, 'page_size': page_size})
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+    page = int(page)
+    page_size = int(page_size)
+
+    # 把page和page_size换算成offset和limit
+    offset = (page - 1) * page_size
+    # offset, limit将覆盖page及page_size的影响
+    offset = str(request.args.get('offset', offset))
+    limit = str(request.args.get('limit', page_size))
+
+    order_by = request.args.get('order_by', 'id')
+    order = request.args.get('order', 'asc')
+    filter_str = request.args.get('filter', '')
+
+    args_rules = [
+        Rules.OFFSET.value,
+        Rules.LIMIT.value,
+        Rules.ORDER_BY.value,
+        Rules.ORDER.value
+    ]
+
+    try:
+        ji.Check.previewing(args_rules, {'offset': offset, 'limit': limit, 'order_by': order_by, 'order': order})
+        offset = int(offset)
+        limit = int(limit)
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        ret['data'] = list()
+        ret['paging'] = {'total': 0, 'offset': offset, 'limit': limit, 'page': page, 'page_size': page_size,
+                         'next': '', 'prev': '', 'first': '', 'last': ''}
+
+        ret['data'], ret['paging']['total'] = OSTemplate.get_by_filter(offset=offset, limit=limit, order_by=order_by,
+                                                                       order=order, filter_str=filter_str)
+
+        host_url = request.host_url.rstrip('/')
+        other_str = '&filter=' + filter_str + '&order=' + order + '&order_by=' + order_by
+        last_pagination = (ret['paging']['total'] + page_size - 1) / page_size
+
+        if page <= 1:
+            ret['paging']['prev'] = host_url + blueprint.url_prefix + '?page=1&page_size=' + page_size.__str__() + \
+                                    other_str
+        else:
+            ret['paging']['prev'] = host_url + blueprint.url_prefix + '?page=' + str(page-1) + '&page_size=' + \
+                                    page_size.__str__() + other_str
+
+        if page >= last_pagination:
+            ret['paging']['next'] = host_url + blueprint.url_prefix + '?page=' + last_pagination.__str__() + \
+                                    '&page_size=' + page_size.__str__() + other_str
+        else:
+            ret['paging']['next'] = host_url + blueprint.url_prefix + '?page=' + str(page+1) + '&page_size=' + \
+                                    page_size.__str__() + other_str
+
+        ret['paging']['first'] = host_url + blueprint.url_prefix + '?page=1&page_size=' + \
+            page_size.__str__() + other_str
+        ret['paging']['last'] = \
+            host_url + blueprint.url_prefix + '?page=' + last_pagination.__str__() + '&page_size=' + \
+            page_size.__str__() + other_str
+
+        return ret
+    except ji.PreviewingError, e:
+        return json.loads(e.message)