diff --git a/.gitignore b/.gitignore index 33f95c7902c..9511e9ede2f 100644 --- a/.gitignore +++ b/.gitignore @@ -67,8 +67,10 @@ awsapi/modules/* .settings/ db.properties.override awsapi/overlays/ +tools/marvin/marvin/cloudstackAPI/* *.egg-info/ docs/tmp docs/publish docs/runbook/tmp docs/runbook/publish +Gemfile.lock diff --git a/LICENSE b/LICENSE index 3f01e10f654..afb662a77e2 100644 --- a/LICENSE +++ b/LICENSE @@ -309,10 +309,1906 @@ Within the deps directory XenServerJava http://community.citrix.com/cdn/xs/sdks/ +Within the patches/systemvm/debian/config/etc directory + placed in the public domain + by Simon Kelley + dnsmasq.conf + vpcdnsmasq.conf + + +Within the patches/systemvm/debian/config/etc/apache2 directory + licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) + Copyright (c) 2012 The Apache Software Foundation + from The Apache Software Foundation http://www.apache.org/ + httpd.conf + ports.conf + sites-available/default + sites-available/default-ssl + vhostexample.conf + + +Within the patches/systemvm/debian/config/etc/ssh/ directory + licensed under the BSD (2-clause) http://www.opensource.org/licenses/BSD-2-Clause (as follows) + + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. Redistributions in binary form must + reproduce the above copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided with the + distribution. + + Neither the name of the author nor the names of contributors may be used to + endorse or promote products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + from OpenSSH Project http://www.openssh.org/ + sshd_config + + +Within the patches/systemvm/debian/config/root/redundant_router directory + placed in the public domain + by The netfilter.org project http://www.netfilter.org/ + conntrackd.conf.templ + + +Within the scripts/storage/secondary directory + licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) + Copyright (c) 2010-2011 OpenStack, LLC. + from OpenStack, LLC http://www.openstack.org + swift + + +Within the scripts/vm/hypervisor/xenserver directory + licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) + Copyright (c) 2010-2011 OpenStack, LLC. + from OpenStack, LLC http://www.openstack.org + swift + + +Within the ui/lib directory + placed in the public domain + by Eric Meyer http://meyerweb.com/eric/ + reset.css + + licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) + Copyright (c) 2006 Google Inc. + from Google Inc. http://google.com + excanvas.js http://code.google.com/p/explorercanvas/ + + licensed under the BSD (2-clause) http://www.opensource.org/licenses/BSD-2-Clause (as follows) + + Copyright (c) 2008 George McGinley Smith + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. Redistributions in binary form must + reproduce the above copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided with the + distribution. + + Neither the name of the author nor the names of contributors may be used to + endorse or promote products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + from George McGinley Smith + jquery.easing.js + + licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) + + Copyright (c) 2011, John Resig + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + from John Resig + jquery.js + + licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) + + Copyright (c) 2006 - 2011 Jörn Zaefferer + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + from Jorn Zaefferer + jquery.validate.js + + licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) + + Copyright (c) 2010, Sebastian Tschan + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + from Sebastian Tschan https://blueimp.net + jquery.md5.js + + licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) + + Copyright (c) 2006 Klaus Hartl (stilbuero.de) + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + from Klaus Hartl http://stilbuero.de + jquery.cookies.js + + +Within the ui/lib/flot directory + licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) + + Released under the MIT license by IOLA, December 2007. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + from IOLA http://www.iola.dk/ + jquery.flot.crosshair.js + jquery.flot.fillbetween.js + jquery.flot.image.js + jquery.flot.js + jquery.flot.navigate.js + jquery.flot.resize.js + jquery.flot.selection.js + jquery.flot.stack.js + jquery.flot.symbol.js + jquery.flot.threshold.js + + licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) + + Created by Brian Medendorp, June 2009 + Updated November 2009 with contributions from: btburnett3, Anthony Aragues and Xavi Ivars + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + from Brian Medendorp + jquery.pie.js + + licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) + + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + from Ole Laursen + jquery.colorhelpers.js + + +Within the ui/lib/jquery-ui directory + licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) + + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + from jQuery UI Developers http://jqueryui.com/about + css/jquery-ui.css + index.html + js/jquery-ui.js + + +Within the ui/lib/qunit directory + licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) + + Copyright (c) 2012 John Resig, Jörn Zaefferer + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + from Jorn Zaefferer + qunit.css http://docs.jquery.com/QUnit + qunit.js http://docs.jquery.com/QUnit + + +Within the utils/src/com/cloud/utils/db directory + licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) + Copyright (c) 2004 Clinton Begin + from Clinton Begin http://code.google.com/p/mybatis/ + ScriptRunner.java http://code.google.com/p/mybatis/ + + + +******************************************************************************** + +Binary or packaged versions of this software (including versions built from source) +contain third party resources (as listed below). + +Within the target/jar directory + placed in the public domain + by Distributed Computing Laboratory at Emory University http://creativecommons.org/licenses/publicdomain/ + cloud-backport-util-concurrent-3.0.jar + + licensed under the Apache License, Version 1.1 http://www.apache.org/licenses/LICENSE-1.1 (as follows) + + Copyright (c) 2012 The Apache Software Foundation + + /* ==================================================================== + * The Apache Software License, Version 1.1 + * + * Copyright (c) 2000 The Apache Software Foundation. All rights + * reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Apache Software Foundation (http://www.apache.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The names "Apache" and "Apache Software Foundation" must + * not be used to endorse or promote products derived from this + * software without prior written permission. For written + * permission, please contact apache@apache.org. + * + * 5. Products derived from this software may not be called "Apache", + * nor may "Apache" appear in their name, without prior written + * permission of the Apache Software Foundation. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + */ + + from The Apache Software Foundation http://www.apache.org/ + cloud-commons-discovery.jar http://commons.apache.org/discovery/ + + licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) + Copyright (c) 2012 The Apache Software Foundation + from The Apache Software Foundation http://www.apache.org/ + cloud-axis.jar http://axis.apache.org/axis/ + cloud-cglib.jar http://cglib.sourceforge.net/ + cloud-commons-codec-1.5.jar http://commons.apache.org/codec/ + cloud-commons-collections-3.2.1.jar http://commons.apache.org/collections/ + cloud-commons-configuration-1.8.jar http://commons.apache.org/configuration/ + cloud-commons-dbcp-1.4.jar http://commons.apache.org/dbcp/ + cloud-commons-httpclient-3.1.jar http://hc.apache.org/httpclient-3.x/ + cloud-commons-lang-2.6.jar http://commons.apache.org/lang/ + cloud-commons-logging-1.1.1.jar http://commons.apache.org/logging/ + cloud-commons-pool-1.5.6.jar http://commons.apache.org/pool/ + cloud-log4j-extras.jar http://logging.apache.org/log4j/companions/extras/ + cloud-log4j.jar http://logging.apache.org/log4j/ + cloud-ws-commons-util-1.0.2.jar http://ws.apache.org/commons/util/ + cloud-xmlrpc-client-3.1.3.jar http://ws.apache.org/xmlrpc/client.html + cloud-xmlrpc-common-3.1.3.jar http://ws.apache.org/xmlrpc/xmlrpc-common/ + + licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) + Copyright (c) 2007-2010, The JASYPT team (http://www.jasypt.org) + from The JASYPT team http://www.jasypt.org + cloud-jasypt-1.9.jar http://www.jasypt.org + + licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) + Copyright (c) 2003-2007 Luck Consulting Pty Ltd + from Luck Consulting Pty Ltd http://gregluck.com/blog/about/ + cloud-ehcache.jar http://ehcache.org/ + + licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) + Copyright (c) 2009 Google Inc. + from Google Inc. http://google.com + cloud-google-gson-1.7.1.jar http://code.google.com/p/google-gson/ + + licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) + + from Jetty Committers http://jetty.codehaus.org/jetty/ + jetty-6.1.26.jar http://repo1.maven.org/maven2/org/mortbay/jetty/jetty/6.1.26/jetty-6.1.26-sources.jar + jetty-util-6.1.26.jar http://repo1.maven.org/maven2/org/mortbay/jetty/jetty-util/6.1.26/jetty-util-6.1.26-sources.jar + + licensed under the BSD (3-clause) http://www.opensource.org/licenses/BSD-3-Clause (as follows) + + Copyright (c) 2009, Caringo, Inc. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. + + from Caringo, Inc. http://www.caringo.com/ + CAStorSDK.jar http://www.castor.org/download.html + + licensed under the BSD (3-clause) http://www.opensource.org/licenses/BSD-3-Clause (as follows) + + Copyright (c) 2002-2011 Atsuhiko Yamanaka, JCraft,Inc. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. + + from JCraft http://www.jcraft.com/ + cloud-jsch-0.1.42.jar http://www.jcraft.com/jsch/ + + licensed under the BSD (3-clause) http://www.opensource.org/licenses/BSD-3-Clause (as follows) + + Copyright (c) 2007-2008 Trilead AG (http://www.trilead.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. + + from Trilead AG http://www.trilead.com + cloud-trilead-ssh2-build213.jar http://sourceforge.net/projects/orion-ssh2/ + + licensed under the Bouncy Castle adaptation of MIT X11 License http://www.bouncycastle.org/licence.html (as follows) + + + Please note: our license is an adaptation of the MIT X11 License and should be + read as such. + + LICENSE Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle + (http://www.bouncycastle.org) + + Permission is hereby granted, free of charge, to any person obtaining a copy of + this software and associated documentation files (the "Software"), to deal in + the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + from The Legion Of The Bouncy Castle http://www.bouncycastle.org + cloud-bcprov-jdk16-1.45.jar http://repo1.maven.org/maven2/org/bouncycastle/bcprov-jdk16/1.45/bcprov-jdk16-1.45-sources.jar + + licensed under the COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 http://www.opensource.org/licenses/CDDL-1.0 (as follows) + + Copyright (c) 2006 Sun Microsystems, Inc. All rights reserved. + + COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 + + 1. Definitions. + + 1.1. "Contributor" means each individual or entity that + creates or contributes to the creation of Modifications. + + 1.2. "Contributor Version" means the combination of the + Original Software, prior Modifications used by a + Contributor (if any), and the Modifications made by that + particular Contributor. + + 1.3. "Covered Software" means (a) the Original Software, or + (b) Modifications, or (c) the combination of files + containing Original Software with files containing + Modifications, in each case including portions thereof. + + 1.4. "Executable" means the Covered Software in any form + other than Source Code. + + 1.5. "Initial Developer" means the individual or entity + that first makes Original Software available under this + License. + + 1.6. "Larger Work" means a work which combines Covered + Software or portions thereof with code not governed by the + terms of this License. + + 1.7. "License" means this document. + + 1.8. "Licensable" means having the right to grant, to the + maximum extent possible, whether at the time of the initial + grant or subsequently acquired, any and all of the rights + conveyed herein. + + 1.9. "Modifications" means the Source Code and Executable + form of any of the following: + + A. Any file that results from an addition to, + deletion from or modification of the contents of a + file containing Original Software or previous + Modifications; + + B. Any new file that contains any part of the + Original Software or previous Modification; or + + C. Any new file that is contributed or otherwise made + available under the terms of this License. + + 1.10. "Original Software" means the Source Code and + Executable form of computer software code that is + originally released under this License. + + 1.11. "Patent Claims" means any patent claim(s), now owned + or hereafter acquired, including without limitation, + method, process, and apparatus claims, in any patent + Licensable by grantor. + + 1.12. "Source Code" means (a) the common form of computer + software code in which modifications are made and (b) + associated documentation included in or with such code. + + 1.13. "You" (or "Your") means an individual or a legal + entity exercising rights under, and complying with all of + the terms of, this License. For legal entities, "You" + includes any entity which controls, is controlled by, or is + under common control with You. For purposes of this + definition, "control" means (a) the power, direct or + indirect, to cause the direction or management of such + entity, whether by contract or otherwise, or (b) ownership + of more than fifty percent (50%) of the outstanding shares + or beneficial ownership of such entity. + + 2. License Grants. + + 2.1. The Initial Developer Grant. + + Conditioned upon Your compliance with Section 3.1 below and + subject to third party intellectual property claims, the + Initial Developer hereby grants You a world-wide, + royalty-free, non-exclusive license: + + (a) under intellectual property rights (other than + patent or trademark) Licensable by Initial Developer, + to use, reproduce, modify, display, perform, + sublicense and distribute the Original Software (or + portions thereof), with or without Modifications, + and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, + using or selling of Original Software, to make, have + made, use, practice, sell, and offer for sale, and/or + otherwise dispose of the Original Software (or + portions thereof). + + (c) The licenses granted in Sections 2.1(a) and (b) + are effective on the date Initial Developer first + distributes or otherwise makes the Original Software + available to a third party under the terms of this + License. + + (d) Notwithstanding Section 2.1(b) above, no patent + license is granted: (1) for code that You delete from + the Original Software, or (2) for infringements + caused by: (i) the modification of the Original + Software, or (ii) the combination of the Original + Software with other software or devices. + + 2.2. Contributor Grant. + + Conditioned upon Your compliance with Section 3.1 below and + subject to third party intellectual property claims, each + Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + (a) under intellectual property rights (other than + patent or trademark) Licensable by Contributor to + use, reproduce, modify, display, perform, sublicense + and distribute the Modifications created by such + Contributor (or portions thereof), either on an + unmodified basis, with other Modifications, as + Covered Software and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, + using, or selling of Modifications made by that + Contributor either alone and/or in combination with + its Contributor Version (or portions of such + combination), to make, use, sell, offer for sale, + have made, and/or otherwise dispose of: (1) + Modifications made by that Contributor (or portions + thereof); and (2) the combination of Modifications + made by that Contributor with its Contributor Version + (or portions of such combination). + + (c) The licenses granted in Sections 2.2(a) and + 2.2(b) are effective on the date Contributor first + distributes or otherwise makes the Modifications + available to a third party. + + (d) Notwithstanding Section 2.2(b) above, no patent + license is granted: (1) for any code that Contributor + has deleted from the Contributor Version; (2) for + infringements caused by: (i) third party + modifications of Contributor Version, or (ii) the + combination of Modifications made by that Contributor + with other software (except as part of the + Contributor Version) or other devices; or (3) under + Patent Claims infringed by Covered Software in the + absence of Modifications made by that Contributor. + + 3. Distribution Obligations. + + 3.1. Availability of Source Code. + + Any Covered Software that You distribute or otherwise make + available in Executable form must also be made available in + Source Code form and that Source Code form must be + distributed only under the terms of this License. You must + include a copy of this License with every copy of the + Source Code form of the Covered Software You distribute or + otherwise make available. You must inform recipients of any + such Covered Software in Executable form as to how they can + obtain such Covered Software in Source Code form in a + reasonable manner on or through a medium customarily used + for software exchange. + + 3.2. Modifications. + + The Modifications that You create or to which You + contribute are governed by the terms of this License. You + represent that You believe Your Modifications are Your + original creation(s) and/or You have sufficient rights to + grant the rights conveyed by this License. + + 3.3. Required Notices. + + You must include a notice in each of Your Modifications + that identifies You as the Contributor of the Modification. + You may not remove or alter any copyright, patent or + trademark notices contained within the Covered Software, or + any notices of licensing or any descriptive text giving + attribution to any Contributor or the Initial Developer. + + 3.4. Application of Additional Terms. + + You may not offer or impose any terms on any Covered + Software in Source Code form that alters or restricts the + applicable version of this License or the recipients' + rights hereunder. You may choose to offer, and to charge a + fee for, warranty, support, indemnity or liability + obligations to one or more recipients of Covered Software. + However, you may do so only on Your own behalf, and not on + behalf of the Initial Developer or any Contributor. You + must make it absolutely clear that any such warranty, + support, indemnity or liability obligation is offered by + You alone, and You hereby agree to indemnify the Initial + Developer and every Contributor for any liability incurred + by the Initial Developer or such Contributor as a result of + warranty, support, indemnity or liability terms You offer. + + 3.5. Distribution of Executable Versions. + + You may distribute the Executable form of the Covered + Software under the terms of this License or under the terms + of a license of Your choice, which may contain terms + different from this License, provided that You are in + compliance with the terms of this License and that the + license for the Executable form does not attempt to limit + or alter the recipient's rights in the Source Code form + from the rights set forth in this License. If You + distribute the Covered Software in Executable form under a + different license, You must make it absolutely clear that + any terms which differ from this License are offered by You + alone, not by the Initial Developer or Contributor. You + hereby agree to indemnify the Initial Developer and every + Contributor for any liability incurred by the Initial + Developer or such Contributor as a result of any such terms + You offer. + + 3.6. Larger Works. + + You may create a Larger Work by combining Covered Software + with other code not governed by the terms of this License + and distribute the Larger Work as a single product. In such + a case, You must make sure the requirements of this License + are fulfilled for the Covered Software. + + 4. Versions of the License. + + 4.1. New Versions. + + Sun Microsystems, Inc. is the initial license steward and + may publish revised and/or new versions of this License + from time to time. Each version will be given a + distinguishing version number. Except as provided in + Section 4.3, no one other than the license steward has the + right to modify this License. + + 4.2. Effect of New Versions. + + You may always continue to use, distribute or otherwise + make the Covered Software available under the terms of the + version of the License under which You originally received + the Covered Software. If the Initial Developer includes a + notice in the Original Software prohibiting it from being + distributed or otherwise made available under any + subsequent version of the License, You must distribute and + make the Covered Software available under the terms of the + version of the License under which You originally received + the Covered Software. Otherwise, You may also choose to + use, distribute or otherwise make the Covered Software + available under the terms of any subsequent version of the + License published by the license steward. + + 4.3. Modified Versions. + + When You are an Initial Developer and You want to create a + new license for Your Original Software, You may create and + use a modified version of this License if You: (a) rename + the license and remove any references to the name of the + license steward (except to note that the license differs + from this License); and (b) otherwise make it clear that + the license contains terms which differ from this License. + + 5. DISCLAIMER OF WARRANTY. + + COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" + BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, + INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED + SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR + PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND + PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY + COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE + INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF + ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF + WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF + ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS + DISCLAIMER. + + 6. TERMINATION. + + 6.1. This License and the rights granted hereunder will + terminate automatically if You fail to comply with terms + herein and fail to cure such breach within 30 days of + becoming aware of the breach. Provisions which, by their + nature, must remain in effect beyond the termination of + this License shall survive. + + 6.2. If You assert a patent infringement claim (excluding + declaratory judgment actions) against Initial Developer or + a Contributor (the Initial Developer or Contributor against + whom You assert such claim is referred to as "Participant") + alleging that the Participant Software (meaning the + Contributor Version where the Participant is a Contributor + or the Original Software where the Participant is the + Initial Developer) directly or indirectly infringes any + patent, then any and all rights granted directly or + indirectly to You by such Participant, the Initial + Developer (if the Initial Developer is not the Participant) + and all Contributors under Sections 2.1 and/or 2.2 of this + License shall, upon 60 days notice from Participant + terminate prospectively and automatically at the expiration + of such 60 day notice period, unless if within such 60 day + period You withdraw Your claim with respect to the + Participant Software against such Participant either + unilaterally or pursuant to a written agreement with + Participant. + + 6.3. In the event of termination under Sections 6.1 or 6.2 + above, all end user licenses that have been validly granted + by You or any distributor hereunder prior to termination + (excluding licenses granted to You by any distributor) + shall survive termination. + + 7. LIMITATION OF LIABILITY. + + UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT + (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE + INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF + COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE + LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT + LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK + STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER + COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN + INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF + LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL + INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT + APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO + NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR + CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT + APPLY TO YOU. + + 8. U.S. GOVERNMENT END USERS. + + The Covered Software is a "commercial item," as that term is + defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial + computer software" (as that term is defined at 48 C.F.R. ¤ + 252.227-7014(a)(1)) and "commercial computer software + documentation" as such terms are used in 48 C.F.R. 12.212 (Sept. + 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 + through 227.7202-4 (June 1995), all U.S. Government End Users + acquire Covered Software with only those rights set forth herein. + This U.S. Government Rights clause is in lieu of, and supersedes, + any other FAR, DFAR, or other clause or provision that addresses + Government rights in computer software under this License. + + 9. MISCELLANEOUS. + + This License represents the complete agreement concerning subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the + extent necessary to make it enforceable. This License shall be + governed by the law of the jurisdiction specified in a notice + contained within the Original Software (except to the extent + applicable law, if any, provides otherwise), excluding such + jurisdiction's conflict-of-law provisions. Any litigation + relating to this License shall be subject to the jurisdiction of + the courts located in the jurisdiction and venue specified in a + notice contained within the Original Software, with the losing + party responsible for costs, including, without limitation, court + costs and reasonable attorneys' fees and expenses. The + application of the United Nations Convention on Contracts for the + International Sale of Goods is expressly excluded. Any law or + regulation which provides that the language of a contract shall + be construed against the drafter shall not apply to this License. + You agree that You alone are responsible for compliance with the + United States export administration regulations (and the export + control laws and regulation of any other countries) when You use, + distribute or otherwise make available any Covered Software. + + 10. RESPONSIBILITY FOR CLAIMS. + + As between Initial Developer and the Contributors, each party is + responsible for claims and damages arising, directly or + indirectly, out of its utilization of rights under this License + and You agree to work with Initial Developer and Contributors to + distribute such responsibility on an equitable basis. Nothing + herein is intended or shall be deemed to constitute any admission + of liability. + + from Project GlassFish http://glassfish.java.net/ + cloud-ejb-api-3.0.jar http://repo1.maven.org/maven2/javax/ejb/ejb-api/3.0/ejb-api-3.0-sources.jar + cloud-jstl-1.2.jar http://jstl.java.net/ + + licensed under the COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 http://www.opensource.org/licenses/CDDL-1.0 (as follows) + + Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + + COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 + + 1. Definitions. + + 1.1. "Contributor" means each individual or entity that + creates or contributes to the creation of Modifications. + + 1.2. "Contributor Version" means the combination of the + Original Software, prior Modifications used by a + Contributor (if any), and the Modifications made by that + particular Contributor. + + 1.3. "Covered Software" means (a) the Original Software, or + (b) Modifications, or (c) the combination of files + containing Original Software with files containing + Modifications, in each case including portions thereof. + + 1.4. "Executable" means the Covered Software in any form + other than Source Code. + + 1.5. "Initial Developer" means the individual or entity + that first makes Original Software available under this + License. + + 1.6. "Larger Work" means a work which combines Covered + Software or portions thereof with code not governed by the + terms of this License. + + 1.7. "License" means this document. + + 1.8. "Licensable" means having the right to grant, to the + maximum extent possible, whether at the time of the initial + grant or subsequently acquired, any and all of the rights + conveyed herein. + + 1.9. "Modifications" means the Source Code and Executable + form of any of the following: + + A. Any file that results from an addition to, + deletion from or modification of the contents of a + file containing Original Software or previous + Modifications; + + B. Any new file that contains any part of the + Original Software or previous Modification; or + + C. Any new file that is contributed or otherwise made + available under the terms of this License. + + 1.10. "Original Software" means the Source Code and + Executable form of computer software code that is + originally released under this License. + + 1.11. "Patent Claims" means any patent claim(s), now owned + or hereafter acquired, including without limitation, + method, process, and apparatus claims, in any patent + Licensable by grantor. + + 1.12. "Source Code" means (a) the common form of computer + software code in which modifications are made and (b) + associated documentation included in or with such code. + + 1.13. "You" (or "Your") means an individual or a legal + entity exercising rights under, and complying with all of + the terms of, this License. For legal entities, "You" + includes any entity which controls, is controlled by, or is + under common control with You. For purposes of this + definition, "control" means (a) the power, direct or + indirect, to cause the direction or management of such + entity, whether by contract or otherwise, or (b) ownership + of more than fifty percent (50%) of the outstanding shares + or beneficial ownership of such entity. + + 2. License Grants. + + 2.1. The Initial Developer Grant. + + Conditioned upon Your compliance with Section 3.1 below and + subject to third party intellectual property claims, the + Initial Developer hereby grants You a world-wide, + royalty-free, non-exclusive license: + + (a) under intellectual property rights (other than + patent or trademark) Licensable by Initial Developer, + to use, reproduce, modify, display, perform, + sublicense and distribute the Original Software (or + portions thereof), with or without Modifications, + and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, + using or selling of Original Software, to make, have + made, use, practice, sell, and offer for sale, and/or + otherwise dispose of the Original Software (or + portions thereof). + + (c) The licenses granted in Sections 2.1(a) and (b) + are effective on the date Initial Developer first + distributes or otherwise makes the Original Software + available to a third party under the terms of this + License. + + (d) Notwithstanding Section 2.1(b) above, no patent + license is granted: (1) for code that You delete from + the Original Software, or (2) for infringements + caused by: (i) the modification of the Original + Software, or (ii) the combination of the Original + Software with other software or devices. + + 2.2. Contributor Grant. + + Conditioned upon Your compliance with Section 3.1 below and + subject to third party intellectual property claims, each + Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + (a) under intellectual property rights (other than + patent or trademark) Licensable by Contributor to + use, reproduce, modify, display, perform, sublicense + and distribute the Modifications created by such + Contributor (or portions thereof), either on an + unmodified basis, with other Modifications, as + Covered Software and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, + using, or selling of Modifications made by that + Contributor either alone and/or in combination with + its Contributor Version (or portions of such + combination), to make, use, sell, offer for sale, + have made, and/or otherwise dispose of: (1) + Modifications made by that Contributor (or portions + thereof); and (2) the combination of Modifications + made by that Contributor with its Contributor Version + (or portions of such combination). + + (c) The licenses granted in Sections 2.2(a) and + 2.2(b) are effective on the date Contributor first + distributes or otherwise makes the Modifications + available to a third party. + + (d) Notwithstanding Section 2.2(b) above, no patent + license is granted: (1) for any code that Contributor + has deleted from the Contributor Version; (2) for + infringements caused by: (i) third party + modifications of Contributor Version, or (ii) the + combination of Modifications made by that Contributor + with other software (except as part of the + Contributor Version) or other devices; or (3) under + Patent Claims infringed by Covered Software in the + absence of Modifications made by that Contributor. + + 3. Distribution Obligations. + + 3.1. Availability of Source Code. + + Any Covered Software that You distribute or otherwise make + available in Executable form must also be made available in + Source Code form and that Source Code form must be + distributed only under the terms of this License. You must + include a copy of this License with every copy of the + Source Code form of the Covered Software You distribute or + otherwise make available. You must inform recipients of any + such Covered Software in Executable form as to how they can + obtain such Covered Software in Source Code form in a + reasonable manner on or through a medium customarily used + for software exchange. + + 3.2. Modifications. + + The Modifications that You create or to which You + contribute are governed by the terms of this License. You + represent that You believe Your Modifications are Your + original creation(s) and/or You have sufficient rights to + grant the rights conveyed by this License. + + 3.3. Required Notices. + + You must include a notice in each of Your Modifications + that identifies You as the Contributor of the Modification. + You may not remove or alter any copyright, patent or + trademark notices contained within the Covered Software, or + any notices of licensing or any descriptive text giving + attribution to any Contributor or the Initial Developer. + + 3.4. Application of Additional Terms. + + You may not offer or impose any terms on any Covered + Software in Source Code form that alters or restricts the + applicable version of this License or the recipients' + rights hereunder. You may choose to offer, and to charge a + fee for, warranty, support, indemnity or liability + obligations to one or more recipients of Covered Software. + However, you may do so only on Your own behalf, and not on + behalf of the Initial Developer or any Contributor. You + must make it absolutely clear that any such warranty, + support, indemnity or liability obligation is offered by + You alone, and You hereby agree to indemnify the Initial + Developer and every Contributor for any liability incurred + by the Initial Developer or such Contributor as a result of + warranty, support, indemnity or liability terms You offer. + + 3.5. Distribution of Executable Versions. + + You may distribute the Executable form of the Covered + Software under the terms of this License or under the terms + of a license of Your choice, which may contain terms + different from this License, provided that You are in + compliance with the terms of this License and that the + license for the Executable form does not attempt to limit + or alter the recipient's rights in the Source Code form + from the rights set forth in this License. If You + distribute the Covered Software in Executable form under a + different license, You must make it absolutely clear that + any terms which differ from this License are offered by You + alone, not by the Initial Developer or Contributor. You + hereby agree to indemnify the Initial Developer and every + Contributor for any liability incurred by the Initial + Developer or such Contributor as a result of any such terms + You offer. + + 3.6. Larger Works. + + You may create a Larger Work by combining Covered Software + with other code not governed by the terms of this License + and distribute the Larger Work as a single product. In such + a case, You must make sure the requirements of this License + are fulfilled for the Covered Software. + + 4. Versions of the License. + + 4.1. New Versions. + + Sun Microsystems, Inc. is the initial license steward and + may publish revised and/or new versions of this License + from time to time. Each version will be given a + distinguishing version number. Except as provided in + Section 4.3, no one other than the license steward has the + right to modify this License. + + 4.2. Effect of New Versions. + + You may always continue to use, distribute or otherwise + make the Covered Software available under the terms of the + version of the License under which You originally received + the Covered Software. If the Initial Developer includes a + notice in the Original Software prohibiting it from being + distributed or otherwise made available under any + subsequent version of the License, You must distribute and + make the Covered Software available under the terms of the + version of the License under which You originally received + the Covered Software. Otherwise, You may also choose to + use, distribute or otherwise make the Covered Software + available under the terms of any subsequent version of the + License published by the license steward. + + 4.3. Modified Versions. + + When You are an Initial Developer and You want to create a + new license for Your Original Software, You may create and + use a modified version of this License if You: (a) rename + the license and remove any references to the name of the + license steward (except to note that the license differs + from this License); and (b) otherwise make it clear that + the license contains terms which differ from this License. + + 5. DISCLAIMER OF WARRANTY. + + COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" + BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, + INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED + SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR + PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND + PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY + COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE + INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF + ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF + WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF + ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS + DISCLAIMER. + + 6. TERMINATION. + + 6.1. This License and the rights granted hereunder will + terminate automatically if You fail to comply with terms + herein and fail to cure such breach within 30 days of + becoming aware of the breach. Provisions which, by their + nature, must remain in effect beyond the termination of + this License shall survive. + + 6.2. If You assert a patent infringement claim (excluding + declaratory judgment actions) against Initial Developer or + a Contributor (the Initial Developer or Contributor against + whom You assert such claim is referred to as "Participant") + alleging that the Participant Software (meaning the + Contributor Version where the Participant is a Contributor + or the Original Software where the Participant is the + Initial Developer) directly or indirectly infringes any + patent, then any and all rights granted directly or + indirectly to You by such Participant, the Initial + Developer (if the Initial Developer is not the Participant) + and all Contributors under Sections 2.1 and/or 2.2 of this + License shall, upon 60 days notice from Participant + terminate prospectively and automatically at the expiration + of such 60 day notice period, unless if within such 60 day + period You withdraw Your claim with respect to the + Participant Software against such Participant either + unilaterally or pursuant to a written agreement with + Participant. + + 6.3. In the event of termination under Sections 6.1 or 6.2 + above, all end user licenses that have been validly granted + by You or any distributor hereunder prior to termination + (excluding licenses granted to You by any distributor) + shall survive termination. + + 7. LIMITATION OF LIABILITY. + + UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT + (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE + INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF + COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE + LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR + CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT + LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK + STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER + COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN + INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF + LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL + INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT + APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO + NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR + CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT + APPLY TO YOU. + + 8. U.S. GOVERNMENT END USERS. + + The Covered Software is a "commercial item," as that term is + defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial + computer software" (as that term is defined at 48 C.F.R. ¤ + 252.227-7014(a)(1)) and "commercial computer software + documentation" as such terms are used in 48 C.F.R. 12.212 (Sept. + 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 + through 227.7202-4 (June 1995), all U.S. Government End Users + acquire Covered Software with only those rights set forth herein. + This U.S. Government Rights clause is in lieu of, and supersedes, + any other FAR, DFAR, or other clause or provision that addresses + Government rights in computer software under this License. + + 9. MISCELLANEOUS. + + This License represents the complete agreement concerning subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the + extent necessary to make it enforceable. This License shall be + governed by the law of the jurisdiction specified in a notice + contained within the Original Software (except to the extent + applicable law, if any, provides otherwise), excluding such + jurisdiction's conflict-of-law provisions. Any litigation + relating to this License shall be subject to the jurisdiction of + the courts located in the jurisdiction and venue specified in a + notice contained within the Original Software, with the losing + party responsible for costs, including, without limitation, court + costs and reasonable attorneys' fees and expenses. The + application of the United Nations Convention on Contracts for the + International Sale of Goods is expressly excluded. Any law or + regulation which provides that the language of a contract shall + be construed against the drafter shall not apply to this License. + You agree that You alone are responsible for compliance with the + United States export administration regulations (and the export + control laws and regulation of any other countries) when You use, + distribute or otherwise make available any Covered Software. + + 10. RESPONSIBILITY FOR CLAIMS. + + As between Initial Developer and the Contributors, each party is + responsible for claims and damages arising, directly or + indirectly, out of its utilization of rights under this License + and You agree to work with Initial Developer and Contributors to + distribute such responsibility on an equitable basis. Nothing + herein is intended or shall be deemed to constitute any admission + of liability. + + from Oracle and/or its affiliates http://oracle.com + cloud-email.jar http://kenai.com/projects/javamail + + licensed under the Common Public License - v 1.0 http://opensource.org/licenses/cpl1.0 (as follows) + + Copyright (c) IBM Corp 2006 + + Common Public License Version 1.0 (CPL) + + THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS COMMON PUBLIC + LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM + CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + + 1. DEFINITIONS + + "Contribution means: + + a) in the case of the initial Contributor, the initial code and documentation + distributed under this Agreement, and + + b) in the case of each subsequent Contributor: + + i) changes to the Program, and + + ii) additions to the Program; + + where such changes and/or additions to the Program originate from and are + distributed by that particular Contributor. A Contribution 'originates' from a + Contributor if it was added to the Program by such Contributor itself or anyone + acting on such Contributor's behalf. Contributions do not include additions to + the Program which: (i) are separate modules of software distributed in + conjunction with the Program under their own license agreement, and (ii) are not + derivative works of the Program. + + "Contributor means any person or entity that distributes the Program. + + "Licensed Patents mean patent claims licensable by a Contributor which are + "necessarily infringed by the use or sale of its Contribution alone or when + "combined with the Program. + + "Program means the Contributions distributed in accordance with this Agreement. + + "Recipient means anyone who receives the Program under this Agreement, including + "all Contributors. + + 2. GRANT OF RIGHTS + + a) Subject to the terms of this Agreement, each Contributor hereby grants + Recipient a non-exclusive, worldwide, royalty-free copyright license to + reproduce, prepare derivative works of, publicly display, publicly perform, + distribute and sublicense the Contribution of such Contributor, if any, and such + derivative works, in source code and object code form. + + b) Subject to the terms of this Agreement, each Contributor hereby grants + Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed + Patents to make, use, sell, offer to sell, import and otherwise transfer the + Contribution of such Contributor, if any, in source code and object code form. + This patent license shall apply to the combination of the Contribution and the + Program if, at the time the Contribution is added by the Contributor, such + addition of the Contribution causes such combination to be covered by the + Licensed Patents. The patent license shall not apply to any other combinations + which include the Contribution. No hardware per se is licensed hereunder. + + c) Recipient understands that although each Contributor grants the licenses to + its Contributions set forth herein, no assurances are provided by any + Contributor that the Program does not infringe the patent or other intellectual + property rights of any other entity. Each Contributor disclaims any liability to + Recipient for claims brought by any other entity based on infringement of + intellectual property rights or otherwise. As a condition to exercising the + rights and licenses granted hereunder, each Recipient hereby assumes sole + responsibility to secure any other intellectual property rights needed, if any. + For example, if a third party patent license is required to allow Recipient to + distribute the Program, it is Recipient's responsibility to acquire that license + before distributing the Program. + + d) Each Contributor represents that to its knowledge it has sufficient copyright + rights in its Contribution, if any, to grant the copyright license set forth in + this Agreement. + + 3. REQUIREMENTS + + A Contributor may choose to distribute the Program in object code form under its + own license agreement, provided that: + + a) it complies with the terms and conditions of this Agreement; and + + b) its license agreement: + + i) effectively disclaims on behalf of all Contributors all warranties and + conditions, express and implied, including warranties or conditions of title and + non-infringement, and implied warranties or conditions of merchantability and + fitness for a particular purpose; + + ii) effectively excludes on behalf of all Contributors all liability for + damages, including direct, indirect, special, incidental and consequential + damages, such as lost profits; + + iii) states that any provisions which differ from this Agreement are offered by + that Contributor alone and not by any other party; and + + iv) states that source code for the Program is available from such Contributor, + and informs licensees how to obtain it in a reasonable manner on or through a + medium customarily used for software exchange. + + When the Program is made available in source code form: + + a) it must be made available under this Agreement; and + + b) a copy of this Agreement must be included with each copy of the Program. + + Contributors may not remove or alter any copyright notices contained within the + Program. + + Each Contributor must identify itself as the originator of its Contribution, if + any, in a manner that reasonably allows subsequent Recipients to identify the + originator of the Contribution. + + 4. COMMERCIAL DISTRIBUTION + + Commercial distributors of software may accept certain responsibilities with + respect to end users, business partners and the like. While this license is + intended to facilitate the commercial use of the Program, the Contributor who + includes the Program in a commercial product offering should do so in a manner + which does not create potential liability for other Contributors. Therefore, if + a Contributor includes the Program in a commercial product offering, such + Contributor ("Commercial Contributor") hereby agrees to defend and indemnify + every other Contributor ("Indemnified Contributor") against any losses, damages + and costs (collectively "Losses") arising from claims, lawsuits and other legal + actions brought by a third party against the Indemnified Contributor to the + extent caused by the acts or omissions of such Commercial Contributor in + connection with its distribution of the Program in a commercial product + offering. The obligations in this section do not apply to any claims or Losses + relating to any actual or alleged intellectual property infringement. In order + to qualify, an Indemnified Contributor must: a) promptly notify the Commercial + Contributor in writing of such claim, and b) allow the Commercial Contributor to + control, and cooperate with the Commercial Contributor in, the defense and any + related settlement negotiations. The Indemnified Contributor may participate in + any such claim at its own expense. + + For example, a Contributor might include the Program in a commercial product + offering, Product X. That Contributor is then a Commercial Contributor. If that + Commercial Contributor then makes performance claims, or offers warranties + related to Product X, those performance claims and warranties are such + Commercial Contributor's responsibility alone. Under this section, the + Commercial Contributor would have to defend claims against the other + Contributors related to those performance claims and warranties, and if a court + requires any other Contributor to pay any damages as a result, the Commercial + Contributor must pay those damages. + + 5. NO WARRANTY + + EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR + IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, + NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each + Recipient is solely responsible for determining the appropriateness of using and + distributing the Program and assumes all risks associated with its exercise of + rights under this Agreement, including but not limited to the risks and costs of + program errors, compliance with applicable laws, damage to or loss of data, + programs or equipment, and unavailability or interruption of operations. + + 6. DISCLAIMER OF LIABILITY + + EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY + CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST + PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS + GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + 7. GENERAL + + If any provision of this Agreement is invalid or unenforceable under applicable + law, it shall not affect the validity or enforceability of the remainder of the + terms of this Agreement, and without further action by the parties hereto, such + provision shall be reformed to the minimum extent necessary to make such + provision valid and enforceable. + + If Recipient institutes patent litigation against a Contributor with respect to + a patent applicable to software (including a cross-claim or counterclaim in a + lawsuit), then any patent licenses granted by that Contributor to such Recipient + under this Agreement shall terminate as of the date such litigation is filed. In + addition, if Recipient institutes patent litigation against any entity + (including a cross-claim or counterclaim in a lawsuit) alleging that the Program + itself (excluding combinations of the Program with other software or hardware) + infringes such Recipient's patent(s), then such Recipient's rights granted under + Section 2(b) shall terminate as of the date such litigation is filed. + + All Recipient's rights under this Agreement shall terminate if it fails to + comply with any of the material terms or conditions of this Agreement and does + not cure such failure in a reasonable period of time after becoming aware of + such noncompliance. If all Recipient's rights under this Agreement terminate, + Recipient agrees to cease use and distribution of the Program as soon as + reasonably practicable. However, Recipient's obligations under this Agreement + and any licenses granted by Recipient relating to the Program shall continue and + survive. + + Everyone is permitted to copy and distribute copies of this Agreement, but in + order to avoid inconsistency the Agreement is copyrighted and may only be + modified in the following manner. The Agreement Steward reserves the right to + publish new versions (including revisions) of this Agreement from time to time. + No one other than the Agreement Steward has the right to modify this Agreement. + IBM is the initial Agreement Steward. IBM may assign the responsibility to serve + as the Agreement Steward to a suitable separate entity. Each new version of the + Agreement will be given a distinguishing version number. The Program (including + Contributions) may always be distributed subject to the version of the Agreement + under which it was received. In addition, after a new version of the Agreement + is published, Contributor may elect to distribute the Program (including its + Contributions) under the new version. Except as expressly stated in Sections + 2(a) and 2(b) above, Recipient receives no rights or licenses to the + intellectual property of any Contributor under this Agreement, whether + expressly, by implication, estoppel or otherwise. All rights in the Program not + expressly granted under this Agreement are reserved. + + This Agreement is governed by the laws of the State of New York and the + intellectual property laws of the United States of America. No party to this + Agreement will bring a legal action under this Agreement more than one year + after the cause of action arose. Each party waives its rights to a jury trial in + any resulting litigation. + + from IBM Corp http://www.ibm.com/ + cloud-wsdl4j-1.6.2.jar http://sourceforge.net/projects/wsdl4j/ + cloud-wsdl4j.jar http://sourceforge.net/projects/wsdl4j/ + + licensed under the Common Public License - v 1.0 http://opensource.org/licenses/cpl1.0 (as follows) + + + Common Public License Version 1.0 (CPL) + + THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS COMMON PUBLIC + LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM + CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + + 1. DEFINITIONS + + "Contribution means: + + a) in the case of the initial Contributor, the initial code and documentation + distributed under this Agreement, and + + b) in the case of each subsequent Contributor: + + i) changes to the Program, and + + ii) additions to the Program; + + where such changes and/or additions to the Program originate from and are + distributed by that particular Contributor. A Contribution 'originates' from a + Contributor if it was added to the Program by such Contributor itself or anyone + acting on such Contributor's behalf. Contributions do not include additions to + the Program which: (i) are separate modules of software distributed in + conjunction with the Program under their own license agreement, and (ii) are not + derivative works of the Program. + + "Contributor means any person or entity that distributes the Program. + + "Licensed Patents mean patent claims licensable by a Contributor which are + "necessarily infringed by the use or sale of its Contribution alone or when + "combined with the Program. + + "Program means the Contributions distributed in accordance with this Agreement. + + "Recipient means anyone who receives the Program under this Agreement, including + "all Contributors. + + 2. GRANT OF RIGHTS + + a) Subject to the terms of this Agreement, each Contributor hereby grants + Recipient a non-exclusive, worldwide, royalty-free copyright license to + reproduce, prepare derivative works of, publicly display, publicly perform, + distribute and sublicense the Contribution of such Contributor, if any, and such + derivative works, in source code and object code form. + + b) Subject to the terms of this Agreement, each Contributor hereby grants + Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed + Patents to make, use, sell, offer to sell, import and otherwise transfer the + Contribution of such Contributor, if any, in source code and object code form. + This patent license shall apply to the combination of the Contribution and the + Program if, at the time the Contribution is added by the Contributor, such + addition of the Contribution causes such combination to be covered by the + Licensed Patents. The patent license shall not apply to any other combinations + which include the Contribution. No hardware per se is licensed hereunder. + + c) Recipient understands that although each Contributor grants the licenses to + its Contributions set forth herein, no assurances are provided by any + Contributor that the Program does not infringe the patent or other intellectual + property rights of any other entity. Each Contributor disclaims any liability to + Recipient for claims brought by any other entity based on infringement of + intellectual property rights or otherwise. As a condition to exercising the + rights and licenses granted hereunder, each Recipient hereby assumes sole + responsibility to secure any other intellectual property rights needed, if any. + For example, if a third party patent license is required to allow Recipient to + distribute the Program, it is Recipient's responsibility to acquire that license + before distributing the Program. + + d) Each Contributor represents that to its knowledge it has sufficient copyright + rights in its Contribution, if any, to grant the copyright license set forth in + this Agreement. + + 3. REQUIREMENTS + + A Contributor may choose to distribute the Program in object code form under its + own license agreement, provided that: + + a) it complies with the terms and conditions of this Agreement; and + + b) its license agreement: + + i) effectively disclaims on behalf of all Contributors all warranties and + conditions, express and implied, including warranties or conditions of title and + non-infringement, and implied warranties or conditions of merchantability and + fitness for a particular purpose; + + ii) effectively excludes on behalf of all Contributors all liability for + damages, including direct, indirect, special, incidental and consequential + damages, such as lost profits; + + iii) states that any provisions which differ from this Agreement are offered by + that Contributor alone and not by any other party; and + + iv) states that source code for the Program is available from such Contributor, + and informs licensees how to obtain it in a reasonable manner on or through a + medium customarily used for software exchange. + + When the Program is made available in source code form: + + a) it must be made available under this Agreement; and + + b) a copy of this Agreement must be included with each copy of the Program. + + Contributors may not remove or alter any copyright notices contained within the + Program. + + Each Contributor must identify itself as the originator of its Contribution, if + any, in a manner that reasonably allows subsequent Recipients to identify the + originator of the Contribution. + + 4. COMMERCIAL DISTRIBUTION + + Commercial distributors of software may accept certain responsibilities with + respect to end users, business partners and the like. While this license is + intended to facilitate the commercial use of the Program, the Contributor who + includes the Program in a commercial product offering should do so in a manner + which does not create potential liability for other Contributors. Therefore, if + a Contributor includes the Program in a commercial product offering, such + Contributor ("Commercial Contributor") hereby agrees to defend and indemnify + every other Contributor ("Indemnified Contributor") against any losses, damages + and costs (collectively "Losses") arising from claims, lawsuits and other legal + actions brought by a third party against the Indemnified Contributor to the + extent caused by the acts or omissions of such Commercial Contributor in + connection with its distribution of the Program in a commercial product + offering. The obligations in this section do not apply to any claims or Losses + relating to any actual or alleged intellectual property infringement. In order + to qualify, an Indemnified Contributor must: a) promptly notify the Commercial + Contributor in writing of such claim, and b) allow the Commercial Contributor to + control, and cooperate with the Commercial Contributor in, the defense and any + related settlement negotiations. The Indemnified Contributor may participate in + any such claim at its own expense. + + For example, a Contributor might include the Program in a commercial product + offering, Product X. That Contributor is then a Commercial Contributor. If that + Commercial Contributor then makes performance claims, or offers warranties + related to Product X, those performance claims and warranties are such + Commercial Contributor's responsibility alone. Under this section, the + Commercial Contributor would have to defend claims against the other + Contributors related to those performance claims and warranties, and if a court + requires any other Contributor to pay any damages as a result, the Commercial + Contributor must pay those damages. + + 5. NO WARRANTY + + EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR + IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, + NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each + Recipient is solely responsible for determining the appropriateness of using and + distributing the Program and assumes all risks associated with its exercise of + rights under this Agreement, including but not limited to the risks and costs of + program errors, compliance with applicable laws, damage to or loss of data, + programs or equipment, and unavailability or interruption of operations. + + 6. DISCLAIMER OF LIABILITY + + EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY + CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST + PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS + GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + 7. GENERAL + + If any provision of this Agreement is invalid or unenforceable under applicable + law, it shall not affect the validity or enforceability of the remainder of the + terms of this Agreement, and without further action by the parties hereto, such + provision shall be reformed to the minimum extent necessary to make such + provision valid and enforceable. + + If Recipient institutes patent litigation against a Contributor with respect to + a patent applicable to software (including a cross-claim or counterclaim in a + lawsuit), then any patent licenses granted by that Contributor to such Recipient + under this Agreement shall terminate as of the date such litigation is filed. In + addition, if Recipient institutes patent litigation against any entity + (including a cross-claim or counterclaim in a lawsuit) alleging that the Program + itself (excluding combinations of the Program with other software or hardware) + infringes such Recipient's patent(s), then such Recipient's rights granted under + Section 2(b) shall terminate as of the date such litigation is filed. + + All Recipient's rights under this Agreement shall terminate if it fails to + comply with any of the material terms or conditions of this Agreement and does + not cure such failure in a reasonable period of time after becoming aware of + such noncompliance. If all Recipient's rights under this Agreement terminate, + Recipient agrees to cease use and distribution of the Program as soon as + reasonably practicable. However, Recipient's obligations under this Agreement + and any licenses granted by Recipient relating to the Program shall continue and + survive. + + Everyone is permitted to copy and distribute copies of this Agreement, but in + order to avoid inconsistency the Agreement is copyrighted and may only be + modified in the following manner. The Agreement Steward reserves the right to + publish new versions (including revisions) of this Agreement from time to time. + No one other than the Agreement Steward has the right to modify this Agreement. + IBM is the initial Agreement Steward. IBM may assign the responsibility to serve + as the Agreement Steward to a suitable separate entity. Each new version of the + Agreement will be given a distinguishing version number. The Program (including + Contributions) may always be distributed subject to the version of the Agreement + under which it was received. In addition, after a new version of the Agreement + is published, Contributor may elect to distribute the Program (including its + Contributions) under the new version. Except as expressly stated in Sections + 2(a) and 2(b) above, Recipient receives no rights or licenses to the + intellectual property of any Contributor under this Agreement, whether + expressly, by implication, estoppel or otherwise. All rights in the Program not + expressly granted under this Agreement are reserved. + + This Agreement is governed by the laws of the State of New York and the + intellectual property laws of the United States of America. No party to this + Agreement will bring a legal action under this Agreement more than one year + after the cause of action arose. Each party waives its rights to a jury trial in + any resulting litigation. + + from JUnit Project http://www.junit.org/ + cloud-junit.jar http://kentbeck.github.com/junit/ + + licensed under the Eclipse Distribution License Version 1.0 http://www.eclipse.org/org/documents/edl-v10.php (as follows) + + Copyright (c) 2012 The Eclipse Foundation. + + Eclipse Distribution License Version 1.0 + + Copyright (c) 2007, Eclipse Foundation, Inc. and its licensors. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. Redistributions in binary form must + reproduce the above copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided with the + distribution. Neither the name of the Eclipse Foundation, Inc. nor the names of + its contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + from The Eclipse Foundation http://www.eclipse.org + cloud-javax.persistence-2.0.0.jar http://wiki.eclipse.org/EclipseLink/Release/2.0.0 + + licensed under the XStream BSD Style License https://fisheye.codehaus.org/browse/xstream/trunk/LICENSE.txt?hb=true (as follows) + + + (BSD Style License) + + Copyright (c) 2003-2006, Joe Walnes Copyright (c) 2006-2011, XStream Committers + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. Redistributions in binary form must + reproduce the above copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided with the + distribution. + + Neither the name of XStream nor the names of its contributors may be used to + endorse or promote products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + from XStream Committers http://xstream.codehaus.org/ + cloud-xstream-1.3.1.jar http://xstream.codehaus.org/repository.html + + Within the deps/awsapi-lib directory licensed under the ANTLR 2 License http://www.antlr2.org/license.html (as follows) - + ANTLR 2 License We reserve no legal rights to the ANTLR--it is fully in the public domain. An @@ -328,7 +2224,7 @@ Within the deps/awsapi-lib directory remain intact in our source code. As long as these guidelines are kept, we expect to continue enhancing this system and expect to make other tools available as they are completed. - + from ANTLR Translator Generator Project http://www.antlr2.org/ antlr-2.7.6.jar http://repo1.maven.org/maven2/antlr/antlr/2.7.6/antlr-2.7.6-sources.jar @@ -1841,7 +3737,7 @@ Within the deps/awsapi-lib directory STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - + from DOM4J Project http://dom4j.sourceforge.net/ dom4j-1.6.1.jar http://dom4j.sourceforge.net/source-repository.html @@ -2345,1927 +4241,7 @@ Within the deps/awsapi-lib directory use the text of this Exhibit A rather than the text found in the Original Code Source Code for Your Modifications.] - + from Shigeru Chiba http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/ javassist-3.9.0.GA.jar http://sourceforge.net/projects/jboss/files/Javassist/ - -Within the patches/systemvm/debian/config/etc directory - placed in the public domain - by Adiscon GmbH http://www.adiscon.com/ - rsyslog.conf - by Simon Kelley - dnsmasq.conf - vpcdnsmasq.conf - - -Within the patches/systemvm/debian/config/etc/apache2 directory - licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) - Copyright (c) 2012 The Apache Software Foundation - from The Apache Software Foundation http://www.apache.org/ - httpd.conf - ports.conf - sites-available/default - sites-available/default-ssl - vhostexample.conf - - -Within the patches/systemvm/debian/config/etc/ssh/ directory - licensed under the BSD (2-clause) http://www.opensource.org/licenses/BSD-2-Clause (as follows) - - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. Redistributions in binary form must - reproduce the above copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided with the - distribution. - - Neither the name of the author nor the names of contributors may be used to - endorse or promote products derived from this software without specific prior - written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - from OpenSSH Project http://www.openssh.org/ - sshd_config - - -Within the patches/systemvm/debian/config/root/redundant_router directory - placed in the public domain - by The netfilter.org project http://www.netfilter.org/ - conntrackd.conf.templ - - -Within the scripts/storage/secondary directory - licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) - Copyright (c) 2010-2011 OpenStack, LLC. - from OpenStack, LLC http://www.openstack.org - swift - - -Within the scripts/vm/hypervisor/xenserver directory - licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) - Copyright (c) 2010-2011 OpenStack, LLC. - from OpenStack, LLC http://www.openstack.org - swift - - -Within the target/jar directory - placed in the public domain - by Distributed Computing Laboratory at Emory University http://creativecommons.org/licenses/publicdomain/ - cloud-backport-util-concurrent-3.0.jar - - licensed under the Apache License, Version 1.1 http://www.apache.org/licenses/LICENSE-1.1 (as follows) - - Copyright (c) 2012 The Apache Software Foundation - - /* ==================================================================== - * The Apache Software License, Version 1.1 - * - * Copyright (c) 2000 The Apache Software Foundation. All rights - * reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Apache" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - */ - - from The Apache Software Foundation http://www.apache.org/ - cloud-commons-discovery.jar http://commons.apache.org/discovery/ - - licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) - Copyright (c) 2012 The Apache Software Foundation - from The Apache Software Foundation http://www.apache.org/ - cloud-axis.jar http://axis.apache.org/axis/ - cloud-cglib.jar http://cglib.sourceforge.net/ - cloud-commons-codec-1.5.jar http://commons.apache.org/codec/ - cloud-commons-collections-3.2.1.jar http://commons.apache.org/collections/ - cloud-commons-configuration-1.8.jar http://commons.apache.org/configuration/ - cloud-commons-dbcp-1.4.jar http://commons.apache.org/dbcp/ - cloud-commons-httpclient-3.1.jar http://hc.apache.org/httpclient-3.x/ - cloud-commons-lang-2.6.jar http://commons.apache.org/lang/ - cloud-commons-logging-1.1.1.jar http://commons.apache.org/logging/ - cloud-commons-pool-1.5.6.jar http://commons.apache.org/pool/ - cloud-log4j-extras.jar http://logging.apache.org/log4j/companions/extras/ - cloud-log4j.jar http://logging.apache.org/log4j/ - cloud-ws-commons-util-1.0.2.jar http://ws.apache.org/commons/util/ - cloud-xmlrpc-client-3.1.3.jar http://ws.apache.org/xmlrpc/client.html - cloud-xmlrpc-common-3.1.3.jar http://ws.apache.org/xmlrpc/xmlrpc-common/ - - licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) - Copyright (c) 2007-2010, The JASYPT team (http://www.jasypt.org) - from The JASYPT team http://www.jasypt.org - cloud-jasypt-1.9.jar http://www.jasypt.org - - licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) - Copyright (c) 2003-2007 Luck Consulting Pty Ltd - from Luck Consulting Pty Ltd http://gregluck.com/blog/about/ - cloud-ehcache.jar http://ehcache.org/ - - licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) - Copyright (c) 2009 Google Inc. - from Google Inc. http://google.com - cloud-google-gson-1.7.1.jar http://code.google.com/p/google-gson/ - - licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) - - from Jetty Committers http://jetty.codehaus.org/jetty/ - jetty-6.1.26.jar http://repo1.maven.org/maven2/org/mortbay/jetty/jetty/6.1.26/jetty-6.1.26-sources.jar - jetty-util-6.1.26.jar http://repo1.maven.org/maven2/org/mortbay/jetty/jetty-util/6.1.26/jetty-util-6.1.26-sources.jar - - licensed under the BSD (3-clause) http://www.opensource.org/licenses/BSD-3-Clause (as follows) - - Copyright (c) 2009, Caringo, Inc. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - THE POSSIBILITY OF SUCH DAMAGE. - - from Caringo, Inc. http://www.caringo.com/ - CAStorSDK.jar http://www.castor.org/download.html - - licensed under the BSD (3-clause) http://www.opensource.org/licenses/BSD-3-Clause (as follows) - - Copyright (c) 2002-2011 Atsuhiko Yamanaka, JCraft,Inc. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - THE POSSIBILITY OF SUCH DAMAGE. - - from JCraft http://www.jcraft.com/ - cloud-jsch-0.1.42.jar http://www.jcraft.com/jsch/ - - licensed under the BSD (3-clause) http://www.opensource.org/licenses/BSD-3-Clause (as follows) - - Copyright (c) 2007-2008 Trilead AG (http://www.trilead.com) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - THE POSSIBILITY OF SUCH DAMAGE. - - from Trilead AG http://www.trilead.com - cloud-trilead-ssh2-build213.jar http://sourceforge.net/projects/orion-ssh2/ - - licensed under the Bouncy Castle adaptation of MIT X11 License http://www.bouncycastle.org/licence.html (as follows) - - - Please note: our license is an adaptation of the MIT X11 License and should be - read as such. - - LICENSE Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle - (http://www.bouncycastle.org) - - Permission is hereby granted, free of charge, to any person obtaining a copy of - this software and associated documentation files (the "Software"), to deal in - the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - from The Legion Of The Bouncy Castle http://www.bouncycastle.org - cloud-bcprov-jdk16-1.45.jar http://repo1.maven.org/maven2/org/bouncycastle/bcprov-jdk16/1.45/bcprov-jdk16-1.45-sources.jar - - licensed under the COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 http://www.opensource.org/licenses/CDDL-1.0 (as follows) - - Copyright (c) 2006 Sun Microsystems, Inc. All rights reserved. - - COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 - - 1. Definitions. - - 1.1. "Contributor" means each individual or entity that - creates or contributes to the creation of Modifications. - - 1.2. "Contributor Version" means the combination of the - Original Software, prior Modifications used by a - Contributor (if any), and the Modifications made by that - particular Contributor. - - 1.3. "Covered Software" means (a) the Original Software, or - (b) Modifications, or (c) the combination of files - containing Original Software with files containing - Modifications, in each case including portions thereof. - - 1.4. "Executable" means the Covered Software in any form - other than Source Code. - - 1.5. "Initial Developer" means the individual or entity - that first makes Original Software available under this - License. - - 1.6. "Larger Work" means a work which combines Covered - Software or portions thereof with code not governed by the - terms of this License. - - 1.7. "License" means this document. - - 1.8. "Licensable" means having the right to grant, to the - maximum extent possible, whether at the time of the initial - grant or subsequently acquired, any and all of the rights - conveyed herein. - - 1.9. "Modifications" means the Source Code and Executable - form of any of the following: - - A. Any file that results from an addition to, - deletion from or modification of the contents of a - file containing Original Software or previous - Modifications; - - B. Any new file that contains any part of the - Original Software or previous Modification; or - - C. Any new file that is contributed or otherwise made - available under the terms of this License. - - 1.10. "Original Software" means the Source Code and - Executable form of computer software code that is - originally released under this License. - - 1.11. "Patent Claims" means any patent claim(s), now owned - or hereafter acquired, including without limitation, - method, process, and apparatus claims, in any patent - Licensable by grantor. - - 1.12. "Source Code" means (a) the common form of computer - software code in which modifications are made and (b) - associated documentation included in or with such code. - - 1.13. "You" (or "Your") means an individual or a legal - entity exercising rights under, and complying with all of - the terms of, this License. For legal entities, "You" - includes any entity which controls, is controlled by, or is - under common control with You. For purposes of this - definition, "control" means (a) the power, direct or - indirect, to cause the direction or management of such - entity, whether by contract or otherwise, or (b) ownership - of more than fifty percent (50%) of the outstanding shares - or beneficial ownership of such entity. - - 2. License Grants. - - 2.1. The Initial Developer Grant. - - Conditioned upon Your compliance with Section 3.1 below and - subject to third party intellectual property claims, the - Initial Developer hereby grants You a world-wide, - royalty-free, non-exclusive license: - - (a) under intellectual property rights (other than - patent or trademark) Licensable by Initial Developer, - to use, reproduce, modify, display, perform, - sublicense and distribute the Original Software (or - portions thereof), with or without Modifications, - and/or as part of a Larger Work; and - - (b) under Patent Claims infringed by the making, - using or selling of Original Software, to make, have - made, use, practice, sell, and offer for sale, and/or - otherwise dispose of the Original Software (or - portions thereof). - - (c) The licenses granted in Sections 2.1(a) and (b) - are effective on the date Initial Developer first - distributes or otherwise makes the Original Software - available to a third party under the terms of this - License. - - (d) Notwithstanding Section 2.1(b) above, no patent - license is granted: (1) for code that You delete from - the Original Software, or (2) for infringements - caused by: (i) the modification of the Original - Software, or (ii) the combination of the Original - Software with other software or devices. - - 2.2. Contributor Grant. - - Conditioned upon Your compliance with Section 3.1 below and - subject to third party intellectual property claims, each - Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - (a) under intellectual property rights (other than - patent or trademark) Licensable by Contributor to - use, reproduce, modify, display, perform, sublicense - and distribute the Modifications created by such - Contributor (or portions thereof), either on an - unmodified basis, with other Modifications, as - Covered Software and/or as part of a Larger Work; and - - (b) under Patent Claims infringed by the making, - using, or selling of Modifications made by that - Contributor either alone and/or in combination with - its Contributor Version (or portions of such - combination), to make, use, sell, offer for sale, - have made, and/or otherwise dispose of: (1) - Modifications made by that Contributor (or portions - thereof); and (2) the combination of Modifications - made by that Contributor with its Contributor Version - (or portions of such combination). - - (c) The licenses granted in Sections 2.2(a) and - 2.2(b) are effective on the date Contributor first - distributes or otherwise makes the Modifications - available to a third party. - - (d) Notwithstanding Section 2.2(b) above, no patent - license is granted: (1) for any code that Contributor - has deleted from the Contributor Version; (2) for - infringements caused by: (i) third party - modifications of Contributor Version, or (ii) the - combination of Modifications made by that Contributor - with other software (except as part of the - Contributor Version) or other devices; or (3) under - Patent Claims infringed by Covered Software in the - absence of Modifications made by that Contributor. - - 3. Distribution Obligations. - - 3.1. Availability of Source Code. - - Any Covered Software that You distribute or otherwise make - available in Executable form must also be made available in - Source Code form and that Source Code form must be - distributed only under the terms of this License. You must - include a copy of this License with every copy of the - Source Code form of the Covered Software You distribute or - otherwise make available. You must inform recipients of any - such Covered Software in Executable form as to how they can - obtain such Covered Software in Source Code form in a - reasonable manner on or through a medium customarily used - for software exchange. - - 3.2. Modifications. - - The Modifications that You create or to which You - contribute are governed by the terms of this License. You - represent that You believe Your Modifications are Your - original creation(s) and/or You have sufficient rights to - grant the rights conveyed by this License. - - 3.3. Required Notices. - - You must include a notice in each of Your Modifications - that identifies You as the Contributor of the Modification. - You may not remove or alter any copyright, patent or - trademark notices contained within the Covered Software, or - any notices of licensing or any descriptive text giving - attribution to any Contributor or the Initial Developer. - - 3.4. Application of Additional Terms. - - You may not offer or impose any terms on any Covered - Software in Source Code form that alters or restricts the - applicable version of this License or the recipients' - rights hereunder. You may choose to offer, and to charge a - fee for, warranty, support, indemnity or liability - obligations to one or more recipients of Covered Software. - However, you may do so only on Your own behalf, and not on - behalf of the Initial Developer or any Contributor. You - must make it absolutely clear that any such warranty, - support, indemnity or liability obligation is offered by - You alone, and You hereby agree to indemnify the Initial - Developer and every Contributor for any liability incurred - by the Initial Developer or such Contributor as a result of - warranty, support, indemnity or liability terms You offer. - - 3.5. Distribution of Executable Versions. - - You may distribute the Executable form of the Covered - Software under the terms of this License or under the terms - of a license of Your choice, which may contain terms - different from this License, provided that You are in - compliance with the terms of this License and that the - license for the Executable form does not attempt to limit - or alter the recipient's rights in the Source Code form - from the rights set forth in this License. If You - distribute the Covered Software in Executable form under a - different license, You must make it absolutely clear that - any terms which differ from this License are offered by You - alone, not by the Initial Developer or Contributor. You - hereby agree to indemnify the Initial Developer and every - Contributor for any liability incurred by the Initial - Developer or such Contributor as a result of any such terms - You offer. - - 3.6. Larger Works. - - You may create a Larger Work by combining Covered Software - with other code not governed by the terms of this License - and distribute the Larger Work as a single product. In such - a case, You must make sure the requirements of this License - are fulfilled for the Covered Software. - - 4. Versions of the License. - - 4.1. New Versions. - - Sun Microsystems, Inc. is the initial license steward and - may publish revised and/or new versions of this License - from time to time. Each version will be given a - distinguishing version number. Except as provided in - Section 4.3, no one other than the license steward has the - right to modify this License. - - 4.2. Effect of New Versions. - - You may always continue to use, distribute or otherwise - make the Covered Software available under the terms of the - version of the License under which You originally received - the Covered Software. If the Initial Developer includes a - notice in the Original Software prohibiting it from being - distributed or otherwise made available under any - subsequent version of the License, You must distribute and - make the Covered Software available under the terms of the - version of the License under which You originally received - the Covered Software. Otherwise, You may also choose to - use, distribute or otherwise make the Covered Software - available under the terms of any subsequent version of the - License published by the license steward. - - 4.3. Modified Versions. - - When You are an Initial Developer and You want to create a - new license for Your Original Software, You may create and - use a modified version of this License if You: (a) rename - the license and remove any references to the name of the - license steward (except to note that the license differs - from this License); and (b) otherwise make it clear that - the license contains terms which differ from this License. - - 5. DISCLAIMER OF WARRANTY. - - COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" - BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, - INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED - SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR - PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND - PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY - COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE - INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF - ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF - WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF - ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS - DISCLAIMER. - - 6. TERMINATION. - - 6.1. This License and the rights granted hereunder will - terminate automatically if You fail to comply with terms - herein and fail to cure such breach within 30 days of - becoming aware of the breach. Provisions which, by their - nature, must remain in effect beyond the termination of - this License shall survive. - - 6.2. If You assert a patent infringement claim (excluding - declaratory judgment actions) against Initial Developer or - a Contributor (the Initial Developer or Contributor against - whom You assert such claim is referred to as "Participant") - alleging that the Participant Software (meaning the - Contributor Version where the Participant is a Contributor - or the Original Software where the Participant is the - Initial Developer) directly or indirectly infringes any - patent, then any and all rights granted directly or - indirectly to You by such Participant, the Initial - Developer (if the Initial Developer is not the Participant) - and all Contributors under Sections 2.1 and/or 2.2 of this - License shall, upon 60 days notice from Participant - terminate prospectively and automatically at the expiration - of such 60 day notice period, unless if within such 60 day - period You withdraw Your claim with respect to the - Participant Software against such Participant either - unilaterally or pursuant to a written agreement with - Participant. - - 6.3. In the event of termination under Sections 6.1 or 6.2 - above, all end user licenses that have been validly granted - by You or any distributor hereunder prior to termination - (excluding licenses granted to You by any distributor) - shall survive termination. - - 7. LIMITATION OF LIABILITY. - - UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT - (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE - INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF - COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE - LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR - CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT - LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK - STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER - COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN - INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF - LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL - INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT - APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO - NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR - CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT - APPLY TO YOU. - - 8. U.S. GOVERNMENT END USERS. - - The Covered Software is a "commercial item," as that term is - defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial - computer software" (as that term is defined at 48 C.F.R. ¤ - 252.227-7014(a)(1)) and "commercial computer software - documentation" as such terms are used in 48 C.F.R. 12.212 (Sept. - 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 - through 227.7202-4 (June 1995), all U.S. Government End Users - acquire Covered Software with only those rights set forth herein. - This U.S. Government Rights clause is in lieu of, and supersedes, - any other FAR, DFAR, or other clause or provision that addresses - Government rights in computer software under this License. - - 9. MISCELLANEOUS. - - This License represents the complete agreement concerning subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the - extent necessary to make it enforceable. This License shall be - governed by the law of the jurisdiction specified in a notice - contained within the Original Software (except to the extent - applicable law, if any, provides otherwise), excluding such - jurisdiction's conflict-of-law provisions. Any litigation - relating to this License shall be subject to the jurisdiction of - the courts located in the jurisdiction and venue specified in a - notice contained within the Original Software, with the losing - party responsible for costs, including, without limitation, court - costs and reasonable attorneys' fees and expenses. The - application of the United Nations Convention on Contracts for the - International Sale of Goods is expressly excluded. Any law or - regulation which provides that the language of a contract shall - be construed against the drafter shall not apply to this License. - You agree that You alone are responsible for compliance with the - United States export administration regulations (and the export - control laws and regulation of any other countries) when You use, - distribute or otherwise make available any Covered Software. - - 10. RESPONSIBILITY FOR CLAIMS. - - As between Initial Developer and the Contributors, each party is - responsible for claims and damages arising, directly or - indirectly, out of its utilization of rights under this License - and You agree to work with Initial Developer and Contributors to - distribute such responsibility on an equitable basis. Nothing - herein is intended or shall be deemed to constitute any admission - of liability. - - from Project GlassFish http://glassfish.java.net/ - cloud-ejb-api-3.0.jar http://repo1.maven.org/maven2/javax/ejb/ejb-api/3.0/ejb-api-3.0-sources.jar - cloud-jstl-1.2.jar http://jstl.java.net/ - - licensed under the COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 http://www.opensource.org/licenses/CDDL-1.0 (as follows) - - Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - - COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 - - 1. Definitions. - - 1.1. "Contributor" means each individual or entity that - creates or contributes to the creation of Modifications. - - 1.2. "Contributor Version" means the combination of the - Original Software, prior Modifications used by a - Contributor (if any), and the Modifications made by that - particular Contributor. - - 1.3. "Covered Software" means (a) the Original Software, or - (b) Modifications, or (c) the combination of files - containing Original Software with files containing - Modifications, in each case including portions thereof. - - 1.4. "Executable" means the Covered Software in any form - other than Source Code. - - 1.5. "Initial Developer" means the individual or entity - that first makes Original Software available under this - License. - - 1.6. "Larger Work" means a work which combines Covered - Software or portions thereof with code not governed by the - terms of this License. - - 1.7. "License" means this document. - - 1.8. "Licensable" means having the right to grant, to the - maximum extent possible, whether at the time of the initial - grant or subsequently acquired, any and all of the rights - conveyed herein. - - 1.9. "Modifications" means the Source Code and Executable - form of any of the following: - - A. Any file that results from an addition to, - deletion from or modification of the contents of a - file containing Original Software or previous - Modifications; - - B. Any new file that contains any part of the - Original Software or previous Modification; or - - C. Any new file that is contributed or otherwise made - available under the terms of this License. - - 1.10. "Original Software" means the Source Code and - Executable form of computer software code that is - originally released under this License. - - 1.11. "Patent Claims" means any patent claim(s), now owned - or hereafter acquired, including without limitation, - method, process, and apparatus claims, in any patent - Licensable by grantor. - - 1.12. "Source Code" means (a) the common form of computer - software code in which modifications are made and (b) - associated documentation included in or with such code. - - 1.13. "You" (or "Your") means an individual or a legal - entity exercising rights under, and complying with all of - the terms of, this License. For legal entities, "You" - includes any entity which controls, is controlled by, or is - under common control with You. For purposes of this - definition, "control" means (a) the power, direct or - indirect, to cause the direction or management of such - entity, whether by contract or otherwise, or (b) ownership - of more than fifty percent (50%) of the outstanding shares - or beneficial ownership of such entity. - - 2. License Grants. - - 2.1. The Initial Developer Grant. - - Conditioned upon Your compliance with Section 3.1 below and - subject to third party intellectual property claims, the - Initial Developer hereby grants You a world-wide, - royalty-free, non-exclusive license: - - (a) under intellectual property rights (other than - patent or trademark) Licensable by Initial Developer, - to use, reproduce, modify, display, perform, - sublicense and distribute the Original Software (or - portions thereof), with or without Modifications, - and/or as part of a Larger Work; and - - (b) under Patent Claims infringed by the making, - using or selling of Original Software, to make, have - made, use, practice, sell, and offer for sale, and/or - otherwise dispose of the Original Software (or - portions thereof). - - (c) The licenses granted in Sections 2.1(a) and (b) - are effective on the date Initial Developer first - distributes or otherwise makes the Original Software - available to a third party under the terms of this - License. - - (d) Notwithstanding Section 2.1(b) above, no patent - license is granted: (1) for code that You delete from - the Original Software, or (2) for infringements - caused by: (i) the modification of the Original - Software, or (ii) the combination of the Original - Software with other software or devices. - - 2.2. Contributor Grant. - - Conditioned upon Your compliance with Section 3.1 below and - subject to third party intellectual property claims, each - Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - (a) under intellectual property rights (other than - patent or trademark) Licensable by Contributor to - use, reproduce, modify, display, perform, sublicense - and distribute the Modifications created by such - Contributor (or portions thereof), either on an - unmodified basis, with other Modifications, as - Covered Software and/or as part of a Larger Work; and - - (b) under Patent Claims infringed by the making, - using, or selling of Modifications made by that - Contributor either alone and/or in combination with - its Contributor Version (or portions of such - combination), to make, use, sell, offer for sale, - have made, and/or otherwise dispose of: (1) - Modifications made by that Contributor (or portions - thereof); and (2) the combination of Modifications - made by that Contributor with its Contributor Version - (or portions of such combination). - - (c) The licenses granted in Sections 2.2(a) and - 2.2(b) are effective on the date Contributor first - distributes or otherwise makes the Modifications - available to a third party. - - (d) Notwithstanding Section 2.2(b) above, no patent - license is granted: (1) for any code that Contributor - has deleted from the Contributor Version; (2) for - infringements caused by: (i) third party - modifications of Contributor Version, or (ii) the - combination of Modifications made by that Contributor - with other software (except as part of the - Contributor Version) or other devices; or (3) under - Patent Claims infringed by Covered Software in the - absence of Modifications made by that Contributor. - - 3. Distribution Obligations. - - 3.1. Availability of Source Code. - - Any Covered Software that You distribute or otherwise make - available in Executable form must also be made available in - Source Code form and that Source Code form must be - distributed only under the terms of this License. You must - include a copy of this License with every copy of the - Source Code form of the Covered Software You distribute or - otherwise make available. You must inform recipients of any - such Covered Software in Executable form as to how they can - obtain such Covered Software in Source Code form in a - reasonable manner on or through a medium customarily used - for software exchange. - - 3.2. Modifications. - - The Modifications that You create or to which You - contribute are governed by the terms of this License. You - represent that You believe Your Modifications are Your - original creation(s) and/or You have sufficient rights to - grant the rights conveyed by this License. - - 3.3. Required Notices. - - You must include a notice in each of Your Modifications - that identifies You as the Contributor of the Modification. - You may not remove or alter any copyright, patent or - trademark notices contained within the Covered Software, or - any notices of licensing or any descriptive text giving - attribution to any Contributor or the Initial Developer. - - 3.4. Application of Additional Terms. - - You may not offer or impose any terms on any Covered - Software in Source Code form that alters or restricts the - applicable version of this License or the recipients' - rights hereunder. You may choose to offer, and to charge a - fee for, warranty, support, indemnity or liability - obligations to one or more recipients of Covered Software. - However, you may do so only on Your own behalf, and not on - behalf of the Initial Developer or any Contributor. You - must make it absolutely clear that any such warranty, - support, indemnity or liability obligation is offered by - You alone, and You hereby agree to indemnify the Initial - Developer and every Contributor for any liability incurred - by the Initial Developer or such Contributor as a result of - warranty, support, indemnity or liability terms You offer. - - 3.5. Distribution of Executable Versions. - - You may distribute the Executable form of the Covered - Software under the terms of this License or under the terms - of a license of Your choice, which may contain terms - different from this License, provided that You are in - compliance with the terms of this License and that the - license for the Executable form does not attempt to limit - or alter the recipient's rights in the Source Code form - from the rights set forth in this License. If You - distribute the Covered Software in Executable form under a - different license, You must make it absolutely clear that - any terms which differ from this License are offered by You - alone, not by the Initial Developer or Contributor. You - hereby agree to indemnify the Initial Developer and every - Contributor for any liability incurred by the Initial - Developer or such Contributor as a result of any such terms - You offer. - - 3.6. Larger Works. - - You may create a Larger Work by combining Covered Software - with other code not governed by the terms of this License - and distribute the Larger Work as a single product. In such - a case, You must make sure the requirements of this License - are fulfilled for the Covered Software. - - 4. Versions of the License. - - 4.1. New Versions. - - Sun Microsystems, Inc. is the initial license steward and - may publish revised and/or new versions of this License - from time to time. Each version will be given a - distinguishing version number. Except as provided in - Section 4.3, no one other than the license steward has the - right to modify this License. - - 4.2. Effect of New Versions. - - You may always continue to use, distribute or otherwise - make the Covered Software available under the terms of the - version of the License under which You originally received - the Covered Software. If the Initial Developer includes a - notice in the Original Software prohibiting it from being - distributed or otherwise made available under any - subsequent version of the License, You must distribute and - make the Covered Software available under the terms of the - version of the License under which You originally received - the Covered Software. Otherwise, You may also choose to - use, distribute or otherwise make the Covered Software - available under the terms of any subsequent version of the - License published by the license steward. - - 4.3. Modified Versions. - - When You are an Initial Developer and You want to create a - new license for Your Original Software, You may create and - use a modified version of this License if You: (a) rename - the license and remove any references to the name of the - license steward (except to note that the license differs - from this License); and (b) otherwise make it clear that - the license contains terms which differ from this License. - - 5. DISCLAIMER OF WARRANTY. - - COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" - BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, - INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED - SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR - PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND - PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY - COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE - INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF - ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF - WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF - ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS - DISCLAIMER. - - 6. TERMINATION. - - 6.1. This License and the rights granted hereunder will - terminate automatically if You fail to comply with terms - herein and fail to cure such breach within 30 days of - becoming aware of the breach. Provisions which, by their - nature, must remain in effect beyond the termination of - this License shall survive. - - 6.2. If You assert a patent infringement claim (excluding - declaratory judgment actions) against Initial Developer or - a Contributor (the Initial Developer or Contributor against - whom You assert such claim is referred to as "Participant") - alleging that the Participant Software (meaning the - Contributor Version where the Participant is a Contributor - or the Original Software where the Participant is the - Initial Developer) directly or indirectly infringes any - patent, then any and all rights granted directly or - indirectly to You by such Participant, the Initial - Developer (if the Initial Developer is not the Participant) - and all Contributors under Sections 2.1 and/or 2.2 of this - License shall, upon 60 days notice from Participant - terminate prospectively and automatically at the expiration - of such 60 day notice period, unless if within such 60 day - period You withdraw Your claim with respect to the - Participant Software against such Participant either - unilaterally or pursuant to a written agreement with - Participant. - - 6.3. In the event of termination under Sections 6.1 or 6.2 - above, all end user licenses that have been validly granted - by You or any distributor hereunder prior to termination - (excluding licenses granted to You by any distributor) - shall survive termination. - - 7. LIMITATION OF LIABILITY. - - UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT - (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE - INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF - COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE - LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR - CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT - LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK - STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER - COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN - INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF - LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL - INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT - APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO - NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR - CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT - APPLY TO YOU. - - 8. U.S. GOVERNMENT END USERS. - - The Covered Software is a "commercial item," as that term is - defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial - computer software" (as that term is defined at 48 C.F.R. ¤ - 252.227-7014(a)(1)) and "commercial computer software - documentation" as such terms are used in 48 C.F.R. 12.212 (Sept. - 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 - through 227.7202-4 (June 1995), all U.S. Government End Users - acquire Covered Software with only those rights set forth herein. - This U.S. Government Rights clause is in lieu of, and supersedes, - any other FAR, DFAR, or other clause or provision that addresses - Government rights in computer software under this License. - - 9. MISCELLANEOUS. - - This License represents the complete agreement concerning subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the - extent necessary to make it enforceable. This License shall be - governed by the law of the jurisdiction specified in a notice - contained within the Original Software (except to the extent - applicable law, if any, provides otherwise), excluding such - jurisdiction's conflict-of-law provisions. Any litigation - relating to this License shall be subject to the jurisdiction of - the courts located in the jurisdiction and venue specified in a - notice contained within the Original Software, with the losing - party responsible for costs, including, without limitation, court - costs and reasonable attorneys' fees and expenses. The - application of the United Nations Convention on Contracts for the - International Sale of Goods is expressly excluded. Any law or - regulation which provides that the language of a contract shall - be construed against the drafter shall not apply to this License. - You agree that You alone are responsible for compliance with the - United States export administration regulations (and the export - control laws and regulation of any other countries) when You use, - distribute or otherwise make available any Covered Software. - - 10. RESPONSIBILITY FOR CLAIMS. - - As between Initial Developer and the Contributors, each party is - responsible for claims and damages arising, directly or - indirectly, out of its utilization of rights under this License - and You agree to work with Initial Developer and Contributors to - distribute such responsibility on an equitable basis. Nothing - herein is intended or shall be deemed to constitute any admission - of liability. - - from Oracle and/or its affiliates http://oracle.com - cloud-email.jar http://kenai.com/projects/javamail - - licensed under the Common Public License - v 1.0 http://opensource.org/licenses/cpl1.0 (as follows) - - Copyright (c) IBM Corp 2006 - - Common Public License Version 1.0 (CPL) - - THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS COMMON PUBLIC - LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM - CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - - 1. DEFINITIONS - - "Contribution means: - - a) in the case of the initial Contributor, the initial code and documentation - distributed under this Agreement, and - - b) in the case of each subsequent Contributor: - - i) changes to the Program, and - - ii) additions to the Program; - - where such changes and/or additions to the Program originate from and are - distributed by that particular Contributor. A Contribution 'originates' from a - Contributor if it was added to the Program by such Contributor itself or anyone - acting on such Contributor's behalf. Contributions do not include additions to - the Program which: (i) are separate modules of software distributed in - conjunction with the Program under their own license agreement, and (ii) are not - derivative works of the Program. - - "Contributor means any person or entity that distributes the Program. - - "Licensed Patents mean patent claims licensable by a Contributor which are - "necessarily infringed by the use or sale of its Contribution alone or when - "combined with the Program. - - "Program means the Contributions distributed in accordance with this Agreement. - - "Recipient means anyone who receives the Program under this Agreement, including - "all Contributors. - - 2. GRANT OF RIGHTS - - a) Subject to the terms of this Agreement, each Contributor hereby grants - Recipient a non-exclusive, worldwide, royalty-free copyright license to - reproduce, prepare derivative works of, publicly display, publicly perform, - distribute and sublicense the Contribution of such Contributor, if any, and such - derivative works, in source code and object code form. - - b) Subject to the terms of this Agreement, each Contributor hereby grants - Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed - Patents to make, use, sell, offer to sell, import and otherwise transfer the - Contribution of such Contributor, if any, in source code and object code form. - This patent license shall apply to the combination of the Contribution and the - Program if, at the time the Contribution is added by the Contributor, such - addition of the Contribution causes such combination to be covered by the - Licensed Patents. The patent license shall not apply to any other combinations - which include the Contribution. No hardware per se is licensed hereunder. - - c) Recipient understands that although each Contributor grants the licenses to - its Contributions set forth herein, no assurances are provided by any - Contributor that the Program does not infringe the patent or other intellectual - property rights of any other entity. Each Contributor disclaims any liability to - Recipient for claims brought by any other entity based on infringement of - intellectual property rights or otherwise. As a condition to exercising the - rights and licenses granted hereunder, each Recipient hereby assumes sole - responsibility to secure any other intellectual property rights needed, if any. - For example, if a third party patent license is required to allow Recipient to - distribute the Program, it is Recipient's responsibility to acquire that license - before distributing the Program. - - d) Each Contributor represents that to its knowledge it has sufficient copyright - rights in its Contribution, if any, to grant the copyright license set forth in - this Agreement. - - 3. REQUIREMENTS - - A Contributor may choose to distribute the Program in object code form under its - own license agreement, provided that: - - a) it complies with the terms and conditions of this Agreement; and - - b) its license agreement: - - i) effectively disclaims on behalf of all Contributors all warranties and - conditions, express and implied, including warranties or conditions of title and - non-infringement, and implied warranties or conditions of merchantability and - fitness for a particular purpose; - - ii) effectively excludes on behalf of all Contributors all liability for - damages, including direct, indirect, special, incidental and consequential - damages, such as lost profits; - - iii) states that any provisions which differ from this Agreement are offered by - that Contributor alone and not by any other party; and - - iv) states that source code for the Program is available from such Contributor, - and informs licensees how to obtain it in a reasonable manner on or through a - medium customarily used for software exchange. - - When the Program is made available in source code form: - - a) it must be made available under this Agreement; and - - b) a copy of this Agreement must be included with each copy of the Program. - - Contributors may not remove or alter any copyright notices contained within the - Program. - - Each Contributor must identify itself as the originator of its Contribution, if - any, in a manner that reasonably allows subsequent Recipients to identify the - originator of the Contribution. - - 4. COMMERCIAL DISTRIBUTION - - Commercial distributors of software may accept certain responsibilities with - respect to end users, business partners and the like. While this license is - intended to facilitate the commercial use of the Program, the Contributor who - includes the Program in a commercial product offering should do so in a manner - which does not create potential liability for other Contributors. Therefore, if - a Contributor includes the Program in a commercial product offering, such - Contributor ("Commercial Contributor") hereby agrees to defend and indemnify - every other Contributor ("Indemnified Contributor") against any losses, damages - and costs (collectively "Losses") arising from claims, lawsuits and other legal - actions brought by a third party against the Indemnified Contributor to the - extent caused by the acts or omissions of such Commercial Contributor in - connection with its distribution of the Program in a commercial product - offering. The obligations in this section do not apply to any claims or Losses - relating to any actual or alleged intellectual property infringement. In order - to qualify, an Indemnified Contributor must: a) promptly notify the Commercial - Contributor in writing of such claim, and b) allow the Commercial Contributor to - control, and cooperate with the Commercial Contributor in, the defense and any - related settlement negotiations. The Indemnified Contributor may participate in - any such claim at its own expense. - - For example, a Contributor might include the Program in a commercial product - offering, Product X. That Contributor is then a Commercial Contributor. If that - Commercial Contributor then makes performance claims, or offers warranties - related to Product X, those performance claims and warranties are such - Commercial Contributor's responsibility alone. Under this section, the - Commercial Contributor would have to defend claims against the other - Contributors related to those performance claims and warranties, and if a court - requires any other Contributor to pay any damages as a result, the Commercial - Contributor must pay those damages. - - 5. NO WARRANTY - - EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR - IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, - NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each - Recipient is solely responsible for determining the appropriateness of using and - distributing the Program and assumes all risks associated with its exercise of - rights under this Agreement, including but not limited to the risks and costs of - program errors, compliance with applicable laws, damage to or loss of data, - programs or equipment, and unavailability or interruption of operations. - - 6. DISCLAIMER OF LIABILITY - - EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY - CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST - PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS - GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - - 7. GENERAL - - If any provision of this Agreement is invalid or unenforceable under applicable - law, it shall not affect the validity or enforceability of the remainder of the - terms of this Agreement, and without further action by the parties hereto, such - provision shall be reformed to the minimum extent necessary to make such - provision valid and enforceable. - - If Recipient institutes patent litigation against a Contributor with respect to - a patent applicable to software (including a cross-claim or counterclaim in a - lawsuit), then any patent licenses granted by that Contributor to such Recipient - under this Agreement shall terminate as of the date such litigation is filed. In - addition, if Recipient institutes patent litigation against any entity - (including a cross-claim or counterclaim in a lawsuit) alleging that the Program - itself (excluding combinations of the Program with other software or hardware) - infringes such Recipient's patent(s), then such Recipient's rights granted under - Section 2(b) shall terminate as of the date such litigation is filed. - - All Recipient's rights under this Agreement shall terminate if it fails to - comply with any of the material terms or conditions of this Agreement and does - not cure such failure in a reasonable period of time after becoming aware of - such noncompliance. If all Recipient's rights under this Agreement terminate, - Recipient agrees to cease use and distribution of the Program as soon as - reasonably practicable. However, Recipient's obligations under this Agreement - and any licenses granted by Recipient relating to the Program shall continue and - survive. - - Everyone is permitted to copy and distribute copies of this Agreement, but in - order to avoid inconsistency the Agreement is copyrighted and may only be - modified in the following manner. The Agreement Steward reserves the right to - publish new versions (including revisions) of this Agreement from time to time. - No one other than the Agreement Steward has the right to modify this Agreement. - IBM is the initial Agreement Steward. IBM may assign the responsibility to serve - as the Agreement Steward to a suitable separate entity. Each new version of the - Agreement will be given a distinguishing version number. The Program (including - Contributions) may always be distributed subject to the version of the Agreement - under which it was received. In addition, after a new version of the Agreement - is published, Contributor may elect to distribute the Program (including its - Contributions) under the new version. Except as expressly stated in Sections - 2(a) and 2(b) above, Recipient receives no rights or licenses to the - intellectual property of any Contributor under this Agreement, whether - expressly, by implication, estoppel or otherwise. All rights in the Program not - expressly granted under this Agreement are reserved. - - This Agreement is governed by the laws of the State of New York and the - intellectual property laws of the United States of America. No party to this - Agreement will bring a legal action under this Agreement more than one year - after the cause of action arose. Each party waives its rights to a jury trial in - any resulting litigation. - - from IBM Corp http://www.ibm.com/ - cloud-wsdl4j-1.6.2.jar http://sourceforge.net/projects/wsdl4j/ - cloud-wsdl4j.jar http://sourceforge.net/projects/wsdl4j/ - - licensed under the Common Public License - v 1.0 http://opensource.org/licenses/cpl1.0 (as follows) - - - Common Public License Version 1.0 (CPL) - - THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS COMMON PUBLIC - LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM - CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - - 1. DEFINITIONS - - "Contribution means: - - a) in the case of the initial Contributor, the initial code and documentation - distributed under this Agreement, and - - b) in the case of each subsequent Contributor: - - i) changes to the Program, and - - ii) additions to the Program; - - where such changes and/or additions to the Program originate from and are - distributed by that particular Contributor. A Contribution 'originates' from a - Contributor if it was added to the Program by such Contributor itself or anyone - acting on such Contributor's behalf. Contributions do not include additions to - the Program which: (i) are separate modules of software distributed in - conjunction with the Program under their own license agreement, and (ii) are not - derivative works of the Program. - - "Contributor means any person or entity that distributes the Program. - - "Licensed Patents mean patent claims licensable by a Contributor which are - "necessarily infringed by the use or sale of its Contribution alone or when - "combined with the Program. - - "Program means the Contributions distributed in accordance with this Agreement. - - "Recipient means anyone who receives the Program under this Agreement, including - "all Contributors. - - 2. GRANT OF RIGHTS - - a) Subject to the terms of this Agreement, each Contributor hereby grants - Recipient a non-exclusive, worldwide, royalty-free copyright license to - reproduce, prepare derivative works of, publicly display, publicly perform, - distribute and sublicense the Contribution of such Contributor, if any, and such - derivative works, in source code and object code form. - - b) Subject to the terms of this Agreement, each Contributor hereby grants - Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed - Patents to make, use, sell, offer to sell, import and otherwise transfer the - Contribution of such Contributor, if any, in source code and object code form. - This patent license shall apply to the combination of the Contribution and the - Program if, at the time the Contribution is added by the Contributor, such - addition of the Contribution causes such combination to be covered by the - Licensed Patents. The patent license shall not apply to any other combinations - which include the Contribution. No hardware per se is licensed hereunder. - - c) Recipient understands that although each Contributor grants the licenses to - its Contributions set forth herein, no assurances are provided by any - Contributor that the Program does not infringe the patent or other intellectual - property rights of any other entity. Each Contributor disclaims any liability to - Recipient for claims brought by any other entity based on infringement of - intellectual property rights or otherwise. As a condition to exercising the - rights and licenses granted hereunder, each Recipient hereby assumes sole - responsibility to secure any other intellectual property rights needed, if any. - For example, if a third party patent license is required to allow Recipient to - distribute the Program, it is Recipient's responsibility to acquire that license - before distributing the Program. - - d) Each Contributor represents that to its knowledge it has sufficient copyright - rights in its Contribution, if any, to grant the copyright license set forth in - this Agreement. - - 3. REQUIREMENTS - - A Contributor may choose to distribute the Program in object code form under its - own license agreement, provided that: - - a) it complies with the terms and conditions of this Agreement; and - - b) its license agreement: - - i) effectively disclaims on behalf of all Contributors all warranties and - conditions, express and implied, including warranties or conditions of title and - non-infringement, and implied warranties or conditions of merchantability and - fitness for a particular purpose; - - ii) effectively excludes on behalf of all Contributors all liability for - damages, including direct, indirect, special, incidental and consequential - damages, such as lost profits; - - iii) states that any provisions which differ from this Agreement are offered by - that Contributor alone and not by any other party; and - - iv) states that source code for the Program is available from such Contributor, - and informs licensees how to obtain it in a reasonable manner on or through a - medium customarily used for software exchange. - - When the Program is made available in source code form: - - a) it must be made available under this Agreement; and - - b) a copy of this Agreement must be included with each copy of the Program. - - Contributors may not remove or alter any copyright notices contained within the - Program. - - Each Contributor must identify itself as the originator of its Contribution, if - any, in a manner that reasonably allows subsequent Recipients to identify the - originator of the Contribution. - - 4. COMMERCIAL DISTRIBUTION - - Commercial distributors of software may accept certain responsibilities with - respect to end users, business partners and the like. While this license is - intended to facilitate the commercial use of the Program, the Contributor who - includes the Program in a commercial product offering should do so in a manner - which does not create potential liability for other Contributors. Therefore, if - a Contributor includes the Program in a commercial product offering, such - Contributor ("Commercial Contributor") hereby agrees to defend and indemnify - every other Contributor ("Indemnified Contributor") against any losses, damages - and costs (collectively "Losses") arising from claims, lawsuits and other legal - actions brought by a third party against the Indemnified Contributor to the - extent caused by the acts or omissions of such Commercial Contributor in - connection with its distribution of the Program in a commercial product - offering. The obligations in this section do not apply to any claims or Losses - relating to any actual or alleged intellectual property infringement. In order - to qualify, an Indemnified Contributor must: a) promptly notify the Commercial - Contributor in writing of such claim, and b) allow the Commercial Contributor to - control, and cooperate with the Commercial Contributor in, the defense and any - related settlement negotiations. The Indemnified Contributor may participate in - any such claim at its own expense. - - For example, a Contributor might include the Program in a commercial product - offering, Product X. That Contributor is then a Commercial Contributor. If that - Commercial Contributor then makes performance claims, or offers warranties - related to Product X, those performance claims and warranties are such - Commercial Contributor's responsibility alone. Under this section, the - Commercial Contributor would have to defend claims against the other - Contributors related to those performance claims and warranties, and if a court - requires any other Contributor to pay any damages as a result, the Commercial - Contributor must pay those damages. - - 5. NO WARRANTY - - EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR - IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, - NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each - Recipient is solely responsible for determining the appropriateness of using and - distributing the Program and assumes all risks associated with its exercise of - rights under this Agreement, including but not limited to the risks and costs of - program errors, compliance with applicable laws, damage to or loss of data, - programs or equipment, and unavailability or interruption of operations. - - 6. DISCLAIMER OF LIABILITY - - EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY - CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST - PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS - GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - - 7. GENERAL - - If any provision of this Agreement is invalid or unenforceable under applicable - law, it shall not affect the validity or enforceability of the remainder of the - terms of this Agreement, and without further action by the parties hereto, such - provision shall be reformed to the minimum extent necessary to make such - provision valid and enforceable. - - If Recipient institutes patent litigation against a Contributor with respect to - a patent applicable to software (including a cross-claim or counterclaim in a - lawsuit), then any patent licenses granted by that Contributor to such Recipient - under this Agreement shall terminate as of the date such litigation is filed. In - addition, if Recipient institutes patent litigation against any entity - (including a cross-claim or counterclaim in a lawsuit) alleging that the Program - itself (excluding combinations of the Program with other software or hardware) - infringes such Recipient's patent(s), then such Recipient's rights granted under - Section 2(b) shall terminate as of the date such litigation is filed. - - All Recipient's rights under this Agreement shall terminate if it fails to - comply with any of the material terms or conditions of this Agreement and does - not cure such failure in a reasonable period of time after becoming aware of - such noncompliance. If all Recipient's rights under this Agreement terminate, - Recipient agrees to cease use and distribution of the Program as soon as - reasonably practicable. However, Recipient's obligations under this Agreement - and any licenses granted by Recipient relating to the Program shall continue and - survive. - - Everyone is permitted to copy and distribute copies of this Agreement, but in - order to avoid inconsistency the Agreement is copyrighted and may only be - modified in the following manner. The Agreement Steward reserves the right to - publish new versions (including revisions) of this Agreement from time to time. - No one other than the Agreement Steward has the right to modify this Agreement. - IBM is the initial Agreement Steward. IBM may assign the responsibility to serve - as the Agreement Steward to a suitable separate entity. Each new version of the - Agreement will be given a distinguishing version number. The Program (including - Contributions) may always be distributed subject to the version of the Agreement - under which it was received. In addition, after a new version of the Agreement - is published, Contributor may elect to distribute the Program (including its - Contributions) under the new version. Except as expressly stated in Sections - 2(a) and 2(b) above, Recipient receives no rights or licenses to the - intellectual property of any Contributor under this Agreement, whether - expressly, by implication, estoppel or otherwise. All rights in the Program not - expressly granted under this Agreement are reserved. - - This Agreement is governed by the laws of the State of New York and the - intellectual property laws of the United States of America. No party to this - Agreement will bring a legal action under this Agreement more than one year - after the cause of action arose. Each party waives its rights to a jury trial in - any resulting litigation. - - from JUnit Project http://www.junit.org/ - cloud-junit.jar http://kentbeck.github.com/junit/ - - licensed under the Eclipse Distribution License Version 1.0 http://www.eclipse.org/org/documents/edl-v10.php (as follows) - - Copyright (c) 2012 The Eclipse Foundation. - - Eclipse Distribution License Version 1.0 - - Copyright (c) 2007, Eclipse Foundation, Inc. and its licensors. - - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. Redistributions in binary form must - reproduce the above copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided with the - distribution. Neither the name of the Eclipse Foundation, Inc. nor the names of - its contributors may be used to endorse or promote products derived from this - software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - from The Eclipse Foundation http://www.eclipse.org - cloud-javax.persistence-2.0.0.jar http://wiki.eclipse.org/EclipseLink/Release/2.0.0 - - licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - - Copyright (C) 2008 Tóth István - 2008-2012 Daniel Veillard - 2009-2011 Bryan Kearney - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - from The libvirt project http://libvirt.org/ - libvirt-java-0.4.9 - - licensed under the XStream BSD Style License https://fisheye.codehaus.org/browse/xstream/trunk/LICENSE.txt?hb=true (as follows) - - - (BSD Style License) - - Copyright (c) 2003-2006, Joe Walnes Copyright (c) 2006-2011, XStream Committers - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. Redistributions in binary form must - reproduce the above copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided with the - distribution. - - Neither the name of XStream nor the names of its contributors may be used to - endorse or promote products derived from this software without specific prior - written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - from XStream Committers http://xstream.codehaus.org/ - cloud-xstream-1.3.1.jar http://xstream.codehaus.org/repository.html - - -Within the ui/lib directory - placed in the public domain - by Eric Meyer http://meyerweb.com/eric/ - reset.css - - licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) - Copyright (c) 2006 Google Inc. - from Google Inc. http://google.com - excanvas.js http://code.google.com/p/explorercanvas/ - - licensed under the BSD (2-clause) http://www.opensource.org/licenses/BSD-2-Clause (as follows) - - Copyright (c) 2008 George McGinley Smith - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. Redistributions in binary form must - reproduce the above copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided with the - distribution. - - Neither the name of the author nor the names of contributors may be used to - endorse or promote products derived from this software without specific prior - written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - from George McGinley Smith - jquery.easing.js - - licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - - Copyright (c) 2011, John Resig - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - from John Resig - jquery.js - - licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - - Copyright (c) 2006 - 2011 Jörn Zaefferer - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - from Jorn Zaefferer - jquery.validate.js - - licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - - Copyright (c) 2010, Sebastian Tschan - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - from Sebastian Tschan https://blueimp.net - jquery.md5.js - - licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - - Copyright (c) 2006 Klaus Hartl (stilbuero.de) - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - from Klaus Hartl http://stilbuero.de - jquery.cookies.js - - -Within the ui/lib/flot directory - licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - - Released under the MIT license by IOLA, December 2007. - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - from IOLA http://www.iola.dk/ - jquery.flot.crosshair.js - jquery.flot.fillbetween.js - jquery.flot.image.js - jquery.flot.js - jquery.flot.navigate.js - jquery.flot.resize.js - jquery.flot.selection.js - jquery.flot.stack.js - jquery.flot.symbol.js - jquery.flot.threshold.js - - licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - - Created by Brian Medendorp, June 2009 - Updated November 2009 with contributions from: btburnett3, Anthony Aragues and Xavi Ivars - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - from Brian Medendorp - jquery.pie.js - - licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - from Ole Laursen - jquery.colorhelpers.js - - -Within the ui/lib/jquery-ui directory - licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - from jQuery UI Developers http://jqueryui.com/about - css/jquery-ui.css - index.html - js/jquery-ui.js - - -Within the ui/lib/qunit directory - licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - - Copyright (c) 2012 John Resig, Jörn Zaefferer - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - from Jorn Zaefferer - qunit.css http://docs.jquery.com/QUnit - qunit.js http://docs.jquery.com/QUnit - - -Within the utils/src/com/cloud/utils/db directory - licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) - Copyright (c) 2004 Clinton Begin - from Clinton Begin http://code.google.com/p/mybatis/ - ScriptRunner.java http://code.google.com/p/mybatis/ - diff --git a/NOTICE b/NOTICE index 18679580c47..e310584e78a 100644 --- a/NOTICE +++ b/NOTICE @@ -6,9 +6,84 @@ - This distribution contains third party resources requiring the following notices: + Source code distribution if this software contains third party resources requiring + the following notices: + For + jquery.md5.js + + + jQuery MD5 Plugin 1.2.1 + https://github.com/blueimp/jQuery-MD5 + + Copyright 2010, Sebastian Tschan + https://blueimp.net + + Licensed under the MIT license: + http://creativecommons.org/licenses/MIT/ + + Based on + A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + Digest Algorithm, as defined in RFC 1321. + Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + Distributed under the BSD License + See http://pajhome.org.uk/crypt/md5 for more info. + + + For + jquery.js + + + jQuery JavaScript Library v1.3.2 + http://jquery.com/ + + Copyright (c) 2009 John Resig + Dual licensed under the MIT and GPL licenses. + http://docs.jquery.com/License + + Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) + Revision: 6246 + + + For + jquery.js + + + jQuery JavaScript Library v1.6.1 + http://jquery.com/ + + Copyright 2011, John Resig + Dual licensed under the MIT or GPL Version 2 licenses. + http://jquery.org/license + + Includes Sizzle.js + http://sizzlejs.com/ + Copyright 2011, The Dojo Foundation + Released under the MIT, BSD, and GPL Licenses. + + Date: Thu May 12 15:04:36 2011 -0400 + + + For + jquery.colorhelpers.js + + + Plugin for jQuery for working with colors. + + Version 1.1. + + Inspiration from jQuery color animation plugin by John Resig. + + Released under the MIT license by Ole Laursen, October 2009. + + +******************************************************************************** + + Binary or packaged versions of this software (including versions built from source) + contains third party resources requiring the following notices: + For cloud-ejb-api-3.0.jar cloud-email.jar @@ -337,28 +412,6 @@ without prior written authorization of the copyright holder. - For - jquery.md5.js - - - jQuery MD5 Plugin 1.2.1 - https://github.com/blueimp/jQuery-MD5 - - Copyright 2010, Sebastian Tschan - https://blueimp.net - - Licensed under the MIT license: - http://creativecommons.org/licenses/MIT/ - - Based on - A JavaScript implementation of the RSA Data Security, Inc. MD5 Message - Digest Algorithm, as defined in RFC 1321. - Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 - Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - Distributed under the BSD License - See http://pajhome.org.uk/crypt/md5 for more info. - - For XmlSchema-1.4.3.jar @@ -430,21 +483,6 @@ THE SOFTWARE. - For - jquery.js - - - jQuery JavaScript Library v1.3.2 - http://jquery.com/ - - Copyright (c) 2009 John Resig - Dual licensed under the MIT and GPL licenses. - http://docs.jquery.com/License - - Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) - Revision: 6246 - - For axis2-1.5.1.jar axis2-adb-1.5.1.jar @@ -532,25 +570,6 @@ -------------------------------------------------------------------------------- - For - jquery.js - - - jQuery JavaScript Library v1.6.1 - http://jquery.com/ - - Copyright 2011, John Resig - Dual licensed under the MIT or GPL Version 2 licenses. - http://jquery.org/license - - Includes Sizzle.js - http://sizzlejs.com/ - Copyright 2011, The Dojo Foundation - Released under the MIT, BSD, and GPL Licenses. - - Date: Thu May 12 15:04:36 2011 -0400 - - For rampart-lib @@ -588,19 +607,6 @@ software copyright (c) 1999. - For - jquery.colorhelpers.js - - - Plugin for jQuery for working with colors. - - Version 1.1. - - Inspiration from jQuery color animation plugin by John Resig. - - Released under the MIT license by Ole Laursen, October 2009. - - For woden-api-1.0M8.jar woden-impl-dom-1.0M8.jar diff --git a/agent/src/com/cloud/agent/AgentShell.java b/agent/src/com/cloud/agent/AgentShell.java index 774f222dfb9..e3d1063e6b8 100644 --- a/agent/src/com/cloud/agent/AgentShell.java +++ b/agent/src/com/cloud/agent/AgentShell.java @@ -231,6 +231,7 @@ public class AgentShell implements IAgentShell { int response; response = client.executeMethod(method); if (response != HttpURLConnection.HTTP_OK) { + method.releaseConnection(); s_logger.warn("Retrieving from " + url + " gives response code: " + response); throw new CloudRuntimeException("Unable to download from " + url @@ -253,6 +254,7 @@ public class AgentShell implements IAgentShell { s_logger.warn("Exception while closing download stream from " + url + ", ", e); } + method.releaseConnection(); } private void loadProperties() throws ConfigurationException { diff --git a/api/src/com/cloud/agent/api/BackupSnapshotCommand.java b/api/src/com/cloud/agent/api/BackupSnapshotCommand.java index f6c02337e8d..52d9d389fe4 100644 --- a/api/src/com/cloud/agent/api/BackupSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/BackupSnapshotCommand.java @@ -17,6 +17,7 @@ package com.cloud.agent.api; import com.cloud.agent.api.LogLevel.Log4jLevel; +import com.cloud.agent.api.to.S3TO; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.agent.api.to.SwiftTO; import com.cloud.storage.StoragePool; @@ -32,6 +33,7 @@ public class BackupSnapshotCommand extends SnapshotCommand { private Long snapshotId; @LogLevel(Log4jLevel.Off) private SwiftTO swift; + private S3TO s3; StorageFilerTO pool; protected BackupSnapshotCommand() { @@ -48,8 +50,7 @@ public class BackupSnapshotCommand extends SnapshotCommand { * @param isFirstSnapshotOfRootVolume true if this is the first snapshot of a root volume. Set the parent of the backup to null. * @param isVolumeInactive True if the volume belongs to a VM that is not running or is detached. */ - public BackupSnapshotCommand(String primaryStoragePoolNameLabel, - String secondaryStoragePoolURL, + public BackupSnapshotCommand(String secondaryStoragePoolURL, Long dcId, Long accountId, Long volumeId, @@ -64,13 +65,12 @@ public class BackupSnapshotCommand extends SnapshotCommand { String vmName, int wait) { - super(primaryStoragePoolNameLabel, secondaryStoragePoolURL, snapshotUuid, snapshotName, dcId, accountId, volumeId); + super(pool, secondaryStoragePoolURL, snapshotUuid, snapshotName, dcId, accountId, volumeId); this.snapshotId = snapshotId; this.prevSnapshotUuid = prevSnapshotUuid; this.prevBackupUuid = prevBackupUuid; this.isVolumeInactive = isVolumeInactive; this.vmName = vmName; - this.pool = new StorageFilerTO(pool); setVolumePath(volumePath); setWait(wait); } @@ -88,7 +88,7 @@ public class BackupSnapshotCommand extends SnapshotCommand { } public String getVmName() { - return vmName; + return vmName; } public SwiftTO getSwift() { @@ -99,6 +99,14 @@ public class BackupSnapshotCommand extends SnapshotCommand { this.swift = swift; } + public S3TO getS3() { + return s3; + } + + public void setS3(S3TO s3) { + this.s3 = s3; + } + public Long getSnapshotId() { return snapshotId; } diff --git a/api/src/com/cloud/agent/api/CreatePrivateTemplateFromSnapshotCommand.java b/api/src/com/cloud/agent/api/CreatePrivateTemplateFromSnapshotCommand.java index 504198c28cf..9e2680e49e6 100644 --- a/api/src/com/cloud/agent/api/CreatePrivateTemplateFromSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/CreatePrivateTemplateFromSnapshotCommand.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.agent.api; +import com.cloud.storage.StoragePool; + /** * This currently assumes that both primary and secondary storage are mounted on the XenServer. */ @@ -40,7 +42,8 @@ public class CreatePrivateTemplateFromSnapshotCommand extends SnapshotCommand { * It may not be the UUID of the base copy of the snapshot, if no data was written since last snapshot. * @param origTemplateInstallPath The install path of the original template VHD on the secondary */ - public CreatePrivateTemplateFromSnapshotCommand(String primaryStoragePoolNameLabel, + + public CreatePrivateTemplateFromSnapshotCommand(StoragePool pool, String secondaryStoragePoolURL, Long dcId, Long accountId, @@ -52,7 +55,7 @@ public class CreatePrivateTemplateFromSnapshotCommand extends SnapshotCommand { String templateName, int wait) { - super(primaryStoragePoolNameLabel, secondaryStoragePoolURL, backedUpSnapshotUuid, backedUpSnapshotName, dcId, accountId, volumeId); + super(pool, secondaryStoragePoolURL, backedUpSnapshotUuid, backedUpSnapshotName, dcId, accountId, volumeId); this.origTemplateInstallPath = origTemplateInstallPath; this.newTemplateId = newTemplateId; this.templateName = templateName; diff --git a/api/src/com/cloud/agent/api/CreatePrivateTemplateFromVolumeCommand.java b/api/src/com/cloud/agent/api/CreatePrivateTemplateFromVolumeCommand.java index b589ed53077..4e0bf32f1b1 100644 --- a/api/src/com/cloud/agent/api/CreatePrivateTemplateFromVolumeCommand.java +++ b/api/src/com/cloud/agent/api/CreatePrivateTemplateFromVolumeCommand.java @@ -16,6 +16,9 @@ // under the License. package com.cloud.agent.api; +import com.cloud.agent.api.to.StorageFilerTO; +import com.cloud.storage.StoragePool; + public class CreatePrivateTemplateFromVolumeCommand extends SnapshotCommand { private String _vmName; private String _volumePath; @@ -23,13 +26,14 @@ public class CreatePrivateTemplateFromVolumeCommand extends SnapshotCommand { private String _uniqueName; private long _templateId; private long _accountId; + StorageFilerTO _primaryPool; // For XenServer private String _secondaryStorageUrl; public CreatePrivateTemplateFromVolumeCommand() { } - public CreatePrivateTemplateFromVolumeCommand(String StoragePoolUUID, String secondaryStorageUrl, long templateId, long accountId, String userSpecifiedName, String uniqueName, String volumePath, String vmName, int wait) { + public CreatePrivateTemplateFromVolumeCommand(StoragePool pool, String secondaryStorageUrl, long templateId, long accountId, String userSpecifiedName, String uniqueName, String volumePath, String vmName, int wait) { _secondaryStorageUrl = secondaryStorageUrl; _templateId = templateId; _accountId = accountId; @@ -37,7 +41,8 @@ public class CreatePrivateTemplateFromVolumeCommand extends SnapshotCommand { _uniqueName = uniqueName; _volumePath = volumePath; _vmName = vmName; - primaryStoragePoolNameLabel = StoragePoolUUID; + primaryStoragePoolNameLabel = pool.getUuid(); + _primaryPool = new StorageFilerTO(pool); setWait(wait); } @@ -46,6 +51,10 @@ public class CreatePrivateTemplateFromVolumeCommand extends SnapshotCommand { return false; } + public StorageFilerTO getPool() { + return _primaryPool; + } + public String getSecondaryStorageUrl() { return _secondaryStorageUrl; } diff --git a/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotCommand.java b/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotCommand.java index 955c81abc97..a19d34436f7 100644 --- a/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotCommand.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.agent.api; +import com.cloud.storage.StoragePool; + /** * This currently assumes that both primary and secondary storage are mounted on the XenServer. */ @@ -39,7 +41,8 @@ public class CreateVolumeFromSnapshotCommand extends SnapshotCommand { * It may not be the UUID of the base copy of the snapshot, if no data was written since last snapshot. * @param templatePath The install path of the template VHD on the secondary, if this a root volume */ - public CreateVolumeFromSnapshotCommand(String primaryStoragePoolNameLabel, + + public CreateVolumeFromSnapshotCommand(StoragePool pool, String secondaryStoragePoolURL, Long dcId, Long accountId, @@ -48,7 +51,7 @@ public class CreateVolumeFromSnapshotCommand extends SnapshotCommand { String backedUpSnapshotName, int wait) { - super(primaryStoragePoolNameLabel, secondaryStoragePoolURL, backedUpSnapshotUuid, backedUpSnapshotName, dcId, accountId, volumeId); + super(pool, secondaryStoragePoolURL, backedUpSnapshotUuid, backedUpSnapshotName, dcId, accountId, volumeId); setWait(wait); } } diff --git a/api/src/com/cloud/agent/api/DeleteSnapshotBackupCommand.java b/api/src/com/cloud/agent/api/DeleteSnapshotBackupCommand.java index 6ea19458212..6114148954f 100644 --- a/api/src/com/cloud/agent/api/DeleteSnapshotBackupCommand.java +++ b/api/src/com/cloud/agent/api/DeleteSnapshotBackupCommand.java @@ -17,6 +17,7 @@ package com.cloud.agent.api; import com.cloud.agent.api.LogLevel.Log4jLevel; +import com.cloud.agent.api.to.S3TO; import com.cloud.agent.api.to.SwiftTO; /** @@ -26,6 +27,7 @@ import com.cloud.agent.api.to.SwiftTO; public class DeleteSnapshotBackupCommand extends SnapshotCommand { @LogLevel(Log4jLevel.Off) private SwiftTO swift; + private S3TO s3; private Boolean all; public SwiftTO getSwift() { @@ -44,6 +46,10 @@ public class DeleteSnapshotBackupCommand extends SnapshotCommand { this.swift = swift; } + public S3TO getS3() { + return s3; + } + protected DeleteSnapshotBackupCommand() { } @@ -73,6 +79,7 @@ public class DeleteSnapshotBackupCommand extends SnapshotCommand { * @param childUUID The child VHD file of the backup whose parent is reset to its grandparent. */ public DeleteSnapshotBackupCommand(SwiftTO swift, + S3TO s3, String secondaryStoragePoolURL, Long dcId, Long accountId, @@ -81,6 +88,7 @@ public class DeleteSnapshotBackupCommand extends SnapshotCommand { { super(null, secondaryStoragePoolURL, backupUUID, null, dcId, accountId, volumeId); setSwift(swift); + this.s3 = s3; setAll(all); } } diff --git a/api/src/com/cloud/agent/api/DeleteTemplateFromS3Command.java b/api/src/com/cloud/agent/api/DeleteTemplateFromS3Command.java new file mode 100644 index 00000000000..278669b2c97 --- /dev/null +++ b/api/src/com/cloud/agent/api/DeleteTemplateFromS3Command.java @@ -0,0 +1,106 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.agent.api; + +import com.cloud.agent.api.to.S3TO; + +public class DeleteTemplateFromS3Command extends Command { + + private S3TO s3; + private Long templateId; + private Long accountId; + + protected DeleteTemplateFromS3Command() { + super(); + } + + public DeleteTemplateFromS3Command(final S3TO s3, final Long accountId, + final Long templateId) { + + super(); + + this.s3 = s3; + this.accountId = accountId; + this.templateId = templateId; + + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + + ((accountId == null) ? 0 : accountId.hashCode()); + result = prime * result + ((s3 == null) ? 0 : s3.hashCode()); + result = prime * result + + ((templateId == null) ? 0 : templateId.hashCode()); + return result; + } + + @Override + public boolean equals(Object thatObject) { + + if (this == thatObject) { + return true; + } + + if (thatObject == null) { + return false; + } + + if (getClass() != thatObject.getClass()) { + return false; + } + + final DeleteTemplateFromS3Command thatCommand = (DeleteTemplateFromS3Command) thatObject; + + if (!(accountId == thatCommand.accountId) + || (this.accountId != null && this.accountId + .equals(thatCommand.accountId))) { + return false; + } + + if (!(templateId == thatCommand.templateId) + || (this.templateId != null && this.templateId + .equals(thatCommand.templateId))) { + return false; + } + + return true; + + } + + public S3TO getS3() { + return s3; + } + + public Long getTemplateId() { + return templateId; + } + + public Long getAccountId() { + return accountId; + } + + @Override + public boolean executeInSequence() { + return true; + } + +} diff --git a/api/src/com/cloud/agent/api/DownloadSnapshotFromS3Command.java b/api/src/com/cloud/agent/api/DownloadSnapshotFromS3Command.java new file mode 100644 index 00000000000..edf683a58be --- /dev/null +++ b/api/src/com/cloud/agent/api/DownloadSnapshotFromS3Command.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.agent.api; + +import com.cloud.agent.api.to.S3TO; + +public class DownloadSnapshotFromS3Command extends SnapshotCommand { + + private S3TO s3; + private String parent; + + protected DownloadSnapshotFromS3Command() { + super(); + } + + public DownloadSnapshotFromS3Command(S3TO s3, String parent, + String secondaryStorageUrl, Long dcId, Long accountId, + Long volumeId, String backupUuid, int wait) { + + super(null, secondaryStorageUrl, backupUuid, "", dcId, accountId, + volumeId); + + this.s3 = s3; + this.parent = parent; + setWait(wait); + + } + + public S3TO getS3() { + return s3; + } + + public void setS3(S3TO s3) { + this.s3 = s3; + } + + public String getParent() { + return parent; + } + + public void setParent(String parent) { + this.parent = parent; + } + +} diff --git a/api/src/com/cloud/agent/api/DownloadTemplateFromS3ToSecondaryStorageCommand.java b/api/src/com/cloud/agent/api/DownloadTemplateFromS3ToSecondaryStorageCommand.java new file mode 100644 index 00000000000..af61228c020 --- /dev/null +++ b/api/src/com/cloud/agent/api/DownloadTemplateFromS3ToSecondaryStorageCommand.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.agent.api; + +import com.cloud.agent.api.to.S3TO; + +public final class DownloadTemplateFromS3ToSecondaryStorageCommand extends Command { + + private final S3TO s3; + private final Long accountId; + private final Long templateId; + private final String storagePath; + + public DownloadTemplateFromS3ToSecondaryStorageCommand(final S3TO s3, + final Long accountId, final Long templateId, + final String storagePath, final int wait) { + + super(); + + this.s3 = s3; + this.accountId = accountId; + this.templateId = templateId; + this.storagePath = storagePath; + + setWait(wait); + + } + + public S3TO getS3() { + return this.s3; + } + + public Long getAccountId() { + return this.accountId; + } + + public Long getTemplateId() { + return this.templateId; + } + + public String getStoragePath() { + return this.storagePath; + } + + @Override + public boolean executeInSequence() { + return true; + } + +} diff --git a/api/src/com/cloud/agent/api/SnapshotCommand.java b/api/src/com/cloud/agent/api/SnapshotCommand.java index dceb461e3b6..d8abeb62371 100644 --- a/api/src/com/cloud/agent/api/SnapshotCommand.java +++ b/api/src/com/cloud/agent/api/SnapshotCommand.java @@ -16,12 +16,16 @@ // under the License. package com.cloud.agent.api; +import com.cloud.agent.api.to.StorageFilerTO; +import com.cloud.storage.StoragePool; + /** * This currently assumes that both primary and secondary storage are mounted on * the XenServer. */ public class SnapshotCommand extends Command { protected String primaryStoragePoolNameLabel; + StorageFilerTO primaryPool; private String snapshotUuid; private String snapshotName; private String secondaryStorageUrl; @@ -46,10 +50,11 @@ public class SnapshotCommand extends Command { * is the value of that field If you have better ideas on how to * get it, you are welcome. */ - public SnapshotCommand(String primaryStoragePoolNameLabel, + public SnapshotCommand(StoragePool pool, String secondaryStorageUrl, String snapshotUuid, String snapshotName, Long dcId, Long accountId, Long volumeId) { - this.primaryStoragePoolNameLabel = primaryStoragePoolNameLabel; + this.primaryStoragePoolNameLabel = pool.getUuid(); + this.primaryPool = new StorageFilerTO(pool); this.snapshotUuid = snapshotUuid; this.secondaryStorageUrl = secondaryStorageUrl; this.dcId = dcId; @@ -65,6 +70,13 @@ public class SnapshotCommand extends Command { return primaryStoragePoolNameLabel; } + /** + * @return the primaryPool + */ + public StorageFilerTO getPool() { + return primaryPool; + } + /** * @return the snapshotUuid */ diff --git a/api/src/com/cloud/agent/api/UpgradeSnapshotCommand.java b/api/src/com/cloud/agent/api/UpgradeSnapshotCommand.java index 1b3ff745985..f00f4902970 100644 --- a/api/src/com/cloud/agent/api/UpgradeSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/UpgradeSnapshotCommand.java @@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. package com.cloud.agent.api; +import com.cloud.storage.StoragePool; + public class UpgradeSnapshotCommand extends SnapshotCommand { private String version; private Long templateId; @@ -30,7 +32,7 @@ public class UpgradeSnapshotCommand extends SnapshotCommand { * @param snapshotUuid The UUID of the snapshot which is going to be upgraded * @param _version version for this snapshot */ - public UpgradeSnapshotCommand(String primaryStoragePoolNameLabel, + public UpgradeSnapshotCommand(StoragePool pool, String secondaryStoragePoolURL, Long dcId, Long accountId, @@ -42,7 +44,7 @@ public class UpgradeSnapshotCommand extends SnapshotCommand { String snapshotName, String version) { - super(primaryStoragePoolNameLabel, secondaryStoragePoolURL, snapshotUuid, snapshotName, dcId, accountId, volumeId); + super(pool, secondaryStoragePoolURL, snapshotUuid, snapshotName, dcId, accountId, volumeId); this.version = version; this.templateId = templateId; this.tmpltAccountId = tmpltAccountId; diff --git a/api/src/com/cloud/agent/api/UploadTemplateToS3FromSecondaryStorageCommand.java b/api/src/com/cloud/agent/api/UploadTemplateToS3FromSecondaryStorageCommand.java new file mode 100644 index 00000000000..1807cd56315 --- /dev/null +++ b/api/src/com/cloud/agent/api/UploadTemplateToS3FromSecondaryStorageCommand.java @@ -0,0 +1,121 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.agent.api; + +import com.cloud.agent.api.to.S3TO; + +public class UploadTemplateToS3FromSecondaryStorageCommand extends Command { + + private final S3TO s3; + private final String storagePath; + private final Long dataCenterId; + private final Long accountId; + private final Long templateId; + + public UploadTemplateToS3FromSecondaryStorageCommand(final S3TO s3, + final String storagePath, final Long dataCenterId, final Long accountId, + final Long templateId) { + + super(); + + this.s3 = s3; + this.storagePath = storagePath; + this.dataCenterId = dataCenterId; + this.accountId = accountId; + this.templateId = templateId; + + } + + @Override + public boolean executeInSequence() { + return false; + } + + @Override + public boolean equals(final Object thatObject) { + + if (this == thatObject) { + return true; + } + + if (thatObject == null || getClass() != thatObject.getClass()) { + return false; + } + + final UploadTemplateToS3FromSecondaryStorageCommand thatCommand = + (UploadTemplateToS3FromSecondaryStorageCommand) thatObject; + + if (this.accountId != null ? !this.accountId.equals(thatCommand + .accountId) : thatCommand.accountId != null) { + return false; + } + + if (this.dataCenterId != null ? !this.dataCenterId.equals(thatCommand + .dataCenterId) : thatCommand.dataCenterId != null) { + return false; + } + + if (this.s3 != null ? !this.s3.equals(thatCommand.s3) : thatCommand.s3 != null) { + return false; + } + + if (this.storagePath != null ? !this.storagePath.equals(thatCommand + .storagePath) : thatCommand.storagePath != null) { + return false; + } + + if (this.templateId != null ? !this.templateId.equals(thatCommand.templateId) : + thatCommand.templateId != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = this.s3 != null ? this.s3.hashCode() : 0; + result = 31 * result + (this.storagePath != null ? this.storagePath.hashCode() : 0); + result = 31 * result + (this.dataCenterId != null ? this.dataCenterId.hashCode() : 0); + result = 31 * result + (this.accountId != null ? this.accountId.hashCode() : 0); + result = 31 * result + (this.templateId != null ? this.templateId.hashCode() : 0); + return result; + } + + public S3TO getS3() { + return this.s3; + } + + public String getStoragePath() { + return this.storagePath; + } + + public Long getDataCenterId() { + return this.dataCenterId; + } + + public Long getAccountId() { + return this.accountId; + } + + public Long getTemplateId() { + return this.templateId; + } + +} diff --git a/api/src/com/cloud/agent/api/downloadSnapshotFromSwiftCommand.java b/api/src/com/cloud/agent/api/downloadSnapshotFromSwiftCommand.java index 0937dada16e..a2ae611d316 100644 --- a/api/src/com/cloud/agent/api/downloadSnapshotFromSwiftCommand.java +++ b/api/src/com/cloud/agent/api/downloadSnapshotFromSwiftCommand.java @@ -34,7 +34,7 @@ public class downloadSnapshotFromSwiftCommand extends SnapshotCommand { public downloadSnapshotFromSwiftCommand(SwiftTO swift, String secondaryStorageUrl, Long dcId, Long accountId, Long volumeId, String parent, String BackupUuid, int wait) { - super("", secondaryStorageUrl, BackupUuid, "", dcId, accountId, volumeId); + super(null, secondaryStorageUrl, BackupUuid, "", dcId, accountId, volumeId); setParent(parent); setSwift(swift); setWait(wait); diff --git a/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java b/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java index 565b50dd27a..b450041597f 100644 --- a/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java +++ b/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java @@ -17,7 +17,8 @@ package com.cloud.agent.api.storage; import com.cloud.storage.Storage.ImageFormat; - +import com.cloud.agent.api.to.StorageFilerTO; +import com.cloud.storage.StoragePool; /** * @@ -27,16 +28,19 @@ public class PrimaryStorageDownloadCommand extends AbstractDownloadCommand { String poolUuid; long poolId; + StorageFilerTO primaryPool; + String secondaryStorageUrl; String primaryStorageUrl; protected PrimaryStorageDownloadCommand() { } - public PrimaryStorageDownloadCommand(String name, String url, ImageFormat format, long accountId, long poolId, String poolUuid, int wait) { + public PrimaryStorageDownloadCommand(String name, String url, ImageFormat format, long accountId, StoragePool pool, int wait) { super(name, url, format, accountId); - this.poolId = poolId; - this.poolUuid = poolUuid; + this.poolId = pool.getId(); + this.poolUuid = pool.getUuid(); + this.primaryPool = new StorageFilerTO(pool); setWait(wait); } @@ -48,6 +52,10 @@ public class PrimaryStorageDownloadCommand extends AbstractDownloadCommand { return poolId; } + public StorageFilerTO getPool() { + return primaryPool; + } + public void setLocalPath(String path) { this.localPath = path; } diff --git a/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java b/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java index 9ef8d0a6fcb..c23dce8ea86 100644 --- a/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java +++ b/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java @@ -39,8 +39,8 @@ public class PortForwardingRuleTO extends FirewallRuleTO { this.dstPortRange = new int[] { rule.getDestinationPortStart(), rule.getDestinationPortEnd() }; } - protected PortForwardingRuleTO(long id, String srcIp, int srcPortStart, int srcPortEnd, String dstIp, int dstPortStart, int dstPortEnd, String protocol, boolean revoked, boolean brandNew) { - super(id, srcIp,null, protocol, srcPortStart, srcPortEnd, revoked, brandNew, FirewallRule.Purpose.PortForwarding, null,0,0); + public PortForwardingRuleTO(long id, String srcIp, int srcPortStart, int srcPortEnd, String dstIp, int dstPortStart, int dstPortEnd, String protocol, boolean revoked, boolean alreadyAdded) { + super(id, null, srcIp, protocol, srcPortStart, srcPortEnd, revoked, alreadyAdded, FirewallRule.Purpose.PortForwarding, null,0,0); this.dstIp = dstIp; this.dstPortRange = new int[] { dstPortStart, dstPortEnd }; } diff --git a/api/src/com/cloud/agent/api/to/S3TO.java b/api/src/com/cloud/agent/api/to/S3TO.java new file mode 100644 index 00000000000..879df229c31 --- /dev/null +++ b/api/src/com/cloud/agent/api/to/S3TO.java @@ -0,0 +1,252 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.agent.api.to; + +import com.cloud.utils.S3Utils; + +import java.util.Date; + +public final class S3TO implements S3Utils.ClientOptions { + + private Long id; + private String uuid; + private String accessKey; + private String secretKey; + private String endPoint; + private String bucketName; + private Boolean httpsFlag; + private Integer connectionTimeout; + private Integer maxErrorRetry; + private Integer socketTimeout; + private Date created; + + public S3TO() { + + super(); + + } + + public S3TO(final Long id, final String uuid, final String accessKey, + final String secretKey, final String endPoint, + final String bucketName, final Boolean httpsFlag, + final Integer connectionTimeout, final Integer maxErrorRetry, + final Integer socketTimeout, final Date created) { + + super(); + + this.id = id; + this.uuid = uuid; + this.accessKey = accessKey; + this.secretKey = secretKey; + this.endPoint = endPoint; + this.bucketName = bucketName; + this.httpsFlag = httpsFlag; + this.connectionTimeout = connectionTimeout; + this.maxErrorRetry = maxErrorRetry; + this.socketTimeout = socketTimeout; + this.created = created; + + } + + @Override + public boolean equals(final Object thatObject) { + + if (this == thatObject) + return true; + if (thatObject == null || getClass() != thatObject.getClass()) + return false; + + final S3TO thatS3TO = (S3TO) thatObject; + + if (httpsFlag != null ? !httpsFlag.equals(thatS3TO.httpsFlag) + : thatS3TO.httpsFlag != null) { + return false; + } + + if (accessKey != null ? !accessKey.equals(thatS3TO.accessKey) + : thatS3TO.accessKey != null) { + return false; + } + + if (connectionTimeout != null ? !connectionTimeout + .equals(thatS3TO.connectionTimeout) + : thatS3TO.connectionTimeout != null) { + return false; + } + + if (endPoint != null ? !endPoint.equals(thatS3TO.endPoint) + : thatS3TO.endPoint != null) { + return false; + } + + if (id != null ? !id.equals(thatS3TO.id) : thatS3TO.id != null) { + return false; + } + + if (uuid != null ? !uuid.equals(thatS3TO.uuid) : thatS3TO.uuid != null) { + return false; + } + + if (maxErrorRetry != null ? !maxErrorRetry + .equals(thatS3TO.maxErrorRetry) + : thatS3TO.maxErrorRetry != null) { + return false; + } + + if (secretKey != null ? !secretKey.equals(thatS3TO.secretKey) + : thatS3TO.secretKey != null) { + return false; + } + + if (socketTimeout != null ? !socketTimeout + .equals(thatS3TO.socketTimeout) + : thatS3TO.socketTimeout != null) { + return false; + } + + if (bucketName != null ? !bucketName.equals(thatS3TO.bucketName) + : thatS3TO.bucketName != null) { + return false; + } + + if (created != null ? !created.equals(thatS3TO.created) + : thatS3TO.created != null) { + return false; + } + + return true; + + } + + @Override + public int hashCode() { + + int result = id != null ? id.hashCode() : 0; + + result = 31 * result + (accessKey != null ? accessKey.hashCode() : 0); + result = 31 * result + (secretKey != null ? secretKey.hashCode() : 0); + result = 31 * result + (endPoint != null ? endPoint.hashCode() : 0); + result = 31 * result + (bucketName != null ? bucketName.hashCode() : 0); + result = 31 * result + (httpsFlag ? 1 : 0); + result = 31 + * result + + (connectionTimeout != null ? connectionTimeout.hashCode() : 0); + result = 31 * result + + (maxErrorRetry != null ? maxErrorRetry.hashCode() : 0); + result = 31 * result + + (socketTimeout != null ? socketTimeout.hashCode() : 0); + + return result; + + } + + public Long getId() { + return this.id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getUuid() { + return this.uuid; + } + + public void setUuid(final String uuid) { + this.uuid = uuid; + } + + @Override + public String getAccessKey() { + return this.accessKey; + } + + public void setAccessKey(final String accessKey) { + this.accessKey = accessKey; + } + + @Override + public String getSecretKey() { + return this.secretKey; + } + + public void setSecretKey(final String secretKey) { + this.secretKey = secretKey; + } + + @Override + public String getEndPoint() { + return this.endPoint; + } + + public void setEndPoint(final String endPoint) { + this.endPoint = endPoint; + } + + public String getBucketName() { + return this.bucketName; + } + + public void setBucketName(final String bucketName) { + this.bucketName = bucketName; + } + + @Override + public Boolean isHttps() { + return this.httpsFlag; + } + + public void setHttps(final Boolean httpsFlag) { + this.httpsFlag = httpsFlag; + } + + @Override + public Integer getConnectionTimeout() { + return connectionTimeout; + } + + public void setConnectionTimeout(final Integer connectionTimeout) { + this.connectionTimeout = connectionTimeout; + } + + @Override + public Integer getMaxErrorRetry() { + return maxErrorRetry; + } + + public void setMaxErrorRetry(final Integer maxErrorRetry) { + this.maxErrorRetry = maxErrorRetry; + } + + @Override + public Integer getSocketTimeout() { + return socketTimeout; + } + + public void setSocketTimeout(final Integer socketTimeout) { + this.socketTimeout = socketTimeout; + } + + public Date getCreated() { + return this.created; + } + + public void setCreated(final Date created) { + this.created = created; + } + +} diff --git a/api/src/com/cloud/api/commands/AddS3Cmd.java b/api/src/com/cloud/api/commands/AddS3Cmd.java new file mode 100644 index 00000000000..8ef6c98e51b --- /dev/null +++ b/api/src/com/cloud/api/commands/AddS3Cmd.java @@ -0,0 +1,218 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.api.commands; + +import static org.apache.cloudstack.api.ApiConstants.S3_ACCESS_KEY; +import static org.apache.cloudstack.api.ApiConstants.S3_CONNECTION_TIMEOUT; +import static org.apache.cloudstack.api.ApiConstants.S3_END_POINT; +import static org.apache.cloudstack.api.ApiConstants.S3_HTTPS_FLAG; +import static org.apache.cloudstack.api.ApiConstants.S3_MAX_ERROR_RETRY; +import static org.apache.cloudstack.api.ApiConstants.S3_SECRET_KEY; +import static org.apache.cloudstack.api.ApiConstants.S3_SOCKET_TIMEOUT; +import static org.apache.cloudstack.api.ApiConstants.S3_BUCKET_NAME; +import static org.apache.cloudstack.api.BaseCmd.CommandType.INTEGER; +import static org.apache.cloudstack.api.BaseCmd.CommandType.STRING; +import static org.apache.cloudstack.api.BaseCmd.CommandType.BOOLEAN; +import static com.cloud.user.Account.ACCOUNT_ID_SYSTEM; + +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Implementation; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import com.cloud.api.response.S3Response; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.DiscoveryException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.storage.S3; + +@Implementation(description = "Adds S3", responseObject = S3Response.class, since = "4.0.0") +public final class AddS3Cmd extends BaseCmd { + + private static String COMMAND_NAME = "adds3response"; + + @Parameter(name = S3_ACCESS_KEY, type = STRING, required = true, + description = "S3 access key") + private String accessKey; + + @Parameter(name = S3_SECRET_KEY, type = STRING, required = true, + description = "S3 secret key") + private String secretKey; + + @Parameter(name = S3_END_POINT, type = STRING, required = false, + description = "S3 host name") + private String endPoint = null; + + @Parameter(name = S3_BUCKET_NAME, type = STRING, required = true, + description = "name of the template storage bucket") + private String bucketName; + + @Parameter(name = S3_HTTPS_FLAG, type = BOOLEAN, required = false, + description = "connect to the S3 endpoint via HTTPS?") + private Boolean httpsFlag = null; + + @Parameter(name = S3_CONNECTION_TIMEOUT, type = INTEGER, required = false, + description = "connection timeout (milliseconds)") + private Integer connectionTimeout = null; + + @Parameter(name = S3_MAX_ERROR_RETRY, type = INTEGER, required = false, + description = "maximum number of times to retry on error") + private Integer maxErrorRetry = null; + + @Parameter(name = S3_SOCKET_TIMEOUT, type = INTEGER, required = false, + description = "socket timeout (milliseconds)") + private Integer socketTimeout = null; + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, + ServerApiException, ConcurrentOperationException, ResourceAllocationException, + NetworkRuleConflictException { + + final S3 result; + + try { + + result = _resourceService.discoverS3(this); + + if (result == null) { + throw new ServerApiException(INTERNAL_ERROR, "Failed to add S3."); + } + + } catch (DiscoveryException e) { + + throw new ServerApiException(INTERNAL_ERROR, "Failed to add S3 due to " + e.getMessage()); + + } + + final S3Response response = _responseGenerator.createS3Response(result); + response.setResponseName(this.getCommandName()); + this.setResponseObject(response); + + } + + @Override + public boolean equals(final Object thatObject) { + + if (this == thatObject) { + return true; + } + + if (thatObject == null || this.getClass() != thatObject.getClass()) { + return false; + } + + final AddS3Cmd thatAddS3Cmd = (AddS3Cmd) thatObject; + + if (this.httpsFlag != null ? !this.httpsFlag.equals(thatAddS3Cmd.httpsFlag) : thatAddS3Cmd.httpsFlag != null) { + return false; + } + + if (this.accessKey != null ? !this.accessKey.equals(thatAddS3Cmd.accessKey) : thatAddS3Cmd.accessKey != null) { + return false; + } + + if (this.connectionTimeout != null ? !this.connectionTimeout.equals(thatAddS3Cmd.connectionTimeout) : thatAddS3Cmd.connectionTimeout != null) { + return false; + } + + if (this.endPoint != null ? !this.endPoint.equals(thatAddS3Cmd.endPoint) : thatAddS3Cmd.endPoint != null) { + return false; + } + + if (this.maxErrorRetry != null ? !this.maxErrorRetry.equals(thatAddS3Cmd.maxErrorRetry) : thatAddS3Cmd.maxErrorRetry != null) { + return false; + } + + if (this.secretKey != null ? !this.secretKey.equals(thatAddS3Cmd.secretKey) : thatAddS3Cmd.secretKey != null) { + return false; + } + + if (this.socketTimeout != null ? !this.socketTimeout.equals(thatAddS3Cmd.socketTimeout) : thatAddS3Cmd.socketTimeout != null) { + return false; + } + + if (this.bucketName != null ? !this.bucketName.equals(thatAddS3Cmd.bucketName) : thatAddS3Cmd.bucketName != null) { + return false; + } + + return true; + + } + + @Override + public int hashCode() { + + int result = this.accessKey != null ? this.accessKey.hashCode() : 0; + result = 31 * result + (this.secretKey != null ? this.secretKey.hashCode() : 0); + result = 31 * result + (this.endPoint != null ? this.endPoint.hashCode() : 0); + result = 31 * result + (this.bucketName != null ? this.bucketName.hashCode() : 0); + result = 31 * result + (this.httpsFlag != null && this.httpsFlag == true ? 1 : 0); + result = 31 * result + (this.connectionTimeout != null ? this.connectionTimeout.hashCode() : 0); + result = 31 * result + (this.maxErrorRetry != null ? this.maxErrorRetry.hashCode() : 0); + result = 31 * result + (this.socketTimeout != null ? this.socketTimeout.hashCode() : 0); + + return result; + + } + + @Override + public String getCommandName() { + return COMMAND_NAME; + } + + @Override + public long getEntityOwnerId() { + return ACCOUNT_ID_SYSTEM; + } + + public String getAccessKey() { + return this.accessKey; + } + + public String getSecretKey() { + return this.secretKey; + } + + public String getEndPoint() { + return this.endPoint; + } + + public String getBucketName() { + return this.bucketName; + } + + public Boolean getHttpsFlag() { + return this.httpsFlag; + } + + public Integer getConnectionTimeout() { + return this.connectionTimeout; + } + + public Integer getMaxErrorRetry() { + return this.maxErrorRetry; + } + + public Integer getSocketTimeout() { + return this.socketTimeout; + } + +} diff --git a/api/src/com/cloud/api/commands/ListS3sCmd.java b/api/src/com/cloud/api/commands/ListS3sCmd.java new file mode 100644 index 00000000000..86c8c539d9a --- /dev/null +++ b/api/src/com/cloud/api/commands/ListS3sCmd.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.api.commands; + +import static org.apache.cloudstack.api.ApiConstants.ID; +import static org.apache.cloudstack.api.BaseCmd.CommandType.LONG; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Implementation; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import com.cloud.api.response.S3Response; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.storage.S3; + +@Implementation(description = "Lists S3s", responseObject = S3Response.class, since = "4.0.0") +public final class ListS3sCmd extends BaseListCmd { + + private static final String COMMAND_NAME = "lists3sresponse"; + + @Parameter(name = ID, type = LONG, required = true, description = "The ID of the S3") + private Long id; + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, + ServerApiException, ConcurrentOperationException, ResourceAllocationException, + NetworkRuleConflictException { + + final List result = _resourceService.listS3s(this); + final ListResponse response = new ListResponse(); + final List s3Responses = new ArrayList(); + + if (result != null) { + + for (S3 s3 : result) { + + S3Response s3Response = _responseGenerator.createS3Response(s3); + s3Response.setResponseName(this.getCommandName()); + s3Response.setObjectName("s3"); + s3Responses.add(s3Response); + + } + + } + + response.setResponses(s3Responses); + response.setResponseName(this.getCommandName()); + + this.setResponseObject(response); + + } + + @Override + public boolean equals(final Object thatObject) { + + if (this == thatObject) { + return true; + } + + if (thatObject == null || getClass() != thatObject.getClass()) { + return false; + } + + final ListS3sCmd thatListS3sCmd = (ListS3sCmd) thatObject; + + if (this.id != null ? !this.id.equals(thatListS3sCmd.id) : thatListS3sCmd.id != null) { + return false; + } + + return true; + + } + + @Override + public int hashCode() { + return this.id != null ? this.id.hashCode() : 0; + } + + @Override + public String getCommandName() { + return COMMAND_NAME; + } + + public Long getId() { + return this.id; + } + +} diff --git a/api/src/com/cloud/api/response/S3Response.java b/api/src/com/cloud/api/response/S3Response.java new file mode 100644 index 00000000000..0d2cf7e4ea7 --- /dev/null +++ b/api/src/com/cloud/api/response/S3Response.java @@ -0,0 +1,210 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.api.response; + +import com.cloud.serializer.Param; +import com.cloud.utils.IdentityProxy; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; + +import static org.apache.cloudstack.api.ApiConstants.*; + +public class S3Response extends BaseResponse { + + @SerializedName(ID) + @Param(description = "The ID of the S3 configuration") + private IdentityProxy id = new IdentityProxy("s3"); + + @SerializedName(S3_ACCESS_KEY) + @Param(description = "The S3 access key") + private String accessKey; + + @SerializedName(S3_SECRET_KEY) + @Param(description = "The S3 secret key") + private String secretKey; + + @SerializedName(S3_END_POINT) + @Param(description = "The S3 end point") + private String endPoint; + + @SerializedName(S3_BUCKET_NAME) + @Param(description = "The name of the template storage bucket") + private String bucketName; + + @SerializedName(S3_HTTPS_FLAG) + @Param(description = "Connect to S3 using HTTPS?") + private Integer httpsFlag; + + @SerializedName(S3_CONNECTION_TIMEOUT) + @Param(description = "The connection timeout (milliseconds)") + private Integer connectionTimeout; + + @SerializedName(S3_MAX_ERROR_RETRY) + @Param(description = "The maximum number of time to retry a connection on error.") + private Integer maxErrorRetry; + + @SerializedName(S3_SOCKET_TIMEOUT) + @Param(description = "The connection socket (milliseconds)") + private Integer socketTimeout; + + @Override + public boolean equals(final Object thatObject) { + + if (this == thatObject) { + return true; + } + + if (thatObject == null || this.getClass() != thatObject.getClass()) { + return false; + } + + final S3Response thatS3Response = (S3Response) thatObject; + + if (this.httpsFlag != null ? !this.httpsFlag.equals(thatS3Response.httpsFlag) : thatS3Response.httpsFlag != null) { + return false; + } + + if (this.accessKey != null ? !this.accessKey.equals(thatS3Response.accessKey) : thatS3Response.accessKey != null) { + return false; + } + + if (this.connectionTimeout != null ? !this.connectionTimeout.equals(thatS3Response.connectionTimeout) : thatS3Response.connectionTimeout != null) { + return false; + } + + if (this.endPoint != null ? !this.endPoint.equals(thatS3Response.endPoint) : thatS3Response.endPoint != null) { + return false; + } + + if (this.id != null ? !this.id.equals(thatS3Response.id) : thatS3Response.id != null) { + return false; + } + + if (this.maxErrorRetry != null ? !this.maxErrorRetry.equals(thatS3Response.maxErrorRetry) : thatS3Response.maxErrorRetry != null) { + return false; + } + + if (this.secretKey != null ? !this.secretKey.equals(thatS3Response.secretKey) : thatS3Response.secretKey != null) { + return false; + } + + if (this.socketTimeout != null ? !this.socketTimeout.equals(thatS3Response.socketTimeout) : thatS3Response.socketTimeout != null) { + return false; + } + + if (this.bucketName != null ? !this.bucketName.equals(thatS3Response.bucketName) : thatS3Response.bucketName != null) { + return false; + } + + return true; + + } + + @Override + public int hashCode() { + + int result = this.id != null ? this.id.hashCode() : 0; + result = 31 * result + (this.accessKey != null ? this.accessKey.hashCode() : 0); + result = 31 * result + (this.secretKey != null ? this.secretKey.hashCode() : 0); + result = 31 * result + (this.endPoint != null ? this.endPoint.hashCode() : 0); + result = 31 * result + (this.bucketName != null ? this.bucketName.hashCode() : 0); + result = 31 * result + (this.httpsFlag != null ? this.httpsFlag : 0); + result = 31 * result + (this.connectionTimeout != null ? this.connectionTimeout.hashCode() : 0); + result = 31 * result + (this.maxErrorRetry != null ? this.maxErrorRetry.hashCode() : 0); + result = 31 * result + (this.socketTimeout != null ? this.socketTimeout.hashCode() : 0); + + return result; + + } + + @Override + public String getObjectId() { + return this.id.getValue().toString(); + } + + public void setObjectId(Long id) { + this.id.setValue(id); + } + + public String getAccessKey() { + return this.accessKey; + } + + public void setAccessKey(final String accessKey) { + this.accessKey = accessKey; + } + + public String getSecretKey() { + return this.secretKey; + } + + public void setSecretKey(final String secretKey) { + this.secretKey = secretKey; + } + + public String getEndPoint() { + return this.endPoint; + } + + public void setEndPoint(final String endPoint) { + this.endPoint = endPoint; + } + + + public String getTemplateBucketName() { + return this.bucketName; + } + + public void setTemplateBucketName(final String templateBucketName) { + this.bucketName = templateBucketName; + } + + public Integer getHttpsFlag() { + return this.httpsFlag; + } + + public void setHttpsFlag(final Integer httpsFlag) { + this.httpsFlag = httpsFlag; + } + + public Integer getConnectionTimeout() { + return this.connectionTimeout; + } + + public void setConnectionTimeout(final Integer connectionTimeout) { + this.connectionTimeout = connectionTimeout; + } + + public Integer getMaxErrorRetry() { + return this.maxErrorRetry; + } + + public void setMaxErrorRetry(final Integer maxErrorRetry) { + this.maxErrorRetry = maxErrorRetry; + } + + public Integer getSocketTimeout() { + return this.socketTimeout; + } + + public void setSocketTimeout(final Integer socketTimeout) { + this.socketTimeout = socketTimeout; + } + +} diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index 2a0c930905f..f91dd6615ef 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -16,11 +16,6 @@ // under the License. package com.cloud.network; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - import com.cloud.acl.ControlledEntity; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; @@ -28,6 +23,11 @@ import com.cloud.network.Networks.TrafficType; import com.cloud.utils.fsm.FiniteState; import com.cloud.utils.fsm.StateMachine; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + /** * owned by an account. */ @@ -168,6 +168,7 @@ public interface Network extends ControlledEntity { public static final Capability AllowDnsSuffixModification = new Capability("AllowDnsSuffixModification"); public static final Capability RedundantRouter = new Capability("RedundantRouter"); public static final Capability ElasticIp = new Capability("ElasticIp"); + public static final Capability AssociatePublicIP = new Capability("AssociatePublicIP"); public static final Capability ElasticLb = new Capability("ElasticLb"); public static final Capability AutoScaleCounters = new Capability("AutoScaleCounters"); diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index 140563ec99f..d5841a4692e 100755 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -41,7 +41,7 @@ public interface NetworkService { List getIsolatedNetworksOwnedByAccountInZone(long zoneId, Account owner); - IpAddress allocateIP(Account ipOwner, boolean isSystem, long zoneId) throws ResourceAllocationException, + IpAddress allocateIP(Account ipOwner, long zoneId, Long networkId) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException; boolean releaseIpAddress(long ipAddressId) throws InsufficientAddressCapacityException; diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java index 153e6c07053..8b4e7e210cd 100644 --- a/api/src/com/cloud/offering/NetworkOffering.java +++ b/api/src/com/cloud/offering/NetworkOffering.java @@ -107,6 +107,8 @@ public interface NetworkOffering { boolean getElasticIp(); + boolean getAssociatePublicIP(); + boolean getElasticLb(); boolean getSpecifyIpRanges(); diff --git a/api/src/com/cloud/resource/ResourceService.java b/api/src/com/cloud/resource/ResourceService.java index 4d1c0bad4dd..ade10127773 100755 --- a/api/src/com/cloud/resource/ResourceService.java +++ b/api/src/com/cloud/resource/ResourceService.java @@ -24,12 +24,15 @@ import org.apache.cloudstack.api.command.admin.host.*; import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd; import org.apache.cloudstack.api.command.admin.swift.ListSwiftsCmd; import org.apache.cloudstack.api.command.admin.host.PrepareForMaintenanceCmd; +import com.cloud.api.commands.AddS3Cmd; +import com.cloud.api.commands.ListS3sCmd; import com.cloud.exception.DiscoveryException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceInUseException; import com.cloud.host.Host; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.org.Cluster; +import com.cloud.storage.S3; import com.cloud.storage.Swift; import com.cloud.utils.fsm.NoTransitionException; import org.apache.cloudstack.api.command.admin.host.ReconnectHostCmd; @@ -90,7 +93,12 @@ public interface ResourceService { Swift discoverSwift(AddSwiftCmd addSwiftCmd) throws DiscoveryException; + S3 discoverS3(AddS3Cmd cmd) throws DiscoveryException; + List getSupportedHypervisorTypes(long zoneId, boolean forVirtualRouter, Long podId); List listSwifts(ListSwiftsCmd cmd); + + List listS3s(ListS3sCmd cmd); + } diff --git a/api/src/com/cloud/storage/S3.java b/api/src/com/cloud/storage/S3.java new file mode 100644 index 00000000000..7a679f2adc5 --- /dev/null +++ b/api/src/com/cloud/storage/S3.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.storage; + +import com.cloud.agent.api.to.S3TO; + +import java.util.Date; + +public interface S3 { + + long getId(); + + String getUuid(); + + String getAccessKey(); + + String getSecretKey(); + + String getEndPoint(); + + String getBucketName(); + + Integer getHttpsFlag(); + + Integer getConnectionTimeout(); + + Integer getMaxErrorRetry(); + + Integer getSocketTimeout(); + + Date getCreated(); + + S3TO toS3TO(); + +} diff --git a/api/src/org/apache/cloudstack/api/ApiConstants.java b/api/src/org/apache/cloudstack/api/ApiConstants.java index 8b05f1d9c11..6d8400ae6fd 100644 --- a/api/src/org/apache/cloudstack/api/ApiConstants.java +++ b/api/src/org/apache/cloudstack/api/ApiConstants.java @@ -16,6 +16,8 @@ // under the License. package org.apache.cloudstack.api; +import org.omg.CORBA.PUBLIC_MEMBER; + public class ApiConstants { public static final String ACCOUNT = "account"; public static final String ACCOUNTS = "accounts"; @@ -383,7 +385,16 @@ public class ApiConstants { public static final String NICIRA_NVP_TRANSPORT_ZONE_UUID = "transportzoneuuid"; public static final String NICIRA_NVP_DEVICE_NAME = "niciradevicename"; public static final String NICIRA_NVP_GATEWAYSERVICE_UUID = "l3gatewayserviceuuid"; - + public static final String S3_ACCESS_KEY = "accesskey"; + public static final String S3_SECRET_KEY = "secretkey"; + public static final String S3_END_POINT = "endpoint"; + public static final String S3_BUCKET_NAME = "bucket"; + public static final String S3_HTTPS_FLAG = "usehttps"; + public static final String S3_CONNECTION_TIMEOUT = "connectiontimeout"; + public static final String S3_MAX_ERROR_RETRY = "maxerrorretry"; + public static final String S3_SOCKET_TIMEOUT = "sockettimeout"; + public static final String INCL_ZONES = "includezones"; + public static final String EXCL_ZONES = "excludezones"; public static final String SOURCE = "source"; public static final String COUNTER_ID = "counterid"; public static final String AGGR_OPERATOR = "aggroperator"; diff --git a/api/src/org/apache/cloudstack/api/ResponseGenerator.java b/api/src/org/apache/cloudstack/api/ResponseGenerator.java index ee7f15e3cf2..559a7ad0ffb 100644 --- a/api/src/org/apache/cloudstack/api/ResponseGenerator.java +++ b/api/src/org/apache/cloudstack/api/ResponseGenerator.java @@ -92,6 +92,7 @@ import org.apache.cloudstack.api.response.VpcResponse; import org.apache.cloudstack.api.response.VpnUsersResponse; import org.apache.cloudstack.api.response.ZoneResponse; +import com.cloud.api.response.S3Response; import com.cloud.async.AsyncJob; import com.cloud.capacity.Capacity; @@ -144,6 +145,7 @@ import com.cloud.projects.ProjectAccount; import com.cloud.projects.ProjectInvitation; import com.cloud.server.ResourceTag; import com.cloud.storage.GuestOS; +import com.cloud.storage.S3; import com.cloud.storage.Snapshot; import com.cloud.storage.StoragePool; import com.cloud.storage.Swift; @@ -296,6 +298,8 @@ public interface ResponseGenerator { SwiftResponse createSwiftResponse(Swift swift); + S3Response createS3Response(S3 result); + PhysicalNetworkResponse createPhysicalNetworkResponse(PhysicalNetwork result); ServiceResponse createNetworkServiceResponse(Service service); @@ -375,5 +379,4 @@ public interface ResponseGenerator { GuestOSResponse createGuestOSResponse(GuestOS os); SnapshotScheduleResponse createSnapshotScheduleResponse(SnapshotSchedule sched); - } diff --git a/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java b/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java index f4d48531849..c696c6ee4ee 100644 --- a/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java @@ -216,7 +216,8 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { @Override public void create() throws ResourceAllocationException{ try { - IpAddress ip = _networkService.allocateIP(_accountService.getAccount(getEntityOwnerId()), false, getZoneId()); + IpAddress ip = _networkService.allocateIP(_accountService.getAccount(getEntityOwnerId()), getZoneId(), getNetworkId()); + if (ip != null) { this.setEntityId(ip.getId()); } else { diff --git a/api/test/src/com/cloud/agent/api/test/BackupSnapshotAnswerTest.java b/api/test/src/com/cloud/agent/api/test/BackupSnapshotAnswerTest.java index aa1c0fb7f42..b3f2847cd51 100644 --- a/api/test/src/com/cloud/agent/api/test/BackupSnapshotAnswerTest.java +++ b/api/test/src/com/cloud/agent/api/test/BackupSnapshotAnswerTest.java @@ -36,7 +36,7 @@ public class BackupSnapshotAnswerTest { StoragePool pool = Mockito.mock(StoragePool.class); - bsc = new BackupSnapshotCommand("primaryStoragePoolNameLabel", + bsc = new BackupSnapshotCommand( "secondaryStoragePoolURL", 101L, 102L, 103L, 104L, "volumePath", pool, "snapshotUuid", "snapshotName", "prevSnapshotUuid", "prevBackupUuid", false, "vmName", 5); diff --git a/api/test/src/com/cloud/agent/api/test/BackupSnapshotCommandTest.java b/api/test/src/com/cloud/agent/api/test/BackupSnapshotCommandTest.java index baeed5577da..a6241488943 100644 --- a/api/test/src/com/cloud/agent/api/test/BackupSnapshotCommandTest.java +++ b/api/test/src/com/cloud/agent/api/test/BackupSnapshotCommandTest.java @@ -116,14 +116,14 @@ public class BackupSnapshotCommandTest { }; BackupSnapshotCommand bsc = new BackupSnapshotCommand( - "primaryStoragePoolNameLabel", "http://secondary.Storage.Url", + "http://secondary.Storage.Url", 101L, 102L, 103L, 104L, "vPath", pool, "420fa39c-4ef1-a83c-fd93-46dc1ff515ae", "sName", "9012793e-0657-11e2-bebc-0050568b0057", "7167e0b2-f5b0-11e1-8414-0050568b0057", false, "vmName", 5); BackupSnapshotCommand bsc1 = new BackupSnapshotCommand( - "primaryStoragePoolNameLabel", "http://secondary.Storage.Url", + "http://secondary.Storage.Url", 101L, 102L, 103L, 104L, "vPath", pool, "420fa39c-4ef1-a83c-fd93-46dc1ff515ae", "sName", "9012793e-0657-11e2-bebc-0050568b0057", @@ -132,7 +132,7 @@ public class BackupSnapshotCommandTest { @Test public void testGetPrimaryStoragePoolNameLabel() { String label = bsc.getPrimaryStoragePoolNameLabel(); - assertTrue(label.equals("primaryStoragePoolNameLabel")); + assertTrue(label.equals("bed9f83e-cac3-11e1-ac8a-0050568b007e")); } @Test diff --git a/api/test/src/com/cloud/agent/api/test/SnapshotCommandTest.java b/api/test/src/com/cloud/agent/api/test/SnapshotCommandTest.java index 3e37edaf53b..98cdee2a8bf 100644 --- a/api/test/src/com/cloud/agent/api/test/SnapshotCommandTest.java +++ b/api/test/src/com/cloud/agent/api/test/SnapshotCommandTest.java @@ -23,19 +23,109 @@ import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + import com.cloud.agent.api.SnapshotCommand; +import com.cloud.storage.Storage.StoragePoolType; +import com.cloud.storage.StoragePool; +import com.cloud.storage.StoragePoolStatus; public class SnapshotCommandTest { - SnapshotCommand ssc = new SnapshotCommand("primaryStoragePoolNameLabel", + + public StoragePool pool = new StoragePool() { + public long getId() { + return 1L; + }; + + public String getName() { + return "name"; + }; + + public String getUuid() { + return "bed9f83e-cac3-11e1-ac8a-0050568b007e"; + }; + + public StoragePoolType getPoolType() { + return StoragePoolType.Filesystem; + }; + + public Date getCreated() { + Date date = null; + try { + date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss") + .parse("01/01/1970 12:12:12"); + } catch (ParseException e) { + e.printStackTrace(); + } + return date; + } + + public Date getUpdateTime() { + return new Date(); + }; + + public long getDataCenterId() { + return 0L; + }; + + public long getCapacityBytes() { + return 0L; + }; + + public long getAvailableBytes() { + return 0L; + }; + + public Long getClusterId() { + return 0L; + }; + + public String getHostAddress() { + return "hostAddress"; + }; + + public String getPath() { + return "path"; + }; + + public String getUserInfo() { + return "userInfo"; + }; + + public boolean isShared() { + return false; + }; + + public boolean isLocal() { + return false; + }; + + public StoragePoolStatus getStatus() { + return StoragePoolStatus.Up; + }; + + public int getPort() { + return 25; + }; + + public Long getPodId() { + return 0L; + }; + }; + + SnapshotCommand ssc = new SnapshotCommand(pool, "http://secondary.Storage.Url", "420fa39c-4ef1-a83c-fd93-46dc1ff515ae", "snapshotName", 101L, 102L, 103L); SnapshotCommand ssc1; + @Before public void setUp() { - ssc1 = new SnapshotCommand("primaryStoragePoolNameLabel", + ssc1 = new SnapshotCommand(pool, "secondaryStorageUrl", "snapshotUuid", "snapshotName", 101L, 102L, 103L); } @@ -43,7 +133,7 @@ public class SnapshotCommandTest { @Test public void testGetPrimaryStoragePoolNameLabel() { String label = ssc.getPrimaryStoragePoolNameLabel(); - assertTrue(label.equals("primaryStoragePoolNameLabel")); + assertTrue(label.equals("bed9f83e-cac3-11e1-ac8a-0050568b007e")); } @Test diff --git a/awsapi/src/com/cloud/bridge/io/S3CAStorBucketAdapter.java b/awsapi/src/com/cloud/bridge/io/S3CAStorBucketAdapter.java index 2101afe1418..d7adc286816 100644 --- a/awsapi/src/com/cloud/bridge/io/S3CAStorBucketAdapter.java +++ b/awsapi/src/com/cloud/bridge/io/S3CAStorBucketAdapter.java @@ -58,6 +58,7 @@ import com.caringo.client.ScspResponse; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; /** @@ -413,23 +414,26 @@ public class S3CAStorBucketAdapter implements S3BucketAdapter { } public class ScspDataSource implements DataSource { - GetMethod method; - public ScspDataSource(GetMethod m) { - method = m; + String content_type = null; + byte content[] = null; + public ScspDataSource(GetMethod method) { + Header h = method.getResponseHeader("Content-type"); + if (h != null) { + content_type = h.getValue(); + } + try{ + content = method.getResponseBody(); + }catch(IOException e){ + s_logger.error("CAStor loadObjectRange getInputStream error", e); + } } @Override public String getContentType() { - Header h = method.getResponseHeader("Content-type"); - return h==null ? null : h.getValue(); + return content_type; } @Override - public InputStream getInputStream() throws IOException { - try { - return method.getResponseBodyAsStream(); - } catch (Exception e) { - s_logger.error("CAStor loadObjectRange getInputStream error", e); - return null; - } + public InputStream getInputStream() { + return new ByteArrayInputStream(content); } @Override public String getName() { @@ -445,21 +449,27 @@ public class S3CAStorBucketAdapter implements S3BucketAdapter { @Override public DataHandler loadObjectRange(String mountedRoot, String bucket, String fileName, long startPos, long endPos) { + HttpClient httpClient = new HttpClient(s_httpClientManager); + // Create a method instance. + GetMethod method = new GetMethod(castorURL(mountedRoot, bucket, fileName)); + method.addRequestHeader("Range", "bytes=" + startPos + "-" + endPos); + int statusCode; try { - HttpClient httpClient = new HttpClient(s_httpClientManager); - // Create a method instance. - GetMethod method = new GetMethod(castorURL(mountedRoot, bucket, fileName)); - method.addRequestHeader("Range", "bytes=" + startPos + "-" + endPos); - int statusCode = httpClient.executeMethod(method); - if (statusCode < HTTP_OK || statusCode >= HTTP_UNSUCCESSFUL) { - s_logger.error("CAStor loadObjectRange response: "+ statusCode); - throw new FileNotExistException("CAStor loadObjectRange response: " + statusCode); - } - return new DataHandler(new ScspDataSource(method)); - } catch (Exception e) { + statusCode = httpClient.executeMethod(method); + } catch (HttpException e) { + s_logger.error("CAStor loadObjectRange failure", e); + throw new FileNotExistException("CAStor loadObjectRange failure: " + e); + } catch (IOException e) { s_logger.error("CAStor loadObjectRange failure", e); throw new FileNotExistException("CAStor loadObjectRange failure: " + e); } + if (statusCode < HTTP_OK || statusCode >= HTTP_UNSUCCESSFUL) { + s_logger.error("CAStor loadObjectRange response: "+ statusCode); + throw new FileNotExistException("CAStor loadObjectRange response: " + statusCode); + } + DataHandler ret = new DataHandler(new ScspDataSource(method)); + method.releaseConnection(); + return ret; } @Override diff --git a/client/WEB-INF/classes/resources/messages.properties b/client/WEB-INF/classes/resources/messages.properties index b606cce3c95..3dc01aa2008 100644 --- a/client/WEB-INF/classes/resources/messages.properties +++ b/client/WEB-INF/classes/resources/messages.properties @@ -19,7 +19,7 @@ #new labels (begin) ********************************************************************************************** label.egress.rules=Egress rules message.acquire.new.ip.vpc=Please confirm that you would like to acquire a new IP for this VPC. -label.zoneWizard.trafficType.management=Mangement: Traffic between CloudStack\'s internal resources, including any components that communicate with the Management Server, such as hosts and CloudStack system VMs +label.zoneWizard.trafficType.management=Management: Traffic between CloudStack\'s internal resources, including any components that communicate with the Management Server, such as hosts and CloudStack system VMs label.zoneWizard.trafficType.public=Public: Traffic between the internet and virtual machines in the cloud. label.zoneWizard.trafficType.guest=Guest: Traffic between end-user virtual machines label.zoneWizard.trafficType.storage=Storage: Traffic between primary and secondary storage servers, such as VM templates and snapshots @@ -32,6 +32,17 @@ label.destroy=Destroy label.restore=Restore label.isolation.uri=Isolation URI label.broadcast.uri=Broadcast URI +label.enable.s3=Enable S3-backed Secondary Storage +confirm.enable.s3=Please fill in the following information to enable support for S3-backed Secondary Storage +message.after.enable.s3=S3-backed Secondary Storage configured. Note: When you leave this page, you will not be able to re-configure S3 again. +label.s3.access_key=Access Key +label.s3.secret_key=Secret Key +label.s3.bucket=Bucket +label.s3.endpoint=Endpoint +label.s3.use_https=Use HTTPS +label.s3.connection_timeout=Connection Timeout +label.s3.max_error_retry=Max Error Retry +label.s3.socket_timeout=Socket Timeout #new labels (end) ************************************************************************************************ @@ -305,8 +316,6 @@ label.installWizard.subtitle=This tour will aid you in setting up your CloudStac label.continue=Continue label.installWizard.title=Hello and Welcome to CloudStack™ label.agree=Agree -label.license.agreement=License Agreement -label.license.agreement.subtitle=Please accept the CloudStack™ EULA before installing. label.manage.resources=Manage Resources label.port.forwarding.policies=Port forwarding policies label.load.balancing.policies=Load balancing policies diff --git a/client/WEB-INF/classes/resources/messages_fr_FR.properties b/client/WEB-INF/classes/resources/messages_fr_FR.properties index 3710d25a916..4ba3c725892 100644 --- a/client/WEB-INF/classes/resources/messages_fr_FR.properties +++ b/client/WEB-INF/classes/resources/messages_fr_FR.properties @@ -292,8 +292,6 @@ label.installWizard.subtitle=Ce tutorial vous aidera label.continue=Continuer label.installWizard.title=Bonjour et bienvenue dans CloudStack label.agree=Accepter -label.license.agreement=Accord de licence -label.license.agreement.subtitle=Merci d\'accepter l\'EULA CloudStack avant d\'installer. label.manage.resources=Gérer les ressources label.port.forwarding.policies=Règles de transfert de port label.load.balancing.policies=Règles de répartition de charge diff --git a/client/WEB-INF/classes/resources/messages_ja.properties b/client/WEB-INF/classes/resources/messages_ja.properties index ec785f6f83e..7555b83dd78 100644 --- a/client/WEB-INF/classes/resources/messages_ja.properties +++ b/client/WEB-INF/classes/resources/messages_ja.properties @@ -295,8 +295,6 @@ label.installWizard.subtitle=ã“ã®ã‚¬ã‚¤ãƒ‰ ツアー㯠CloudStack™ ç’° label.continue=続行 label.installWizard.title=CloudStack™ ã¸ã‚ˆã†ã“ã label.agree=åŒæ„ã™ã‚‹ -label.license.agreement=ライセンス契約 -label.license.agreement.subtitle=インストールã®å‰ã« CloudStack™ エンド ユーザー ライセンス契約ã«åŒæ„ã—ã¦ãã ã•ã„。 label.manage.resources=リソースã®ç®¡ç† label.port.forwarding.policies=ãƒãƒ¼ãƒˆè»¢é€ãƒãƒªã‚·ãƒ¼ label.load.balancing.policies=è² è·åˆ†æ•£ãƒãƒªã‚·ãƒ¼ diff --git a/client/WEB-INF/classes/resources/messages_pt_BR.properties b/client/WEB-INF/classes/resources/messages_pt_BR.properties index 2b6a5d3ce45..3bc435b9717 100644 --- a/client/WEB-INF/classes/resources/messages_pt_BR.properties +++ b/client/WEB-INF/classes/resources/messages_pt_BR.properties @@ -292,8 +292,6 @@ label.installWizard.subtitle=Este tour vai auxiliar voc label.continue=Continuar label.installWizard.title=Olá, seja bem vindo ao CloudStack&\#8482 label.agree=Concordo -label.license.agreement=Acordo de Licença -label.license.agreement.subtitle=Por favor aceite a EULA do CloudStack&\#8482 antes de instalar. label.manage.resources=Gerenciar Recursos label.port.forwarding.policies=Políticas de redirecionamento de portas label.load.balancing.policies=Políticas de balanceamento de carga diff --git a/client/WEB-INF/classes/resources/messages_ru_RU.properties b/client/WEB-INF/classes/resources/messages_ru_RU.properties index 0c6b962d1cf..dd7e7460744 100644 --- a/client/WEB-INF/classes/resources/messages_ru_RU.properties +++ b/client/WEB-INF/classes/resources/messages_ru_RU.properties @@ -292,8 +292,6 @@ label.installWizard.subtitle=Это руководÑтво наÑтроит ва label.continue=Продолжить label.installWizard.title=ЗдравÑтвуйте и добро пожаловать в CloudStack\! label.agree=СоглаÑен -label.license.agreement=Лицензионное Ñоглашение -label.license.agreement.subtitle=Ð”Ð»Ñ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶ÐµÐ½Ð¸Ñ ÑƒÑтановки ÑоглаÑитеÑÑŒ Ñ Ð»Ð¸Ñ†ÐµÐ½Ð·Ð¸Ð¾Ð½Ð½Ñ‹Ð¼ Ñоглашением. label.manage.resources=Управление реÑурÑами label.port.forwarding.policies=Политики проброÑа портов label.load.balancing.policies=Политики баланÑировки нагрузки diff --git a/client/WEB-INF/classes/resources/messages_zh_CN.properties b/client/WEB-INF/classes/resources/messages_zh_CN.properties index f86601773cb..62160d98488 100644 --- a/client/WEB-INF/classes/resources/messages_zh_CN.properties +++ b/client/WEB-INF/classes/resources/messages_zh_CN.properties @@ -295,8 +295,6 @@ label.installWizard.subtitle=此教程将帮助您设置 CloudStack™ 安装 label.continue=ç»§ç»­ label.installWizard.title=您好,欢迎使用 CloudStack™ label.agree=åŒæ„ -label.license.agreement=许å¯åè®® -label.license.agreement.subtitle=å¿…é¡»å…ˆæŽ¥å— CloudStack™ EULA æ‰èƒ½è¿›è¡Œå®‰è£…。 label.manage.resources=管ç†èµ„æº label.port.forwarding.policies=端å£è½¬å‘ç­–ç•¥ label.load.balancing.policies=负载平衡策略 diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in index df7768720f1..c334c81924c 100755 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -224,10 +224,14 @@ listAlerts=org.apache.cloudstack.api.command.admin.resource.ListAlertsCmd;3 #### system capacity commands listCapacity=org.apache.cloudstack.api.command.admin.resource.ListCapacityCmd;3 -#### swift commands^M +#### swift commands addSwift=org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd;1 listSwifts=org.apache.cloudstack.api.command.admin.swift.ListSwiftsCmd;1 +#### s3 commands +addS3=com.cloud.api.commands.AddS3Cmd;1 +listS3s=com.cloud.api.commands.ListS3sCmd;1 + #### host commands addHost=org.apache.cloudstack.api.command.admin.host.AddHostCmd;3 addCluster=org.apache.cloudstack.api.command.admin.cluster.AddClusterCmd;1 diff --git a/client/tomcatconf/db-enc.properties.in b/client/tomcatconf/db-enc.properties.in index 6136f37511f..a9404fa4932 100644 --- a/client/tomcatconf/db-enc.properties.in +++ b/client/tomcatconf/db-enc.properties.in @@ -37,9 +37,6 @@ db.cloud.testOnBorrow=true db.cloud.testWhileIdle=true db.cloud.timeBetweenEvictionRunsMillis=40000 db.cloud.minEvictableIdleTimeMillis=240000 -db.cloud.removeAbandoned=false -db.cloud.removeAbandonedTimeout=300 -db.cloud.logAbandoned=true db.cloud.poolPreparedStatements=false db.cloud.url.params=prepStmtCacheSize=517&cachePrepStmts=true diff --git a/client/tomcatconf/db.properties.in b/client/tomcatconf/db.properties.in index f39d8fe4097..e38366706d4 100644 --- a/client/tomcatconf/db.properties.in +++ b/client/tomcatconf/db.properties.in @@ -37,9 +37,6 @@ db.cloud.testOnBorrow=true db.cloud.testWhileIdle=true db.cloud.timeBetweenEvictionRunsMillis=40000 db.cloud.minEvictableIdleTimeMillis=240000 -db.cloud.removeAbandoned=false -db.cloud.removeAbandonedTimeout=300 -db.cloud.logAbandoned=true db.cloud.poolPreparedStatements=false db.cloud.url.params=prepStmtCacheSize=517&cachePrepStmts=true diff --git a/core/pom.xml b/core/pom.xml index 15f0f7b7302..3d6356e561e 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -43,6 +43,11 @@ + + commons-codec + commons-codec + ${cs.codec.version} + install diff --git a/core/src/com/cloud/agent/api/DirectNetworkUsageCommand.java b/core/src/com/cloud/agent/api/DirectNetworkUsageCommand.java index 97dcf90177e..86e794a1dc6 100644 --- a/core/src/com/cloud/agent/api/DirectNetworkUsageCommand.java +++ b/core/src/com/cloud/agent/api/DirectNetworkUsageCommand.java @@ -24,11 +24,15 @@ public class DirectNetworkUsageCommand extends Command { private List publicIps; private Date start; private Date end; + private String includeZones; + private String excludeZones; - public DirectNetworkUsageCommand(List publicIps, Date start, Date end) { + public DirectNetworkUsageCommand(List publicIps, Date start, Date end, String includeZones, String excludeZones) { this.setPublicIps(publicIps); this.setStart(start); this.setEnd(end); + this.setIncludeZones(includeZones); + this.setExcludeZones(excludeZones); } @Override @@ -59,4 +63,21 @@ public class DirectNetworkUsageCommand extends Command { public Date getEnd() { return end; } + + public String getIncludeZones() { + return includeZones; + } + + public void setIncludeZones(String includeZones) { + this.includeZones = includeZones; + } + + public String getExcludeZones() { + return excludeZones; + } + + public void setExcludeZones(String excludeZones) { + this.excludeZones = excludeZones; + } + } diff --git a/core/src/com/cloud/network/resource/TrafficSentinelResource.java b/core/src/com/cloud/network/resource/TrafficSentinelResource.java index a9088d0eb67..a13e080b7e4 100644 --- a/core/src/com/cloud/network/resource/TrafficSentinelResource.java +++ b/core/src/com/cloud/network/resource/TrafficSentinelResource.java @@ -49,7 +49,6 @@ import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupTrafficMonitorCommand; import com.cloud.host.Host; import com.cloud.resource.ServerResource; -import com.cloud.utils.NumbersUtil; import com.cloud.utils.exception.ExecutionException; public class TrafficSentinelResource implements ServerResource { @@ -59,8 +58,8 @@ public class TrafficSentinelResource implements ServerResource { private String _ip; private String _guid; private String _url; - private static Integer _numRetries; - private static Integer _timeoutInSeconds; + private String _inclZones; + private String _exclZones; private static final Logger s_logger = Logger.getLogger(TrafficSentinelResource.class); @@ -91,9 +90,8 @@ public class TrafficSentinelResource implements ServerResource { throw new ConfigurationException("Unable to find url"); } - _numRetries = NumbersUtil.parseInt((String) params.get("numRetries"), 1); - - _timeoutInSeconds = NumbersUtil.parseInt((String) params.get("timeoutInSeconds"), 300); + _inclZones = (String)params.get("inclZones"); + _exclZones = (String)params.get("exclZones"); return true; } catch (Exception e) { @@ -197,6 +195,15 @@ public class TrafficSentinelResource implements ServerResource { try { //Direct Network Usage URL trafficSentinel; + //Use Global include/exclude zones if there are no per TS zones + if(_inclZones == null){ + _inclZones = cmd.getIncludeZones(); + } + + if(_exclZones == null){ + _exclZones = cmd.getExcludeZones(); + } + try { //Query traffic Sentinel trafficSentinel = new URL(_url+"/inmsf/Query?script="+URLEncoder.encode(getScript(cmd.getPublicIps(), cmd.getStart(), cmd.getEnd()),"UTF-8") @@ -247,12 +254,28 @@ public class TrafficSentinelResource implements ServerResource { IpAddresses += ","; } } + String destZoneCondition = ""; + if(_inclZones !=null && !_inclZones.isEmpty()){ + destZoneCondition = " & destinationzone = "+_inclZones; + } + if(_exclZones !=null && !_exclZones.isEmpty()){ + destZoneCondition += " & destinationzone != "+_exclZones; + } + + String srcZoneCondition = ""; + if(_inclZones !=null && !_inclZones.isEmpty()){ + srcZoneCondition = " & sourcezone = "+_inclZones; + } + if(_exclZones !=null && !_exclZones.isEmpty()){ + srcZoneCondition += " & sourcezone != "+_exclZones; + } + String startDate = getDateString(start); String endtDate = getDateString(end); StringBuffer sb = new StringBuffer(); sb.append("var q = Query.topN(\"historytrmx\","); sb.append(" \"ipsource,bytes\","); - sb.append(" \"ipsource = "+IpAddresses+" & destinationzone = EXTERNAL\","); + sb.append(" \"ipsource = "+IpAddresses+destZoneCondition+"\","); sb.append(" \""+startDate+", "+endtDate+"\","); sb.append(" \"bytes\","); sb.append(" 100000);"); @@ -265,7 +288,7 @@ public class TrafficSentinelResource implements ServerResource { sb.append(" });"); sb.append("var q = Query.topN(\"historytrmx\","); sb.append(" \"ipdestination,bytes\","); - sb.append(" \"ipdestination = "+IpAddresses+" & sourcezone = EXTERNAL\","); + sb.append(" \"ipdestination = "+IpAddresses+srcZoneCondition+"\","); sb.append(" \""+startDate+", "+endtDate+"\","); sb.append(" \"bytes\","); sb.append(" 100000);"); diff --git a/core/src/com/cloud/storage/S3VO.java b/core/src/com/cloud/storage/S3VO.java new file mode 100644 index 00000000000..ab16b2a512b --- /dev/null +++ b/core/src/com/cloud/storage/S3VO.java @@ -0,0 +1,208 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.storage; + +import com.cloud.agent.api.to.S3TO; +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.Identity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import java.util.Date; + +@Entity +@Table(name = "s3") +public class S3VO implements S3, Identity { + + public static final String ID_COLUMN_NAME = "id"; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = ID_COLUMN_NAME) + private long id; + + @Column(name = "uuid") + private String uuid; + + @Column(name = "access_key") + private String accessKey; + + @Column(name = "secret_key") + private String secretKey; + + @Column(name = "end_point") + private String endPoint; + + @Column(name = "bucket") + private String bucketName; + + @Column(name = "https") + private Integer httpsFlag; + + @Column(name = "connection_timeout") + private Integer connectionTimeout; + + @Column(name = "max_error_retry") + private Integer maxErrorRetry; + + @Column(name = "socket_timeout") + private Integer socketTimeout; + + @Column(name = GenericDao.CREATED_COLUMN) + private Date created; + + public S3VO() { + super(); + } + + public S3VO(final String uuid, final String accessKey, + final String secretKey, final String endPoint, + final String bucketName, final Boolean httpsFlag, + final Integer connectionTimeout, final Integer maxErrorRetry, + final Integer socketTimeout, final Date created) { + + super(); + + this.uuid = uuid; + this.accessKey = accessKey; + this.secretKey = secretKey; + this.endPoint = endPoint; + this.bucketName = bucketName; + + Integer value = null; + if (httpsFlag != null) { + value = httpsFlag == false ? 0 : 1; + } + this.httpsFlag = value; + + this.connectionTimeout = connectionTimeout; + this.maxErrorRetry = maxErrorRetry; + this.socketTimeout = socketTimeout; + this.created = created; + + } + + @Override + public S3TO toS3TO() { + + Boolean httpsFlag = null; + if (this.httpsFlag != null) { + httpsFlag = this.httpsFlag == 0 ? false : true; + } + + return new S3TO(this.id, this.uuid, this.accessKey, this.secretKey, + this.endPoint, this.bucketName, httpsFlag, + this.connectionTimeout, this.maxErrorRetry, this.socketTimeout, + this.created); + + } + + public long getId() { + return this.id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getUuid() { + return this.uuid; + } + + public void setUuid(final String uuid) { + this.uuid = uuid; + } + + public String getAccessKey() { + return this.accessKey; + } + + public void setAccessKey(final String accessKey) { + this.accessKey = accessKey; + } + + public String getSecretKey() { + return this.secretKey; + } + + public void setSecretKey(final String secretKey) { + this.secretKey = secretKey; + } + + public String getEndPoint() { + return this.endPoint; + } + + public void setEndPoint(final String endPoint) { + this.endPoint = endPoint; + } + + public String getBucketName() { + return this.bucketName; + } + + public void setBucketName(final String bucketName) { + this.bucketName = bucketName; + } + + public Integer getHttpsFlag() { + return this.httpsFlag; + } + + public void setHttpsFlag(final Integer httpsFlag) { + this.httpsFlag = httpsFlag; + } + + public Integer getConnectionTimeout() { + return this.connectionTimeout; + } + + public void setConnectionTimeout(final int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + } + + public Integer getMaxErrorRetry() { + return this.maxErrorRetry; + } + + public void setMaxErrorRetry(final int maxErrorRetry) { + this.maxErrorRetry = maxErrorRetry; + } + + public Integer getSocketTimeout() { + return this.socketTimeout; + } + + public void setSocketTimeout(final int socketTimeout) { + this.socketTimeout = socketTimeout; + } + + public Date getCreated() { + return this.created; + } + + public void setCreated(final Date created) { + this.created = created; + } + +} diff --git a/core/src/com/cloud/storage/SnapshotVO.java b/core/src/com/cloud/storage/SnapshotVO.java index 928cd2d786f..885a4795ad3 100644 --- a/core/src/com/cloud/storage/SnapshotVO.java +++ b/core/src/com/cloud/storage/SnapshotVO.java @@ -91,6 +91,9 @@ public class SnapshotVO implements Snapshot, Identity { @Column(name="swift_id") Long swiftId; + @Column(name="s3_id") + Long s3Id; + @Column(name="sechost_id") Long secHostId; @@ -289,4 +292,13 @@ public class SnapshotVO implements Snapshot, Identity { public void setUuid(String uuid) { this.uuid = uuid; } + + public Long getS3Id() { + return s3Id; + } + + public void setS3Id(Long s3Id) { + this.s3Id = s3Id; + } + } diff --git a/core/src/com/cloud/storage/VMTemplateS3VO.java b/core/src/com/cloud/storage/VMTemplateS3VO.java new file mode 100644 index 00000000000..a75c37d192d --- /dev/null +++ b/core/src/com/cloud/storage/VMTemplateS3VO.java @@ -0,0 +1,203 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.storage; + +import com.cloud.utils.db.GenericDaoBase; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import java.text.DateFormat; +import java.util.Date; + +@Entity +@Table(name = "template_s3_ref") +public class VMTemplateS3VO { + + public static final String S3_ID_COLUMN_NAME = "s3_id"; + + public static final String TEMPLATE_ID_COLUMN_NAME = "template_id"; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @Column(name = S3_ID_COLUMN_NAME) + private long s3Id; + + @Column(name = TEMPLATE_ID_COLUMN_NAME) + private long templateId; + + @Column(name = GenericDaoBase.CREATED_COLUMN) + private Date created; + + @Column(name = "size") + private Long size; + + @Column(name = "physical_size") + private Long physicalSize; + + public VMTemplateS3VO() { + super(); + } + + public VMTemplateS3VO(final long s3Id, final long templateId, + final Date created, final Long size, final Long physicalSize) { + + super(); + + this.s3Id = s3Id; + this.templateId = templateId; + this.created = created; + this.size = size; + this.physicalSize = physicalSize; + + } + + @Override + public boolean equals(final Object thatObject) { + + if (this == thatObject) { + return true; + } + + if (thatObject == null || getClass() != thatObject.getClass()) { + return false; + } + + final VMTemplateS3VO thatVMTemplateS3VO = (VMTemplateS3VO) thatObject; + + if (this.id != thatVMTemplateS3VO.id) { + return false; + } + + if (this.s3Id != thatVMTemplateS3VO.s3Id) { + return false; + } + + if (this.templateId != thatVMTemplateS3VO.templateId) { + return false; + } + + if (this.created != null ? !created.equals(thatVMTemplateS3VO.created) + : thatVMTemplateS3VO.created != null) { + return false; + } + + if (this.physicalSize != null ? !physicalSize + .equals(thatVMTemplateS3VO.physicalSize) + : thatVMTemplateS3VO.physicalSize != null) { + return false; + } + + if (this.size != null ? !size.equals(thatVMTemplateS3VO.size) + : thatVMTemplateS3VO.size != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + + int result = (int) (this.id ^ (this.id >>> 32)); + + result = 31 * result + (int) (this.s3Id ^ (this.s3Id >>> 32)); + result = 31 * result + + (int) (this.templateId ^ (this.templateId >>> 32)); + result = 31 * result + + (this.created != null ? this.created.hashCode() : 0); + result = 31 * result + (this.size != null ? this.size.hashCode() : 0); + result = 31 + * result + + (this.physicalSize != null ? this.physicalSize.hashCode() : 0); + + return result; + + } + + public long getId() { + return this.id; + } + + public void setId(final long id) { + this.id = id; + } + + public long getS3Id() { + return this.s3Id; + } + + public void setS3Id(final long s3Id) { + this.s3Id = s3Id; + } + + public long getTemplateId() { + return this.templateId; + } + + public void setTemplateId(final long templateId) { + this.templateId = templateId; + } + + public Date getCreated() { + return this.created; + } + + public void setCreated(final Date created) { + this.created = created; + } + + public Long getSize() { + return this.size; + } + + public void setSize(final Long size) { + this.size = size; + } + + public Long getPhysicalSize() { + return this.physicalSize; + } + + public void setPhysicalSize(final Long physicalSize) { + this.physicalSize = physicalSize; + } + + @Override + public String toString() { + + final StringBuilder stringBuilder = new StringBuilder( + "VMTemplateS3VO [ id: ").append(id).append(", created: ") + .append(DateFormat.getDateTimeInstance().format(created)) + .append(", physicalSize: ").append(physicalSize) + .append(", size: ").append(size).append(", templateId: ") + .append(templateId).append(", s3Id: ").append(s3Id) + .append(" ]"); + + return stringBuilder.toString(); + + } + +} diff --git a/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java b/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java index 3b4cc8f4da9..a4bea9df2b4 100755 --- a/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java +++ b/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java @@ -16,10 +16,20 @@ // under the License. package com.cloud.storage.resource; +import static com.cloud.utils.S3Utils.deleteDirectory; +import static com.cloud.utils.S3Utils.getDirectory; +import static com.cloud.utils.S3Utils.putDirectory; +import static com.cloud.utils.StringUtils.join; +import static com.cloud.utils.db.GlobalLock.executeWithNoWaitLock; +import static java.lang.String.format; +import static java.util.Arrays.asList; +import static org.apache.commons.lang.StringUtils.substringAfterLast; + import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; +import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; @@ -32,6 +42,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.Callable; import javax.naming.ConfigurationException; @@ -46,6 +57,9 @@ import com.cloud.agent.api.ComputeChecksumCommand; import com.cloud.agent.api.DeleteObjectFromSwiftCommand; import com.cloud.agent.api.DeleteSnapshotBackupCommand; import com.cloud.agent.api.DeleteSnapshotsDirCommand; +import com.cloud.agent.api.DeleteTemplateFromS3Command; +import com.cloud.agent.api.DownloadSnapshotFromS3Command; +import com.cloud.agent.api.DownloadTemplateFromS3ToSecondaryStorageCommand; import com.cloud.agent.api.GetStorageStatsAnswer; import com.cloud.agent.api.GetStorageStatsCommand; import com.cloud.agent.api.PingCommand; @@ -60,6 +74,8 @@ import com.cloud.agent.api.SecStorageSetupCommand.Certificates; import com.cloud.agent.api.StartupSecondaryStorageCommand; import com.cloud.agent.api.SecStorageVMSetupCommand; import com.cloud.agent.api.StartupCommand; +import com.cloud.agent.api.StartupSecondaryStorageCommand; +import com.cloud.agent.api.UploadTemplateToS3FromSecondaryStorageCommand; import com.cloud.agent.api.downloadSnapshotFromSwiftCommand; import com.cloud.agent.api.downloadTemplateFromSwiftToSecondaryStorageCommand; import com.cloud.agent.api.uploadTemplateToSwiftFromSecondaryStorageCommand; @@ -75,6 +91,7 @@ import com.cloud.agent.api.storage.ListVolumeAnswer; import com.cloud.agent.api.storage.ListVolumeCommand; import com.cloud.agent.api.storage.UploadCommand; import com.cloud.agent.api.storage.ssCommand; +import com.cloud.agent.api.to.S3TO; import com.cloud.agent.api.to.SwiftTO; import com.cloud.exception.InternalErrorException; import com.cloud.host.Host; @@ -89,6 +106,9 @@ import com.cloud.storage.template.TemplateLocation; import com.cloud.storage.template.UploadManager; import com.cloud.storage.template.UploadManagerImpl; import com.cloud.utils.NumbersUtil; +import com.cloud.utils.S3Utils; +import com.cloud.utils.S3Utils.FileNamingStrategy; +import com.cloud.utils.S3Utils.ObjectNamingStrategy; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; @@ -96,8 +116,15 @@ import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.Script; import com.cloud.vm.SecondaryStorageVm; -public class NfsSecondaryStorageResource extends ServerResourceBase implements SecondaryStorageResource { - private static final Logger s_logger = Logger.getLogger(NfsSecondaryStorageResource.class); +public class NfsSecondaryStorageResource extends ServerResourceBase implements + SecondaryStorageResource { + + private static final Logger s_logger = Logger + .getLogger(NfsSecondaryStorageResource.class); + + private static final String TEMPLATE_ROOT_DIR = "template/tmpl"; + private static final String SNAPSHOT_ROOT_DIR = "snapshots"; + int _timeout; String _instance; @@ -167,16 +194,24 @@ public class NfsSecondaryStorageResource extends ServerResourceBase implements S return execute((ListVolumeCommand)cmd); }else if (cmd instanceof downloadSnapshotFromSwiftCommand){ return execute((downloadSnapshotFromSwiftCommand)cmd); + } else if (cmd instanceof DownloadSnapshotFromS3Command) { + return execute((DownloadSnapshotFromS3Command) cmd); } else if (cmd instanceof DeleteSnapshotBackupCommand){ return execute((DeleteSnapshotBackupCommand)cmd); } else if (cmd instanceof DeleteSnapshotsDirCommand){ return execute((DeleteSnapshotsDirCommand)cmd); } else if (cmd instanceof downloadTemplateFromSwiftToSecondaryStorageCommand) { return execute((downloadTemplateFromSwiftToSecondaryStorageCommand) cmd); + } else if (cmd instanceof DownloadTemplateFromS3ToSecondaryStorageCommand) { + return execute((DownloadTemplateFromS3ToSecondaryStorageCommand) cmd); } else if (cmd instanceof uploadTemplateToSwiftFromSecondaryStorageCommand) { return execute((uploadTemplateToSwiftFromSecondaryStorageCommand) cmd); + } else if (cmd instanceof UploadTemplateToS3FromSecondaryStorageCommand) { + return execute((UploadTemplateToS3FromSecondaryStorageCommand) cmd); } else if (cmd instanceof DeleteObjectFromSwiftCommand) { return execute((DeleteObjectFromSwiftCommand) cmd); + } else if (cmd instanceof DeleteTemplateFromS3Command) { + return execute((DeleteTemplateFromS3Command) cmd); } else if (cmd instanceof CleanupSnapshotBackupCommand){ return execute((CleanupSnapshotBackupCommand)cmd); } else { @@ -184,6 +219,69 @@ public class NfsSecondaryStorageResource extends ServerResourceBase implements S } } + @SuppressWarnings("unchecked") + private String determineS3TemplateDirectory(final Long accountId, + final Long templateId) { + return join(asList(TEMPLATE_ROOT_DIR, accountId, templateId), + S3Utils.SEPARATOR); + } + + @SuppressWarnings("unchecked") + private String determineStorageTemplatePath(final String storagePath, + final Long accountId, final Long templateId) { + return join( + asList(getRootDir(storagePath), TEMPLATE_ROOT_DIR, accountId, + templateId), File.separator); + } + + private Answer execute( + final DownloadTemplateFromS3ToSecondaryStorageCommand cmd) { + + final S3TO s3 = cmd.getS3(); + final String storagePath = cmd.getStoragePath(); + final Long accountId = cmd.getAccountId(); + final Long templateId = cmd.getTemplateId(); + + try { + + final File downloadDirectory = _storage + .getFile(determineStorageTemplatePath(storagePath, + accountId, templateId)); + downloadDirectory.mkdirs(); + + if (!downloadDirectory.exists()) { + final String errMsg = format( + "Unable to create directory " + + "download directory %1$s for download of template id " + + "%2$s from S3.", downloadDirectory.getName(), + templateId); + s_logger.error(errMsg); + return new Answer(cmd, false, errMsg); + } + + getDirectory(s3, s3.getBucketName(), + determineS3TemplateDirectory(accountId, templateId), + downloadDirectory, new FileNamingStrategy() { + @Override + public String determineFileName(final String key) { + return substringAfterLast(key, S3Utils.SEPARATOR); + } + }); + + return new Answer(cmd, true, format("Successfully downloaded " + + "template id %1$s from S3 to directory %2$s", templateId, + downloadDirectory.getName())); + + } catch (Exception e) { + + final String errMsg = format("Failed to upload template id %1$s " + + "due to $2%s", templateId, e.getMessage()); + s_logger.error(errMsg, e); + return new Answer(cmd, false, errMsg); + + } + + } private Answer execute(downloadTemplateFromSwiftToSecondaryStorageCommand cmd) { SwiftTO swift = cmd.getSwift(); @@ -255,6 +353,83 @@ public class NfsSecondaryStorageResource extends ServerResourceBase implements S } } + private Answer execute(UploadTemplateToS3FromSecondaryStorageCommand cmd) { + + final S3TO s3 = cmd.getS3(); + final Long accountId = cmd.getAccountId(); + final Long templateId = cmd.getTemplateId(); + + try { + + final String templatePath = determineStorageTemplatePath( + cmd.getStoragePath(), accountId, templateId); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Found template id " + templateId + + " account id " + accountId + " from directory " + + templatePath + " to upload to S3."); + } + + if (!_storage.isDirectory(templatePath)) { + final String errMsg = format("S3 Sync Failure: Directory %1$s" + + "for template id %2$s does not exist.", templatePath, + templateId); + s_logger.error(errMsg); + return new Answer(cmd, false, errMsg); + } + + if (!_storage.isFile(templatePath + "/template.properties")) { + final String errMsg = format("S3 Sync Failure: Template id " + + "%1$s does not exist on the file system.", + templatePath); + s_logger.error(errMsg); + return new Answer(cmd, false, errMsg); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug(format( + "Pushing template id %1$s from %2$s to S3...", + templateId, templatePath)); + } + + final String bucket = s3.getBucketName(); + putDirectory(s3, bucket, _storage.getFile(templatePath), + new FilenameFilter() { + @Override + public boolean accept(final File directory, + final String fileName) { + return !fileName.startsWith("."); + } + }, new ObjectNamingStrategy() { + @Override + public String determineKey(final File file) { + s_logger.debug(String + .format("Determining key using account id %1$s and template id %2$s", + accountId, templateId)); + return join( + asList(determineS3TemplateDirectory( + accountId, templateId), file + .getName()), S3Utils.SEPARATOR); + } + }); + + return new Answer( + cmd, + true, + format("Uploaded the contents of directory %1$s for template id %2$s to S3 bucket %3$s", + templatePath, templateId, bucket)); + + } catch (Exception e) { + + final String errMsg = format("Failed to upload template id %1$s", + templateId); + s_logger.error(errMsg, e); + return new Answer(cmd, false, errMsg); + + } + + } + private Answer execute(DeleteObjectFromSwiftCommand cmd) { SwiftTO swift = cmd.getSwift(); String container = cmd.getContainer(); @@ -278,6 +453,47 @@ public class NfsSecondaryStorageResource extends ServerResourceBase implements S } + private Answer execute(final DeleteTemplateFromS3Command cmd) { + + final S3TO s3 = cmd.getS3(); + final Long accountId = cmd.getAccountId(); + final Long templateId = cmd.getTemplateId(); + + if (accountId == null || (accountId != null && accountId <= 0)) { + final String errorMessage = "No account id specified for S3 template deletion."; + s_logger.error(errorMessage); + return new Answer(cmd, false, errorMessage); + } + + if (templateId == null || (templateId != null && templateId <= 0)) { + final String errorMessage = "No template id specified for S3 template deletion."; + s_logger.error(errorMessage); + return new Answer(cmd, false, errorMessage); + } + + if (s3 == null) { + final String errorMessge = "No S3 client options provided"; + s_logger.error(errorMessge); + return new Answer(cmd, false, errorMessge); + } + + final String bucket = s3.getBucketName(); + try { + deleteDirectory(s3, bucket, + determineS3TemplateDirectory(templateId, accountId)); + return new Answer(cmd, true, String.format( + "Deleted template %1%s from bucket %2$s.", templateId, + bucket)); + } catch (Exception e) { + final String errorMessage = String + .format("Failed to delete templaet id %1$s from bucket %2$s due to the following error: %3$s", + templateId, bucket, e.getMessage()); + s_logger.error(errorMessage, e); + return new Answer(cmd, false, errorMessage); + } + + } + String swiftDownload(SwiftTO swift, String container, String rfilename, String lFullPath) { Script command = new Script("/bin/bash", s_logger); command.add("-c"); @@ -450,6 +666,110 @@ public class NfsSecondaryStorageResource extends ServerResourceBase implements S } } + public Answer execute(final DownloadSnapshotFromS3Command cmd) { + + final S3TO s3 = cmd.getS3(); + final String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); + final Long accountId = cmd.getAccountId(); + final Long volumeId = cmd.getVolumeId(); + + try { + + executeWithNoWaitLock(determineSnapshotLockId(accountId, volumeId), + new Callable() { + + @Override + public Void call() throws Exception { + + final String directoryName = determineSnapshotLocalDirectory( + secondaryStorageUrl, accountId, volumeId); + + String result = createLocalDir(directoryName); + if (result != null) { + throw new InternalErrorException( + format("Failed to create directory %1$s during S3 snapshot download.", + directoryName)); + } + + final String snapshotFileName = determineSnapshotBackupFilename(cmd + .getSnapshotUuid()); + final String key = determineSnapshotS3Key( + accountId, volumeId, snapshotFileName); + final File targetFile = S3Utils.getFile(s3, + s3.getBucketName(), key, + _storage.getFile(directoryName), + new FileNamingStrategy() { + + @Override + public String determineFileName( + String key) { + return snapshotFileName; + } + + }); + + if (cmd.getParent() != null) { + + final String parentPath = join( + File.pathSeparator, directoryName, + determineSnapshotBackupFilename(cmd + .getParent())); + result = setVhdParent( + targetFile.getAbsolutePath(), + parentPath); + if (result != null) { + throw new InternalErrorException( + format("Failed to set the parent for backup %1$s to %2$s due to %3$s.", + targetFile + .getAbsolutePath(), + parentPath, result)); + } + + } + + return null; + + } + + }); + + return new Answer( + cmd, + true, + format("Succesfully retrieved volume id %1$s for account id %2$s to %3$s from S3.", + volumeId, accountId, secondaryStorageUrl)); + + } catch (Exception e) { + final String errMsg = format( + "Failed to retrieve volume id %1$s for account id %2$s to %3$s from S3 due to exception %4$s", + volumeId, accountId, secondaryStorageUrl, e.getMessage()); + s_logger.error(errMsg); + return new Answer(cmd, false, errMsg); + } + + } + + private String determineSnapshotS3Directory(final Long accountId, + final Long volumeId) { + return join(S3Utils.SEPARATOR, SNAPSHOT_ROOT_DIR, accountId, volumeId); + } + + private String determineSnapshotS3Key(final Long accountId, + final Long volumeId, final String snapshotFileName) { + + final String directoryName = determineSnapshotS3Directory(accountId, + volumeId); + return join(S3Utils.SEPARATOR, directoryName, snapshotFileName); + + } + + private String determineSnapshotLocalDirectory( + final String secondaryStorageUrl, final Long accountId, + final Long volumeId) { + return join(File.pathSeparator, getRootDir(secondaryStorageUrl), + SNAPSHOT_ROOT_DIR, accountId, volumeId); + } + public Answer execute(downloadSnapshotFromSwiftCommand cmd){ SwiftTO swift = cmd.getSwift(); String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); @@ -621,6 +941,92 @@ public class NfsSecondaryStorageResource extends ServerResourceBase implements S } } + private String deleteSnapshotBackupFromLocalFileSystem( + final String secondaryStorageUrl, final Long accountId, + final Long volumeId, final String name, final Boolean deleteAllFlag) { + + final String lPath = determineSnapshotLocalDirectory( + secondaryStorageUrl, accountId, volumeId) + + File.pathSeparator + + (deleteAllFlag ? "*" : "*" + name + "*"); + + final String result = deleteLocalFile(lPath); + + if (result != null) { + return "failed to delete snapshot " + lPath + " , err=" + result; + } + + return null; + + } + + private String deleteSnapshotBackupfromS3(final S3TO s3, + final String secondaryStorageUrl, final Long accountId, + final Long volumeId, final String name, final Boolean deleteAllFlag) { + + try { + + final String bucket = s3.getBucketName(); + + final String result = executeWithNoWaitLock( + determineSnapshotLockId(accountId, volumeId), + new Callable() { + + @Override + public String call() throws Exception { + + final String innerResult = deleteSnapshotBackupFromLocalFileSystem( + secondaryStorageUrl, accountId, volumeId, + name, deleteAllFlag); + if (innerResult != null) { + return innerResult; + } + + if (deleteAllFlag) { + S3Utils.deleteDirectory( + s3, + bucket, + determineSnapshotS3Directory(accountId, + volumeId)); + } else { + S3Utils.deleteObject( + s3, + bucket, + determineSnapshotS3Key( + accountId, + volumeId, + determineSnapshotBackupFilename(name))); + } + + return null; + + } + + }); + + return result; + + } catch (Exception e) { + + s_logger.error( + String.format( + "Failed to delete snapshot backup for account id %1$s volume id %2$sfrom S3.", + accountId, volumeId), e); + return e.getMessage(); + + } + + } + + private String determineSnapshotBackupFilename(final String snapshotUuid) { + return snapshotUuid + ".vhd"; + } + + private String determineSnapshotLockId(final Long accountId, + final Long volumeId) { + return join("_", "SNAPSHOT", accountId, volumeId); + } + protected Answer execute(final DeleteSnapshotBackupCommand cmd) { String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); Long accountId = cmd.getAccountId(); @@ -628,21 +1034,22 @@ public class NfsSecondaryStorageResource extends ServerResourceBase implements S String name = cmd.getSnapshotUuid(); try { SwiftTO swift = cmd.getSwift(); + S3TO s3 = cmd.getS3(); if (swift == null) { - String parent = getRootDir(secondaryStorageUrl); - String filename; - if (cmd.isAll()) { - filename = "*"; - - } else { - filename = "*" + name + "*"; - } - String lPath = parent + "/snapshots/" + String.valueOf(accountId) + "/" + String.valueOf(volumeId) + "/" + filename; - String result = deleteLocalFile(lPath); + final String result = deleteSnapshotBackupFromLocalFileSystem( + secondaryStorageUrl, accountId, volumeId, name, + cmd.isAll()); if (result != null) { - String errMsg = "failed to delete snapshot " + lPath + " , err=" + result; - s_logger.warn(errMsg); - return new Answer(cmd, false, errMsg); + s_logger.warn(result); + return new Answer(cmd, false, result); + } + } else if (s3 != null) { + final String result = deleteSnapshotBackupfromS3(s3, + secondaryStorageUrl, accountId, volumeId, name, + cmd.isAll()); + if (result != null) { + s_logger.warn(result); + return new Answer(cmd, false, result); } } else { String filename; diff --git a/deps/XenServerJava/src/com/xensource/xenapi/APIVersion.java b/deps/XenServerJava/src/com/xensource/xenapi/APIVersion.java index 763b98f2260..174cf5ad581 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/APIVersion.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/APIVersion.java @@ -1,18 +1,18 @@ /* Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -31,16 +31,28 @@ package com.xensource.xenapi; public enum APIVersion { - API_1_1, API_1_2, API_1_3, API_1_4, API_1_5, API_1_6, API_1_7, UNKNOWN; + API_1_1, API_1_2, API_1_3, API_1_4, API_1_5, API_1_6, API_1_7, API_1_8, API_1_9, API_1_10, UNKNOWN; public static APIVersion latest() { - return API_1_7; + return API_1_10; } public static APIVersion fromMajorMinor(long major, long minor) { - if (major == 1 && minor == 7) + if (major == 1 && minor == 10) + { + return API_1_10; + } + else if (major == 1 && minor == 9) + { + return API_1_9; + } + else if (major == 1 && minor == 8) + { + return API_1_8; + } + else if (major == 1 && minor == 7) { return API_1_7; } @@ -93,6 +105,12 @@ public enum APIVersion return "1.6"; case API_1_7: return "1.7"; + case API_1_8: + return "1.8"; + case API_1_9: + return "1.9"; + case API_1_10: + return "1.10"; default: return "Unknown"; } diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Auth.java b/deps/XenServerJava/src/com/xensource/xenapi/Auth.java index 1bf615e1ea4..fd84390d2a5 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Auth.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Auth.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -109,4 +111,4 @@ public class Auth extends XenAPIObject { return Types.toSetOfString(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Blob.java b/deps/XenServerJava/src/com/xensource/xenapi/Blob.java index 7d3ad582264..eeff12e709b 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Blob.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Blob.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Blob extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Blob extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -99,6 +104,7 @@ public class Blob extends XenAPIObject { print.printf("%1$20s: %2$s\n", "nameLabel", this.nameLabel); print.printf("%1$20s: %2$s\n", "nameDescription", this.nameDescription); print.printf("%1$20s: %2$s\n", "size", this.size); + print.printf("%1$20s: %2$s\n", "_public", this._public); print.printf("%1$20s: %2$s\n", "lastUpdated", this.lastUpdated); print.printf("%1$20s: %2$s\n", "mimeType", this.mimeType); return writer.toString(); @@ -113,6 +119,7 @@ public class Blob extends XenAPIObject { map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); map.put("size", this.size == null ? 0 : this.size); + map.put("public", this._public == null ? false : this._public); map.put("last_updated", this.lastUpdated == null ? new Date(0) : this.lastUpdated); map.put("mime_type", this.mimeType == null ? "" : this.mimeType); return map; @@ -127,13 +134,17 @@ public class Blob extends XenAPIObject { */ public String nameLabel; /** - * a notes field containg human-readable description + * a notes field containing human-readable description */ public String nameDescription; /** * Size of the binary data, in bytes */ public Long size; + /** + * True if the blob is publicly accessible + */ + public Boolean _public; /** * Time at which the data in the blob was last updated */ @@ -265,6 +276,23 @@ public class Blob extends XenAPIObject { return Types.toLong(result); } + /** + * Get the public field of the given blob. + * + * @return value of the field + */ + public Boolean getPublic(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "blob.get_public"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toBoolean(result); + } + /** * Get the last_updated field of the given blob. * @@ -331,26 +359,43 @@ public class Blob extends XenAPIObject { return; } + /** + * Set the public field of the given blob. + * + * @param _public New value to set + */ + public void setPublic(Connection c, Boolean _public) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "blob.set_public"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(_public)}; + Map response = c.dispatch(method_call, method_params); + return; + } + /** * Create a placeholder for a binary blob * * @param mimeType The mime-type of the blob. Defaults to 'application/octet-stream' if the empty string is supplied + * @param _public True if the blob should be publicly available * @return The reference to the created blob */ - public static Blob create(Connection c, String mimeType) throws + public static Blob create(Connection c, String mimeType, Boolean _public) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "blob.create"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(mimeType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toBlob(result); } /** - * + * * */ public void destroy(Connection c) throws @@ -398,4 +443,4 @@ public class Blob extends XenAPIObject { return Types.toMapOfBlobBlobRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Bond.java b/deps/XenServerJava/src/com/xensource/xenapi/Bond.java index ee67e3c49e0..d9d30459e6e 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Bond.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Bond.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -44,14 +46,14 @@ import java.util.Set; import org.apache.xmlrpc.XmlRpcException; /** - * + * * * @author Citrix Systems, Inc. */ public class Bond extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Bond extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -99,6 +104,10 @@ public class Bond extends XenAPIObject { print.printf("%1$20s: %2$s\n", "master", this.master); print.printf("%1$20s: %2$s\n", "slaves", this.slaves); print.printf("%1$20s: %2$s\n", "otherConfig", this.otherConfig); + print.printf("%1$20s: %2$s\n", "primarySlave", this.primarySlave); + print.printf("%1$20s: %2$s\n", "mode", this.mode); + print.printf("%1$20s: %2$s\n", "properties", this.properties); + print.printf("%1$20s: %2$s\n", "linksUp", this.linksUp); return writer.toString(); } @@ -111,6 +120,10 @@ public class Bond extends XenAPIObject { map.put("master", this.master == null ? new PIF("OpaqueRef:NULL") : this.master); map.put("slaves", this.slaves == null ? new LinkedHashSet() : this.slaves); map.put("other_config", this.otherConfig == null ? new HashMap() : this.otherConfig); + map.put("primary_slave", this.primarySlave == null ? new PIF("OpaqueRef:NULL") : this.primarySlave); + map.put("mode", this.mode == null ? Types.BondMode.UNRECOGNIZED : this.mode); + map.put("properties", this.properties == null ? new HashMap() : this.properties); + map.put("links_up", this.linksUp == null ? 0 : this.linksUp); return map; } @@ -130,6 +143,22 @@ public class Bond extends XenAPIObject { * additional configuration */ public Map otherConfig; + /** + * The PIF of which the IP configuration and MAC were copied to the bond, and which will receive all configuration/VLANs/VIFs on the bond if the bond is destroyed + */ + public PIF primarySlave; + /** + * The algorithm used to distribute traffic among the bonded NICs + */ + public Types.BondMode mode; + /** + * Additional configuration properties specific to the bond mode. + */ + public Map properties; + /** + * Number of links up in this bond + */ + public Long linksUp; } /** @@ -235,6 +264,74 @@ public class Bond extends XenAPIObject { return Types.toMapOfStringString(result); } + /** + * Get the primary_slave field of the given Bond. + * + * @return value of the field + */ + public PIF getPrimarySlave(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Bond.get_primary_slave"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toPIF(result); + } + + /** + * Get the mode field of the given Bond. + * + * @return value of the field + */ + public Types.BondMode getMode(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Bond.get_mode"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toBondMode(result); + } + + /** + * Get the properties field of the given Bond. + * + * @return value of the field + */ + public Map getProperties(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Bond.get_properties"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfStringString(result); + } + + /** + * Get the links_up field of the given Bond. + * + * @return value of the field + */ + public Long getLinksUp(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Bond.get_links_up"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toLong(result); + } + /** * Set the other_config field of the given Bond. * @@ -289,16 +386,18 @@ public class Bond extends XenAPIObject { * * @param network Network to add the bonded PIF to * @param members PIFs to add to this bond - * @param MAC The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the first of the specified 'members' + * @param MAC The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave. + * @param mode Bonding mode to use for the new bond + * @param properties Additional configuration parameters specific to the bond mode * @return Task */ - public static Task createAsync(Connection c, Network network, Set members, String MAC) throws + public static Task createAsync(Connection c, Network network, Set members, String MAC, Types.BondMode mode, Map properties) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "Async.Bond.create"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(members), Marshalling.toXMLRPC(MAC)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(members), Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(properties)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -309,16 +408,18 @@ public class Bond extends XenAPIObject { * * @param network Network to add the bonded PIF to * @param members PIFs to add to this bond - * @param MAC The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the first of the specified 'members' + * @param MAC The MAC address to use on the bond itself. If this parameter is the empty string then the bond will inherit its MAC address from the primary slave. + * @param mode Bonding mode to use for the new bond + * @param properties Additional configuration parameters specific to the bond mode * @return The reference of the created Bond object */ - public static Bond create(Connection c, Network network, Set members, String MAC) throws + public static Bond create(Connection c, Network network, Set members, String MAC, Types.BondMode mode, Map properties) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "Bond.create"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(members), Marshalling.toXMLRPC(MAC)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(members), Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(properties)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toBond(result); @@ -356,6 +457,76 @@ public class Bond extends XenAPIObject { return; } + /** + * Change the bond mode + * + * @param value The new bond mode + * @return Task + */ + public Task setModeAsync(Connection c, Types.BondMode value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.Bond.set_mode"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Change the bond mode + * + * @param value The new bond mode + */ + public void setMode(Connection c, Types.BondMode value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Bond.set_mode"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Set the value of a property of the bond + * + * @param name The property name + * @param value The property value + * @return Task + */ + public Task setPropertyAsync(Connection c, String name, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.Bond.set_property"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Set the value of a property of the bond + * + * @param name The property name + * @param value The property value + */ + public void setProperty(Connection c, String name, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Bond.set_property"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + /** * Return a list of all the Bonds known to the system. * @@ -390,4 +561,4 @@ public class Bond extends XenAPIObject { return Types.toMapOfBondBondRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Connection.java b/deps/XenServerJava/src/com/xensource/xenapi/Connection.java index 6c205a2a605..22f64d34fd3 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Connection.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Connection.java @@ -1,18 +1,18 @@ /* Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -54,11 +54,11 @@ public class Connection /** * The version of the bindings that this class belongs to. */ - public static final String BINDINGS_VERSION = "5.6.100-1"; - + public static final String BINDINGS_VERSION = "6.1.0-1"; + /** * true if the connection is to the Rio edition of XenServer. Certain function calls are not allowed. - * + * * @deprecated Use getAPIVersion() instead. */ @Deprecated @@ -91,12 +91,12 @@ public class Connection /** * Creates a connection to a particular server using a given username and password. This object can then be passed * in to any other API calls. - * + * * This constructor calls Session.loginWithPassword, passing itself as the first parameter. - * + * * When this constructor is used, a call to dispose() (also called in the Connection's finalizer) will attempt a * Session.logout on this connection. - * + * * @deprecated Use a constructor that takes a URL as the first parameter instead. */ @Deprecated @@ -155,10 +155,10 @@ public class Connection /** * Creates a connection to a particular server using a given username and password. This object can then be passed * in to any other API calls. - * + * * Note this constructor does NOT call Session.loginWithPassword; the programmer is responsible for calling it, * passing the Connection as a parameter. No attempt to connect to the server is made until login is called. - * + * * When this constructor is used, a call to dispose() will do nothing. The programmer is responsible for manually * logging out the Session. */ @@ -172,7 +172,7 @@ public class Connection /** * Creates a connection to a particular server using a given username and password. This object can then be passed * in to any other API calls. - * + * * The additional sessionReference parameter must be a reference to a logged-in Session. Any method calls on this * Connection will use it. This constructor does not call Session.loginWithPassword, and dispose() on the resulting * Connection object does not call Session.logout. The programmer is responsible for ensuring the Session is logged @@ -285,7 +285,7 @@ public class Connection } /* - * Because the binding calls are constructing their own parameter lists, they need to be able to get to + * Because the binding calls are constructing their own parameter lists, they need to be able to get to * the session reference directly. This is all rather ugly and needs redone * Changed to public to allow easier integration with HTTP-level streaming interface, * see CA-15447 @@ -310,17 +310,17 @@ public class Connection response.get("Status").equals("Success")) { // Store the Session reference and ask the server what the - // API version it's using is. + // API version it's using is. Session session = Types.toSession(response.get("Value")); - sessionReference = session.ref; + sessionReference = session.ref; setAPIVersion(session); } else if (method_call.equals("session.slave_local_login_with_password") && response.get("Status").equals("Success")) { - // Store the Session reference and assume API version 1.2. + // Store the Session reference and assume the latest API version. sessionReference = Types.toSession(response.get("Value")).ref; - apiVersion = APIVersion.API_1_2; + apiVersion = APIVersion.latest(); } else if (method_call.equals("session.logout")) { diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Console.java b/deps/XenServerJava/src/com/xensource/xenapi/Console.java index e73e685a468..c734a839629 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Console.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Console.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Console extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Console extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -411,4 +416,4 @@ public class Console extends XenAPIObject { return Types.toMapOfConsoleConsoleRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Crashdump.java b/deps/XenServerJava/src/com/xensource/xenapi/Crashdump.java index 31cf4180c9f..d1187bb4a7a 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Crashdump.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Crashdump.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Crashdump extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Crashdump extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -350,4 +355,4 @@ public class Crashdump extends XenAPIObject { return Types.toMapOfCrashdumpCrashdumpRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/DRTask.java b/deps/XenServerJava/src/com/xensource/xenapi/DRTask.java new file mode 100644 index 00000000000..9694faa3c3c --- /dev/null +++ b/deps/XenServerJava/src/com/xensource/xenapi/DRTask.java @@ -0,0 +1,303 @@ +/* + * Copyright (c) Citrix Systems, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1) Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2) Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +package com.xensource.xenapi; + +import com.xensource.xenapi.Types.BadServerResponse; +import com.xensource.xenapi.Types.VersionException; +import com.xensource.xenapi.Types.XenAPIException; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.xmlrpc.XmlRpcException; + +/** + * DR task + * + * @author Citrix Systems, Inc. + */ +public class DRTask extends XenAPIObject { + + /** + * The XenAPI reference (OpaqueRef) to this object. + */ + protected final String ref; + + /** + * For internal use only. + */ + DRTask(String ref) { + this.ref = ref; + } + + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ + public String toWireString() { + return this.ref; + } + + /** + * If obj is a DRTask, compares XenAPI references for equality. + */ + @Override + public boolean equals(Object obj) + { + if (obj != null && obj instanceof DRTask) + { + DRTask other = (DRTask) obj; + return other.ref.equals(this.ref); + } else + { + return false; + } + } + + @Override + public int hashCode() + { + return ref.hashCode(); + } + + /** + * Represents all the fields in a DRTask + */ + public static class Record implements Types.Record { + public String toString() { + StringWriter writer = new StringWriter(); + PrintWriter print = new PrintWriter(writer); + print.printf("%1$20s: %2$s\n", "uuid", this.uuid); + print.printf("%1$20s: %2$s\n", "introducedSRs", this.introducedSRs); + return writer.toString(); + } + + /** + * Convert a DR_task.Record to a Map + */ + public Map toMap() { + Map map = new HashMap(); + map.put("uuid", this.uuid == null ? "" : this.uuid); + map.put("introduced_SRs", this.introducedSRs == null ? new LinkedHashSet() : this.introducedSRs); + return map; + } + + /** + * Unique identifier/object reference + */ + public String uuid; + /** + * All SRs introduced by this appliance + */ + public Set introducedSRs; + } + + /** + * Get a record containing the current state of the given DR_task. + * + * @return all fields from the object + */ + public DRTask.Record getRecord(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "DR_task.get_record"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toDRTaskRecord(result); + } + + /** + * Get a reference to the DR_task instance with the specified UUID. + * + * @param uuid UUID of object to return + * @return reference to the object + */ + public static DRTask getByUuid(Connection c, String uuid) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "DR_task.get_by_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toDRTask(result); + } + + /** + * Get the uuid field of the given DR_task. + * + * @return value of the field + */ + public String getUuid(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "DR_task.get_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the introduced_SRs field of the given DR_task. + * + * @return value of the field + */ + public Set getIntroducedSRs(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "DR_task.get_introduced_SRs"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfSR(result); + } + + /** + * Create a disaster recovery task which will query the supplied list of devices + * + * @param type The SR driver type of the SRs to introduce + * @param deviceConfig The device configuration of the SRs to introduce + * @param whitelist The devices to use for disaster recovery + * @return Task + */ + public static Task createAsync(Connection c, String type, Map deviceConfig, Set whitelist) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.DR_task.create"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(whitelist)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Create a disaster recovery task which will query the supplied list of devices + * + * @param type The SR driver type of the SRs to introduce + * @param deviceConfig The device configuration of the SRs to introduce + * @param whitelist The devices to use for disaster recovery + * @return The reference to the created task + */ + public static DRTask create(Connection c, String type, Map deviceConfig, Set whitelist) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "DR_task.create"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(deviceConfig), Marshalling.toXMLRPC(whitelist)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toDRTask(result); + } + + /** + * Destroy the disaster recovery task, detaching and forgetting any SRs introduced which are no longer required + * + * @return Task + */ + public Task destroyAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.DR_task.destroy"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Destroy the disaster recovery task, detaching and forgetting any SRs introduced which are no longer required + * + */ + public void destroy(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "DR_task.destroy"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Return a list of all the DR_tasks known to the system. + * + * @return references to all objects + */ + public static Set getAll(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "DR_task.get_all"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfDRTask(result); + } + + /** + * Return a map of DR_task references to DR_task records for all DR_tasks known to the system. + * + * @return records of all objects + */ + public static Map getAllRecords(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "DR_task.get_all_records"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfDRTaskDRTaskRecord(result); + } + +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/DataSource.java b/deps/XenServerJava/src/com/xensource/xenapi/DataSource.java index aebe39b7b1e..a0f46fb4fe8 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/DataSource.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/DataSource.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class DataSource extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class DataSource extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -127,7 +132,7 @@ public class DataSource extends XenAPIObject { */ public String nameLabel; /** - * a notes field containg human-readable description + * a notes field containing human-readable description */ public String nameDescription; /** @@ -156,4 +161,4 @@ public class DataSource extends XenAPIObject { public Double value; } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Event.java b/deps/XenServerJava/src/com/xensource/xenapi/Event.java index 36ebf457abf..3574cd19b0f 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Event.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Event.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Event extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Event extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -152,7 +157,7 @@ public class Event extends XenAPIObject { } /** - * Registers this session with the event system. Specifying the empty list will register for all classes. + * Registers this session with the event system. Specifying * as the desired class will register for all classes. * * @param classes register for events for the indicated classes * @return Task @@ -170,7 +175,7 @@ public class Event extends XenAPIObject { } /** - * Registers this session with the event system. Specifying the empty list will register for all classes. + * Registers this session with the event system. Specifying * as the desired class will register for all classes. * * @param classes register for events for the indicated classes */ @@ -238,6 +243,28 @@ public class Event extends XenAPIObject { return Types.toSetOfEventRecord(result); } + /** + * Blocking call which returns a (possibly empty) batch of events + * + * @param classes register for events for the indicated classes + * @param token A token representing the point from which to generate database events. The empty string represents the beginning. + * @param timeout Return after this many seconds if no events match + * @return the batch of events + */ + public static Set from(Connection c, Set classes, String token, Double timeout) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.SessionNotRegistered, + Types.EventsLost { + String method_call = "event.from"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(classes), Marshalling.toXMLRPC(token), Marshalling.toXMLRPC(timeout)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfEventRecord(result); + } + /** * Return the ID of the next event to be generated by the system * @@ -255,4 +282,23 @@ public class Event extends XenAPIObject { return Types.toLong(result); } -} + /** + * Injects an artificial event on the given object and return the corresponding ID + * + * @param clazz class of the object + * @param ref A reference to the object that will be changed. + * @return the event ID + */ + public static String inject(Connection c, String clazz, String ref) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "event.inject"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(clazz), Marshalling.toXMLRPC(ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/GPUGroup.java b/deps/XenServerJava/src/com/xensource/xenapi/GPUGroup.java new file mode 100644 index 00000000000..fbd7d7d59dd --- /dev/null +++ b/deps/XenServerJava/src/com/xensource/xenapi/GPUGroup.java @@ -0,0 +1,445 @@ +/* + * Copyright (c) Citrix Systems, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1) Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2) Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +package com.xensource.xenapi; + +import com.xensource.xenapi.Types.BadServerResponse; +import com.xensource.xenapi.Types.VersionException; +import com.xensource.xenapi.Types.XenAPIException; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.xmlrpc.XmlRpcException; + +/** + * A group of compatible GPUs across the resource pool + * + * @author Citrix Systems, Inc. + */ +public class GPUGroup extends XenAPIObject { + + /** + * The XenAPI reference (OpaqueRef) to this object. + */ + protected final String ref; + + /** + * For internal use only. + */ + GPUGroup(String ref) { + this.ref = ref; + } + + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ + public String toWireString() { + return this.ref; + } + + /** + * If obj is a GPUGroup, compares XenAPI references for equality. + */ + @Override + public boolean equals(Object obj) + { + if (obj != null && obj instanceof GPUGroup) + { + GPUGroup other = (GPUGroup) obj; + return other.ref.equals(this.ref); + } else + { + return false; + } + } + + @Override + public int hashCode() + { + return ref.hashCode(); + } + + /** + * Represents all the fields in a GPUGroup + */ + public static class Record implements Types.Record { + public String toString() { + StringWriter writer = new StringWriter(); + PrintWriter print = new PrintWriter(writer); + print.printf("%1$20s: %2$s\n", "uuid", this.uuid); + print.printf("%1$20s: %2$s\n", "nameLabel", this.nameLabel); + print.printf("%1$20s: %2$s\n", "nameDescription", this.nameDescription); + print.printf("%1$20s: %2$s\n", "PGPUs", this.PGPUs); + print.printf("%1$20s: %2$s\n", "VGPUs", this.VGPUs); + print.printf("%1$20s: %2$s\n", "GPUTypes", this.GPUTypes); + print.printf("%1$20s: %2$s\n", "otherConfig", this.otherConfig); + return writer.toString(); + } + + /** + * Convert a GPU_group.Record to a Map + */ + public Map toMap() { + Map map = new HashMap(); + map.put("uuid", this.uuid == null ? "" : this.uuid); + map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); + map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); + map.put("PGPUs", this.PGPUs == null ? new LinkedHashSet() : this.PGPUs); + map.put("VGPUs", this.VGPUs == null ? new LinkedHashSet() : this.VGPUs); + map.put("GPU_types", this.GPUTypes == null ? new LinkedHashSet() : this.GPUTypes); + map.put("other_config", this.otherConfig == null ? new HashMap() : this.otherConfig); + return map; + } + + /** + * Unique identifier/object reference + */ + public String uuid; + /** + * a human-readable name + */ + public String nameLabel; + /** + * a notes field containing human-readable description + */ + public String nameDescription; + /** + * List of pGPUs in the group + */ + public Set PGPUs; + /** + * List of vGPUs using the group + */ + public Set VGPUs; + /** + * List of GPU types (vendor+device ID) that can be in this group + */ + public Set GPUTypes; + /** + * Additional configuration + */ + public Map otherConfig; + } + + /** + * Get a record containing the current state of the given GPU_group. + * + * @return all fields from the object + */ + public GPUGroup.Record getRecord(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.get_record"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toGPUGroupRecord(result); + } + + /** + * Get a reference to the GPU_group instance with the specified UUID. + * + * @param uuid UUID of object to return + * @return reference to the object + */ + public static GPUGroup getByUuid(Connection c, String uuid) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.get_by_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toGPUGroup(result); + } + + /** + * Get all the GPU_group instances with the given label. + * + * @param label label of object to return + * @return references to objects with matching names + */ + public static Set getByNameLabel(Connection c, String label) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.get_by_name_label"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfGPUGroup(result); + } + + /** + * Get the uuid field of the given GPU_group. + * + * @return value of the field + */ + public String getUuid(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.get_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the name/label field of the given GPU_group. + * + * @return value of the field + */ + public String getNameLabel(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.get_name_label"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the name/description field of the given GPU_group. + * + * @return value of the field + */ + public String getNameDescription(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.get_name_description"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the PGPUs field of the given GPU_group. + * + * @return value of the field + */ + public Set getPGPUs(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.get_PGPUs"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfPGPU(result); + } + + /** + * Get the VGPUs field of the given GPU_group. + * + * @return value of the field + */ + public Set getVGPUs(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.get_VGPUs"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfVGPU(result); + } + + /** + * Get the GPU_types field of the given GPU_group. + * + * @return value of the field + */ + public Set getGPUTypes(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.get_GPU_types"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfString(result); + } + + /** + * Get the other_config field of the given GPU_group. + * + * @return value of the field + */ + public Map getOtherConfig(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.get_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfStringString(result); + } + + /** + * Set the name/label field of the given GPU_group. + * + * @param label New value to set + */ + public void setNameLabel(Connection c, String label) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.set_name_label"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(label)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Set the name/description field of the given GPU_group. + * + * @param description New value to set + */ + public void setNameDescription(Connection c, String description) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.set_name_description"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(description)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Set the other_config field of the given GPU_group. + * + * @param otherConfig New value to set + */ + public void setOtherConfig(Connection c, Map otherConfig) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.set_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Add the given key-value pair to the other_config field of the given GPU_group. + * + * @param key Key to add + * @param value Value to add + */ + public void addToOtherConfig(Connection c, String key, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.add_to_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Remove the given key and its corresponding value from the other_config field of the given GPU_group. If the key is not in that Map, then do nothing. + * + * @param key Key to remove + */ + public void removeFromOtherConfig(Connection c, String key) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.remove_from_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Return a list of all the GPU_groups known to the system. + * + * @return references to all objects + */ + public static Set getAll(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.get_all"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfGPUGroup(result); + } + + /** + * Return a map of GPU_group references to GPU_group records for all GPU_groups known to the system. + * + * @return records of all objects + */ + public static Map getAllRecords(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "GPU_group.get_all_records"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfGPUGroupGPUGroupRecord(result); + } + +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Host.java b/deps/XenServerJava/src/com/xensource/xenapi/Host.java index d17609838cb..2368930b55b 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Host.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Host.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Host extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Host extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -139,6 +144,9 @@ public class Host extends XenAPIObject { print.printf("%1$20s: %2$s\n", "powerOnMode", this.powerOnMode); print.printf("%1$20s: %2$s\n", "powerOnConfig", this.powerOnConfig); print.printf("%1$20s: %2$s\n", "localCacheSr", this.localCacheSr); + print.printf("%1$20s: %2$s\n", "chipsetInfo", this.chipsetInfo); + print.printf("%1$20s: %2$s\n", "PCIs", this.PCIs); + print.printf("%1$20s: %2$s\n", "PGPUs", this.PGPUs); return writer.toString(); } @@ -191,6 +199,9 @@ public class Host extends XenAPIObject { map.put("power_on_mode", this.powerOnMode == null ? "" : this.powerOnMode); map.put("power_on_config", this.powerOnConfig == null ? new HashMap() : this.powerOnConfig); map.put("local_cache_sr", this.localCacheSr == null ? new SR("OpaqueRef:NULL") : this.localCacheSr); + map.put("chipset_info", this.chipsetInfo == null ? new HashMap() : this.chipsetInfo); + map.put("PCIs", this.PCIs == null ? new LinkedHashSet() : this.PCIs); + map.put("PGPUs", this.PGPUs == null ? new LinkedHashSet() : this.PGPUs); return map; } @@ -203,7 +214,7 @@ public class Host extends XenAPIObject { */ public String nameLabel; /** - * a notes field containg human-readable description + * a notes field containing human-readable description */ public String nameDescription; /** @@ -370,6 +381,18 @@ public class Host extends XenAPIObject { * The SR that is used as a local cache */ public SR localCacheSr; + /** + * Information about chipset features + */ + public Map chipsetInfo; + /** + * List of PCI devices in the host + */ + public Set PCIs; + /** + * List of physical GPUs in the host + */ + public Set PGPUs; } /** @@ -1173,6 +1196,57 @@ public class Host extends XenAPIObject { return Types.toSR(result); } + /** + * Get the chipset_info field of the given host. + * + * @return value of the field + */ + public Map getChipsetInfo(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "host.get_chipset_info"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfStringString(result); + } + + /** + * Get the PCIs field of the given host. + * + * @return value of the field + */ + public Set getPCIs(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "host.get_PCIs"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfPCI(result); + } + + /** + * Get the PGPUs field of the given host. + * + * @return value of the field + */ + public Set getPGPUs(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "host.get_PGPUs"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfPGPU(result); + } + /** * Set the name/label field of the given host. * @@ -1897,7 +1971,7 @@ public class Host extends XenAPIObject { } /** - * + * * * @return A set of data sources */ @@ -2031,10 +2105,11 @@ public class Host extends XenAPIObject { /** * Return a set of VMs which are not co-operating with the host's memory control system + * @deprecated * * @return Task */ - public Task getUncooperativeResidentVMsAsync(Connection c) throws + @Deprecated public Task getUncooperativeResidentVMsAsync(Connection c) throws BadServerResponse, XenAPIException, XmlRpcException { @@ -2048,10 +2123,11 @@ public class Host extends XenAPIObject { /** * Return a set of VMs which are not co-operating with the host's memory control system + * @deprecated * * @return VMs which are not co-operating */ - public Set getUncooperativeResidentVMs(Connection c) throws + @Deprecated public Set getUncooperativeResidentVMs(Connection c) throws BadServerResponse, XenAPIException, XmlRpcException { @@ -2193,7 +2269,41 @@ public class Host extends XenAPIObject { } /** - * + * Returns the management interface for the specified host + * + * @return Task + */ + public Task getManagementIfaceAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.host.get_management_interface"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Returns the management interface for the specified host + * + * @return The managment interface for the host + */ + public PIF getManagementIface(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "host.get_management_interface"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toPIF(result); + } + + /** + * * * @return An XML fragment containing the system status capabilities. */ @@ -2377,15 +2487,16 @@ public class Host extends XenAPIObject { * * @param name The name associated with the blob * @param mimeType The mime type for the data. Empty string translates to application/octet-stream + * @param _public True if the blob should be publicly available * @return Task */ - public Task createNewBlobAsync(Connection c, String name, String mimeType) throws + public Task createNewBlobAsync(Connection c, String name, String mimeType, Boolean _public) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "Async.host.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -2396,15 +2507,16 @@ public class Host extends XenAPIObject { * * @param name The name associated with the blob * @param mimeType The mime type for the data. Empty string translates to application/octet-stream + * @param _public True if the blob should be publicly available * @return The reference of the blob, needed for populating its data */ - public Blob createNewBlob(Connection c, String name, String mimeType) throws + public Blob createNewBlob(Connection c, String name, String mimeType, Boolean _public) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "host.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toBlob(result); @@ -2635,7 +2747,7 @@ public class Host extends XenAPIObject { } /** - * Set the power-on-mode, host, user and password + * Set the power-on-mode, host, user and password * * @param powerOnMode power-on-mode can be empty,iLO,wake-on-lan, DRAC or other * @param powerOnConfig Power on config @@ -2654,7 +2766,7 @@ public class Host extends XenAPIObject { } /** - * Set the power-on-mode, host, user and password + * Set the power-on-mode, host, user and password * * @param powerOnMode power-on-mode can be empty,iLO,wake-on-lan, DRAC or other * @param powerOnConfig Power on config @@ -2732,6 +2844,44 @@ public class Host extends XenAPIObject { return; } + /** + * Prepare to receive a VM, returning a token which can be passed to VM.migrate. + * + * @param network The network through which migration traffic should be received. + * @param options Extra configuration operations + * @return Task + */ + public Task migrateReceiveAsync(Connection c, Network network, Map options) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.host.migrate_receive"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(options)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Prepare to receive a VM, returning a token which can be passed to VM.migrate. + * + * @param network The network through which migration traffic should be received. + * @param options Extra configuration operations + * @return A value which should be passed to VM.migrate + */ + public Map migrateReceive(Connection c, Network network, Map options) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "host.migrate_receive"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(options)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfStringString(result); + } + /** * Return a list of all the hosts known to the system. * @@ -2766,4 +2916,4 @@ public class Host extends XenAPIObject { return Types.toMapOfHostHostRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/HostCpu.java b/deps/XenServerJava/src/com/xensource/xenapi/HostCpu.java index 7c7809e0897..4f4cdbc7296 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/HostCpu.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/HostCpu.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class HostCpu extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class HostCpu extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -528,4 +533,4 @@ public class HostCpu extends XenAPIObject { return Types.toMapOfHostCpuHostCpuRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/HostCrashdump.java b/deps/XenServerJava/src/com/xensource/xenapi/HostCrashdump.java index b166073185d..f63479054a3 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/HostCrashdump.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/HostCrashdump.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class HostCrashdump extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class HostCrashdump extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -409,4 +414,4 @@ public class HostCrashdump extends XenAPIObject { return Types.toMapOfHostCrashdumpHostCrashdumpRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/HostMetrics.java b/deps/XenServerJava/src/com/xensource/xenapi/HostMetrics.java index 2a682c806d5..5c7c7805902 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/HostMetrics.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/HostMetrics.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class HostMetrics extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class HostMetrics extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -365,4 +370,4 @@ public class HostMetrics extends XenAPIObject { return Types.toMapOfHostMetricsHostMetricsRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/HostPatch.java b/deps/XenServerJava/src/com/xensource/xenapi/HostPatch.java index b871ed90c85..fafe4377f42 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/HostPatch.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/HostPatch.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class HostPatch extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class HostPatch extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -135,7 +140,7 @@ public class HostPatch extends XenAPIObject { */ public String nameLabel; /** - * a notes field containg human-readable description + * a notes field containing human-readable description */ public String nameDescription; /** @@ -544,4 +549,4 @@ public class HostPatch extends XenAPIObject { return Types.toMapOfHostPatchHostPatchRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Marshalling.java b/deps/XenServerJava/src/com/xensource/xenapi/Marshalling.java index 2603381c643..416aad94b9e 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Marshalling.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Marshalling.java @@ -1,18 +1,18 @@ /* Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Message.java b/deps/XenServerJava/src/com/xensource/xenapi/Message.java index d7b50360699..95bcc8fa107 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Message.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Message.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Message extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Message extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -151,7 +156,7 @@ public class Message extends XenAPIObject { } /** - * + * * * @param name The name of the message * @param priority The priority of the message @@ -173,7 +178,7 @@ public class Message extends XenAPIObject { } /** - * + * * */ public void destroy(Connection c) throws @@ -188,7 +193,7 @@ public class Message extends XenAPIObject { } /** - * + * * * @param cls The class of object * @param objUuid The uuid of the object @@ -208,7 +213,7 @@ public class Message extends XenAPIObject { } /** - * + * * * @return The references to the messages */ @@ -225,7 +230,7 @@ public class Message extends XenAPIObject { } /** - * + * * * @param since The cutoff time * @return The relevant messages @@ -243,7 +248,7 @@ public class Message extends XenAPIObject { } /** - * + * * * @return The message record */ @@ -260,7 +265,7 @@ public class Message extends XenAPIObject { } /** - * + * * * @param uuid The uuid of the message * @return The message reference @@ -278,7 +283,7 @@ public class Message extends XenAPIObject { } /** - * + * * * @return The messages */ @@ -295,7 +300,7 @@ public class Message extends XenAPIObject { } /** - * + * * * @param expr The expression to match (not currently used) * @return The messages @@ -312,4 +317,4 @@ public class Message extends XenAPIObject { return Types.toMapOfMessageMessageRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Network.java b/deps/XenServerJava/src/com/xensource/xenapi/Network.java index 7b1282d5ffc..1b23afeee4d 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Network.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Network.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Network extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Network extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -107,6 +112,7 @@ public class Network extends XenAPIObject { print.printf("%1$20s: %2$s\n", "bridge", this.bridge); print.printf("%1$20s: %2$s\n", "blobs", this.blobs); print.printf("%1$20s: %2$s\n", "tags", this.tags); + print.printf("%1$20s: %2$s\n", "defaultLockingMode", this.defaultLockingMode); return writer.toString(); } @@ -127,6 +133,7 @@ public class Network extends XenAPIObject { map.put("bridge", this.bridge == null ? "" : this.bridge); map.put("blobs", this.blobs == null ? new HashMap() : this.blobs); map.put("tags", this.tags == null ? new LinkedHashSet() : this.tags); + map.put("default_locking_mode", this.defaultLockingMode == null ? Types.NetworkDefaultLockingMode.UNRECOGNIZED : this.defaultLockingMode); return map; } @@ -139,7 +146,7 @@ public class Network extends XenAPIObject { */ public String nameLabel; /** - * a notes field containg human-readable description + * a notes field containing human-readable description */ public String nameDescription; /** @@ -178,6 +185,10 @@ public class Network extends XenAPIObject { * user-specified tags for categorization purposes */ public Set tags; + /** + * The network will use this value to determine the behaviour of all VIFs where locking_mode = default + */ + public Types.NetworkDefaultLockingMode defaultLockingMode; } /** @@ -507,6 +518,23 @@ public class Network extends XenAPIObject { return Types.toSetOfString(result); } + /** + * Get the default_locking_mode field of the given network. + * + * @return value of the field + */ + public Types.NetworkDefaultLockingMode getDefaultLockingMode(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "network.get_default_locking_mode"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toNetworkDefaultLockingMode(result); + } + /** * Set the name/label field of the given network. * @@ -657,15 +685,16 @@ public class Network extends XenAPIObject { * * @param name The name associated with the blob * @param mimeType The mime type for the data. Empty string translates to application/octet-stream + * @param _public True if the blob should be publicly available * @return Task */ - public Task createNewBlobAsync(Connection c, String name, String mimeType) throws + public Task createNewBlobAsync(Connection c, String name, String mimeType, Boolean _public) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "Async.network.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -676,20 +705,55 @@ public class Network extends XenAPIObject { * * @param name The name associated with the blob * @param mimeType The mime type for the data. Empty string translates to application/octet-stream + * @param _public True if the blob should be publicly available * @return The reference of the blob, needed for populating its data */ - public Blob createNewBlob(Connection c, String name, String mimeType) throws + public Blob createNewBlob(Connection c, String name, String mimeType, Boolean _public) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "network.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toBlob(result); } + /** + * Set the default locking mode for VIFs attached to this network + * + * @param value The default locking mode for VIFs attached to this network. + * @return Task + */ + public Task setDefaultLockingModeAsync(Connection c, Types.NetworkDefaultLockingMode value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.network.set_default_locking_mode"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Set the default locking mode for VIFs attached to this network + * + * @param value The default locking mode for VIFs attached to this network. + */ + public void setDefaultLockingMode(Connection c, Types.NetworkDefaultLockingMode value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "network.set_default_locking_mode"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + /** * Return a list of all the networks known to the system. * @@ -724,4 +788,4 @@ public class Network extends XenAPIObject { return Types.toMapOfNetworkNetworkRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/PBD.java b/deps/XenServerJava/src/com/xensource/xenapi/PBD.java index 0a1e60d354a..6fddfa68542 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/PBD.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/PBD.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class PBD extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class PBD extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -534,4 +539,4 @@ public class PBD extends XenAPIObject { return Types.toMapOfPBDPBDRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/PCI.java b/deps/XenServerJava/src/com/xensource/xenapi/PCI.java new file mode 100644 index 00000000000..9e2ec77d0be --- /dev/null +++ b/deps/XenServerJava/src/com/xensource/xenapi/PCI.java @@ -0,0 +1,418 @@ +/* + * Copyright (c) Citrix Systems, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1) Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2) Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +package com.xensource.xenapi; + +import com.xensource.xenapi.Types.BadServerResponse; +import com.xensource.xenapi.Types.VersionException; +import com.xensource.xenapi.Types.XenAPIException; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.xmlrpc.XmlRpcException; + +/** + * A PCI device + * + * @author Citrix Systems, Inc. + */ +public class PCI extends XenAPIObject { + + /** + * The XenAPI reference (OpaqueRef) to this object. + */ + protected final String ref; + + /** + * For internal use only. + */ + PCI(String ref) { + this.ref = ref; + } + + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ + public String toWireString() { + return this.ref; + } + + /** + * If obj is a PCI, compares XenAPI references for equality. + */ + @Override + public boolean equals(Object obj) + { + if (obj != null && obj instanceof PCI) + { + PCI other = (PCI) obj; + return other.ref.equals(this.ref); + } else + { + return false; + } + } + + @Override + public int hashCode() + { + return ref.hashCode(); + } + + /** + * Represents all the fields in a PCI + */ + public static class Record implements Types.Record { + public String toString() { + StringWriter writer = new StringWriter(); + PrintWriter print = new PrintWriter(writer); + print.printf("%1$20s: %2$s\n", "uuid", this.uuid); + print.printf("%1$20s: %2$s\n", "clazzName", this.clazzName); + print.printf("%1$20s: %2$s\n", "vendorName", this.vendorName); + print.printf("%1$20s: %2$s\n", "deviceName", this.deviceName); + print.printf("%1$20s: %2$s\n", "host", this.host); + print.printf("%1$20s: %2$s\n", "pciId", this.pciId); + print.printf("%1$20s: %2$s\n", "dependencies", this.dependencies); + print.printf("%1$20s: %2$s\n", "otherConfig", this.otherConfig); + return writer.toString(); + } + + /** + * Convert a PCI.Record to a Map + */ + public Map toMap() { + Map map = new HashMap(); + map.put("uuid", this.uuid == null ? "" : this.uuid); + map.put("class_name", this.clazzName == null ? "" : this.clazzName); + map.put("vendor_name", this.vendorName == null ? "" : this.vendorName); + map.put("device_name", this.deviceName == null ? "" : this.deviceName); + map.put("host", this.host == null ? new Host("OpaqueRef:NULL") : this.host); + map.put("pci_id", this.pciId == null ? "" : this.pciId); + map.put("dependencies", this.dependencies == null ? new LinkedHashSet() : this.dependencies); + map.put("other_config", this.otherConfig == null ? new HashMap() : this.otherConfig); + return map; + } + + /** + * Unique identifier/object reference + */ + public String uuid; + /** + * PCI class name + */ + public String clazzName; + /** + * Vendor name + */ + public String vendorName; + /** + * Device name + */ + public String deviceName; + /** + * Physical machine that owns the PCI device + */ + public Host host; + /** + * PCI ID of the physical device + */ + public String pciId; + /** + * List of dependent PCI devices + */ + public Set dependencies; + /** + * Additional configuration + */ + public Map otherConfig; + } + + /** + * Get a record containing the current state of the given PCI. + * + * @return all fields from the object + */ + public PCI.Record getRecord(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.get_record"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toPCIRecord(result); + } + + /** + * Get a reference to the PCI instance with the specified UUID. + * + * @param uuid UUID of object to return + * @return reference to the object + */ + public static PCI getByUuid(Connection c, String uuid) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.get_by_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toPCI(result); + } + + /** + * Get the uuid field of the given PCI. + * + * @return value of the field + */ + public String getUuid(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.get_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the class_name field of the given PCI. + * + * @return value of the field + */ + public String getClazzName(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.get_class_name"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the vendor_name field of the given PCI. + * + * @return value of the field + */ + public String getVendorName(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.get_vendor_name"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the device_name field of the given PCI. + * + * @return value of the field + */ + public String getDeviceName(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.get_device_name"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the host field of the given PCI. + * + * @return value of the field + */ + public Host getHost(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.get_host"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toHost(result); + } + + /** + * Get the pci_id field of the given PCI. + * + * @return value of the field + */ + public String getPciId(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.get_pci_id"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the dependencies field of the given PCI. + * + * @return value of the field + */ + public Set getDependencies(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.get_dependencies"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfPCI(result); + } + + /** + * Get the other_config field of the given PCI. + * + * @return value of the field + */ + public Map getOtherConfig(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.get_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfStringString(result); + } + + /** + * Set the other_config field of the given PCI. + * + * @param otherConfig New value to set + */ + public void setOtherConfig(Connection c, Map otherConfig) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.set_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Add the given key-value pair to the other_config field of the given PCI. + * + * @param key Key to add + * @param value Value to add + */ + public void addToOtherConfig(Connection c, String key, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.add_to_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Remove the given key and its corresponding value from the other_config field of the given PCI. If the key is not in that Map, then do nothing. + * + * @param key Key to remove + */ + public void removeFromOtherConfig(Connection c, String key) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.remove_from_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Return a list of all the PCIs known to the system. + * + * @return references to all objects + */ + public static Set getAll(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.get_all"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfPCI(result); + } + + /** + * Return a map of PCI references to PCI records for all PCIs known to the system. + * + * @return records of all objects + */ + public static Map getAllRecords(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PCI.get_all_records"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfPCIPCIRecord(result); + } + +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/PGPU.java b/deps/XenServerJava/src/com/xensource/xenapi/PGPU.java new file mode 100644 index 00000000000..a9e1c432dad --- /dev/null +++ b/deps/XenServerJava/src/com/xensource/xenapi/PGPU.java @@ -0,0 +1,349 @@ +/* + * Copyright (c) Citrix Systems, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1) Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2) Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +package com.xensource.xenapi; + +import com.xensource.xenapi.Types.BadServerResponse; +import com.xensource.xenapi.Types.VersionException; +import com.xensource.xenapi.Types.XenAPIException; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.xmlrpc.XmlRpcException; + +/** + * A physical GPU (pGPU) + * + * @author Citrix Systems, Inc. + */ +public class PGPU extends XenAPIObject { + + /** + * The XenAPI reference (OpaqueRef) to this object. + */ + protected final String ref; + + /** + * For internal use only. + */ + PGPU(String ref) { + this.ref = ref; + } + + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ + public String toWireString() { + return this.ref; + } + + /** + * If obj is a PGPU, compares XenAPI references for equality. + */ + @Override + public boolean equals(Object obj) + { + if (obj != null && obj instanceof PGPU) + { + PGPU other = (PGPU) obj; + return other.ref.equals(this.ref); + } else + { + return false; + } + } + + @Override + public int hashCode() + { + return ref.hashCode(); + } + + /** + * Represents all the fields in a PGPU + */ + public static class Record implements Types.Record { + public String toString() { + StringWriter writer = new StringWriter(); + PrintWriter print = new PrintWriter(writer); + print.printf("%1$20s: %2$s\n", "uuid", this.uuid); + print.printf("%1$20s: %2$s\n", "PCI", this.PCI); + print.printf("%1$20s: %2$s\n", "GPUGroup", this.GPUGroup); + print.printf("%1$20s: %2$s\n", "host", this.host); + print.printf("%1$20s: %2$s\n", "otherConfig", this.otherConfig); + return writer.toString(); + } + + /** + * Convert a PGPU.Record to a Map + */ + public Map toMap() { + Map map = new HashMap(); + map.put("uuid", this.uuid == null ? "" : this.uuid); + map.put("PCI", this.PCI == null ? new PCI("OpaqueRef:NULL") : this.PCI); + map.put("GPU_group", this.GPUGroup == null ? new GPUGroup("OpaqueRef:NULL") : this.GPUGroup); + map.put("host", this.host == null ? new Host("OpaqueRef:NULL") : this.host); + map.put("other_config", this.otherConfig == null ? new HashMap() : this.otherConfig); + return map; + } + + /** + * Unique identifier/object reference + */ + public String uuid; + /** + * Link to underlying PCI device + */ + public PCI PCI; + /** + * GPU group the pGPU is contained in + */ + public GPUGroup GPUGroup; + /** + * Host that own the GPU + */ + public Host host; + /** + * Additional configuration + */ + public Map otherConfig; + } + + /** + * Get a record containing the current state of the given PGPU. + * + * @return all fields from the object + */ + public PGPU.Record getRecord(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PGPU.get_record"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toPGPURecord(result); + } + + /** + * Get a reference to the PGPU instance with the specified UUID. + * + * @param uuid UUID of object to return + * @return reference to the object + */ + public static PGPU getByUuid(Connection c, String uuid) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PGPU.get_by_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toPGPU(result); + } + + /** + * Get the uuid field of the given PGPU. + * + * @return value of the field + */ + public String getUuid(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PGPU.get_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the PCI field of the given PGPU. + * + * @return value of the field + */ + public PCI getPCI(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PGPU.get_PCI"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toPCI(result); + } + + /** + * Get the GPU_group field of the given PGPU. + * + * @return value of the field + */ + public GPUGroup getGPUGroup(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PGPU.get_GPU_group"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toGPUGroup(result); + } + + /** + * Get the host field of the given PGPU. + * + * @return value of the field + */ + public Host getHost(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PGPU.get_host"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toHost(result); + } + + /** + * Get the other_config field of the given PGPU. + * + * @return value of the field + */ + public Map getOtherConfig(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PGPU.get_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfStringString(result); + } + + /** + * Set the other_config field of the given PGPU. + * + * @param otherConfig New value to set + */ + public void setOtherConfig(Connection c, Map otherConfig) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PGPU.set_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Add the given key-value pair to the other_config field of the given PGPU. + * + * @param key Key to add + * @param value Value to add + */ + public void addToOtherConfig(Connection c, String key, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PGPU.add_to_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Remove the given key and its corresponding value from the other_config field of the given PGPU. If the key is not in that Map, then do nothing. + * + * @param key Key to remove + */ + public void removeFromOtherConfig(Connection c, String key) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PGPU.remove_from_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Return a list of all the PGPUs known to the system. + * + * @return references to all objects + */ + public static Set getAll(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PGPU.get_all"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfPGPU(result); + } + + /** + * Return a map of PGPU references to PGPU records for all PGPUs known to the system. + * + * @return records of all objects + */ + public static Map getAllRecords(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PGPU.get_all_records"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfPGPUPGPURecord(result); + } + +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/PIF.java b/deps/XenServerJava/src/com/xensource/xenapi/PIF.java index bb0629446a6..950afebce14 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/PIF.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/PIF.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class PIF extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class PIF extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -119,6 +124,10 @@ public class PIF extends XenAPIObject { print.printf("%1$20s: %2$s\n", "disallowUnplug", this.disallowUnplug); print.printf("%1$20s: %2$s\n", "tunnelAccessPIFOf", this.tunnelAccessPIFOf); print.printf("%1$20s: %2$s\n", "tunnelTransportPIFOf", this.tunnelTransportPIFOf); + print.printf("%1$20s: %2$s\n", "ipv6ConfigurationMode", this.ipv6ConfigurationMode); + print.printf("%1$20s: %2$s\n", "IPv6", this.IPv6); + print.printf("%1$20s: %2$s\n", "ipv6Gateway", this.ipv6Gateway); + print.printf("%1$20s: %2$s\n", "primaryAddressType", this.primaryAddressType); return writer.toString(); } @@ -151,6 +160,10 @@ public class PIF extends XenAPIObject { map.put("disallow_unplug", this.disallowUnplug == null ? false : this.disallowUnplug); map.put("tunnel_access_PIF_of", this.tunnelAccessPIFOf == null ? new LinkedHashSet() : this.tunnelAccessPIFOf); map.put("tunnel_transport_PIF_of", this.tunnelTransportPIFOf == null ? new LinkedHashSet() : this.tunnelTransportPIFOf); + map.put("ipv6_configuration_mode", this.ipv6ConfigurationMode == null ? Types.Ipv6ConfigurationMode.UNRECOGNIZED : this.ipv6ConfigurationMode); + map.put("IPv6", this.IPv6 == null ? new LinkedHashSet() : this.IPv6); + map.put("ipv6_gateway", this.ipv6Gateway == null ? "" : this.ipv6Gateway); + map.put("primary_address_type", this.primaryAddressType == null ? Types.PrimaryAddressType.UNRECOGNIZED : this.primaryAddressType); return map; } @@ -250,6 +263,22 @@ public class PIF extends XenAPIObject { * Indicates to which tunnel this PIF provides transport */ public Set tunnelTransportPIFOf; + /** + * Sets if and how this interface gets an IPv6 address + */ + public Types.Ipv6ConfigurationMode ipv6ConfigurationMode; + /** + * IPv6 address + */ + public Set IPv6; + /** + * IPv6 gateway + */ + public String ipv6Gateway; + /** + * Which protocol should define the primary address of this interface + */ + public Types.PrimaryAddressType primaryAddressType; } /** @@ -695,6 +724,74 @@ public class PIF extends XenAPIObject { return Types.toSetOfTunnel(result); } + /** + * Get the ipv6_configuration_mode field of the given PIF. + * + * @return value of the field + */ + public Types.Ipv6ConfigurationMode getIpv6ConfigurationMode(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PIF.get_ipv6_configuration_mode"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toIpv6ConfigurationMode(result); + } + + /** + * Get the IPv6 field of the given PIF. + * + * @return value of the field + */ + public Set getIPv6(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PIF.get_IPv6"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfString(result); + } + + /** + * Get the ipv6_gateway field of the given PIF. + * + * @return value of the field + */ + public String getIpv6Gateway(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PIF.get_ipv6_gateway"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the primary_address_type field of the given PIF. + * + * @return value of the field + */ + public Types.PrimaryAddressType getPrimaryAddressType(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PIF.get_primary_address_type"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toPrimaryAddressType(result); + } + /** * Set the other_config field of the given PIF. * @@ -884,6 +981,80 @@ public class PIF extends XenAPIObject { return; } + /** + * Reconfigure the IPv6 address settings for this interface + * + * @param mode whether to use dynamic/static/no-assignment + * @param IPv6 the new IPv6 address (in / format) + * @param gateway the new gateway + * @param DNS the new DNS settings + * @return Task + */ + public Task reconfigureIpv6Async(Connection c, Types.Ipv6ConfigurationMode mode, String IPv6, String gateway, String DNS) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.PIF.reconfigure_ipv6"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(IPv6), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Reconfigure the IPv6 address settings for this interface + * + * @param mode whether to use dynamic/static/no-assignment + * @param IPv6 the new IPv6 address (in / format) + * @param gateway the new gateway + * @param DNS the new DNS settings + */ + public void reconfigureIpv6(Connection c, Types.Ipv6ConfigurationMode mode, String IPv6, String gateway, String DNS) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PIF.reconfigure_ipv6"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(mode), Marshalling.toXMLRPC(IPv6), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Change the primary address type used by this PIF + * + * @param primaryAddressType Whether to prefer IPv4 or IPv6 connections + * @return Task + */ + public Task setPrimaryAddressTypeAsync(Connection c, Types.PrimaryAddressType primaryAddressType) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.PIF.set_primary_address_type"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(primaryAddressType)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Change the primary address type used by this PIF + * + * @param primaryAddressType Whether to prefer IPv4 or IPv6 connections + */ + public void setPrimaryAddressType(Connection c, Types.PrimaryAddressType primaryAddressType) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "PIF.set_primary_address_type"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(primaryAddressType)}; + Map response = c.dispatch(method_call, method_params); + return; + } + /** * Scan for physical interfaces on a host and create PIF objects to represent them * @@ -918,42 +1089,6 @@ public class PIF extends XenAPIObject { return; } - /** - * Scan for physical interfaces on a host and create PIF objects to represent them. Use BIOS-based device names. - * - * @param host The host on which to scan - * @return Task - */ - public static Task scanBiosAsync(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { - String method_call = "Async.PIF.scan_bios"; - String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host)}; - Map response = c.dispatch(method_call, method_params); - Object result = response.get("Value"); - return Types.toTask(result); - } - - /** - * Scan for physical interfaces on a host and create PIF objects to represent them. Use BIOS-based device names. - * - * @param host The host on which to scan - * @return List of newly created PIFs - */ - public static Set scanBios(Connection c, Host host) throws - BadServerResponse, - XenAPIException, - XmlRpcException { - String method_call = "PIF.scan_bios"; - String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(host)}; - Map response = c.dispatch(method_call, method_params); - Object result = response.get("Value"); - return Types.toSetOfPIF(result); - } - /** * Create a PIF object matching a particular network interface * @@ -1097,32 +1232,36 @@ public class PIF extends XenAPIObject { /** * Create a new PIF record in the database only * - * @param device - * @param network - * @param host - * @param MAC - * @param MTU - * @param VLAN - * @param physical - * @param ipConfigurationMode - * @param IP - * @param netmask - * @param gateway - * @param DNS - * @param bondSlaveOf - * @param VLANMasterOf - * @param management - * @param otherConfig - * @param disallowUnplug + * @param device + * @param network + * @param host + * @param MAC + * @param MTU + * @param VLAN + * @param physical + * @param ipConfigurationMode + * @param IP + * @param netmask + * @param gateway + * @param DNS + * @param bondSlaveOf + * @param VLANMasterOf + * @param management + * @param otherConfig + * @param disallowUnplug + * @param ipv6ConfigurationMode + * @param IPv6 + * @param ipv6Gateway + * @param primaryAddressType * @return Task */ - public static Task dbIntroduceAsync(Connection c, String device, Network network, Host host, String MAC, Long MTU, Long VLAN, Boolean physical, Types.IpConfigurationMode ipConfigurationMode, String IP, String netmask, String gateway, String DNS, Bond bondSlaveOf, VLAN VLANMasterOf, Boolean management, Map otherConfig, Boolean disallowUnplug) throws + public static Task dbIntroduceAsync(Connection c, String device, Network network, Host host, String MAC, Long MTU, Long VLAN, Boolean physical, Types.IpConfigurationMode ipConfigurationMode, String IP, String netmask, String gateway, String DNS, Bond bondSlaveOf, VLAN VLANMasterOf, Boolean management, Map otherConfig, Boolean disallowUnplug, Types.Ipv6ConfigurationMode ipv6ConfigurationMode, Set IPv6, String ipv6Gateway, Types.PrimaryAddressType primaryAddressType) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "Async.PIF.db_introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(MTU), Marshalling.toXMLRPC(VLAN), Marshalling.toXMLRPC(physical), Marshalling.toXMLRPC(ipConfigurationMode), Marshalling.toXMLRPC(IP), Marshalling.toXMLRPC(netmask), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS), Marshalling.toXMLRPC(bondSlaveOf), Marshalling.toXMLRPC(VLANMasterOf), Marshalling.toXMLRPC(management), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(disallowUnplug)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(MTU), Marshalling.toXMLRPC(VLAN), Marshalling.toXMLRPC(physical), Marshalling.toXMLRPC(ipConfigurationMode), Marshalling.toXMLRPC(IP), Marshalling.toXMLRPC(netmask), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS), Marshalling.toXMLRPC(bondSlaveOf), Marshalling.toXMLRPC(VLANMasterOf), Marshalling.toXMLRPC(management), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(disallowUnplug), Marshalling.toXMLRPC(ipv6ConfigurationMode), Marshalling.toXMLRPC(IPv6), Marshalling.toXMLRPC(ipv6Gateway), Marshalling.toXMLRPC(primaryAddressType)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1131,32 +1270,36 @@ public class PIF extends XenAPIObject { /** * Create a new PIF record in the database only * - * @param device - * @param network - * @param host - * @param MAC - * @param MTU - * @param VLAN - * @param physical - * @param ipConfigurationMode - * @param IP - * @param netmask - * @param gateway - * @param DNS - * @param bondSlaveOf - * @param VLANMasterOf - * @param management - * @param otherConfig - * @param disallowUnplug + * @param device + * @param network + * @param host + * @param MAC + * @param MTU + * @param VLAN + * @param physical + * @param ipConfigurationMode + * @param IP + * @param netmask + * @param gateway + * @param DNS + * @param bondSlaveOf + * @param VLANMasterOf + * @param management + * @param otherConfig + * @param disallowUnplug + * @param ipv6ConfigurationMode + * @param IPv6 + * @param ipv6Gateway + * @param primaryAddressType * @return The ref of the newly created PIF record. */ - public static PIF dbIntroduce(Connection c, String device, Network network, Host host, String MAC, Long MTU, Long VLAN, Boolean physical, Types.IpConfigurationMode ipConfigurationMode, String IP, String netmask, String gateway, String DNS, Bond bondSlaveOf, VLAN VLANMasterOf, Boolean management, Map otherConfig, Boolean disallowUnplug) throws + public static PIF dbIntroduce(Connection c, String device, Network network, Host host, String MAC, Long MTU, Long VLAN, Boolean physical, Types.IpConfigurationMode ipConfigurationMode, String IP, String netmask, String gateway, String DNS, Bond bondSlaveOf, VLAN VLANMasterOf, Boolean management, Map otherConfig, Boolean disallowUnplug, Types.Ipv6ConfigurationMode ipv6ConfigurationMode, Set IPv6, String ipv6Gateway, Types.PrimaryAddressType primaryAddressType) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "PIF.db_introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(MTU), Marshalling.toXMLRPC(VLAN), Marshalling.toXMLRPC(physical), Marshalling.toXMLRPC(ipConfigurationMode), Marshalling.toXMLRPC(IP), Marshalling.toXMLRPC(netmask), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS), Marshalling.toXMLRPC(bondSlaveOf), Marshalling.toXMLRPC(VLANMasterOf), Marshalling.toXMLRPC(management), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(disallowUnplug)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(network), Marshalling.toXMLRPC(host), Marshalling.toXMLRPC(MAC), Marshalling.toXMLRPC(MTU), Marshalling.toXMLRPC(VLAN), Marshalling.toXMLRPC(physical), Marshalling.toXMLRPC(ipConfigurationMode), Marshalling.toXMLRPC(IP), Marshalling.toXMLRPC(netmask), Marshalling.toXMLRPC(gateway), Marshalling.toXMLRPC(DNS), Marshalling.toXMLRPC(bondSlaveOf), Marshalling.toXMLRPC(VLANMasterOf), Marshalling.toXMLRPC(management), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(disallowUnplug), Marshalling.toXMLRPC(ipv6ConfigurationMode), Marshalling.toXMLRPC(IPv6), Marshalling.toXMLRPC(ipv6Gateway), Marshalling.toXMLRPC(primaryAddressType)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toPIF(result); @@ -1228,4 +1371,4 @@ public class PIF extends XenAPIObject { return Types.toMapOfPIFPIFRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/PIFMetrics.java b/deps/XenServerJava/src/com/xensource/xenapi/PIFMetrics.java index 34417d3cea3..d0a3911d327 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/PIFMetrics.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/PIFMetrics.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class PIFMetrics extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class PIFMetrics extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -525,4 +530,4 @@ public class PIFMetrics extends XenAPIObject { return Types.toMapOfPIFMetricsPIFMetricsRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Pool.java b/deps/XenServerJava/src/com/xensource/xenapi/Pool.java index 1b06094afe3..2dc0fac9c78 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Pool.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Pool.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Pool extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Pool extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -121,6 +126,7 @@ public class Pool extends XenAPIObject { print.printf("%1$20s: %2$s\n", "redoLogVdi", this.redoLogVdi); print.printf("%1$20s: %2$s\n", "vswitchController", this.vswitchController); print.printf("%1$20s: %2$s\n", "restrictions", this.restrictions); + print.printf("%1$20s: %2$s\n", "metadataVDIs", this.metadataVDIs); return writer.toString(); } @@ -155,6 +161,7 @@ public class Pool extends XenAPIObject { map.put("redo_log_vdi", this.redoLogVdi == null ? new VDI("OpaqueRef:NULL") : this.redoLogVdi); map.put("vswitch_controller", this.vswitchController == null ? "" : this.vswitchController); map.put("restrictions", this.restrictions == null ? new HashMap() : this.restrictions); + map.put("metadata_VDIs", this.metadataVDIs == null ? new LinkedHashSet() : this.metadataVDIs); return map; } @@ -262,6 +269,10 @@ public class Pool extends XenAPIObject { * Pool-wide restrictions currently in effect */ public Map restrictions; + /** + * The set of currently known metadata VDIs for this pool + */ + public Set metadataVDIs; } /** @@ -741,6 +752,23 @@ public class Pool extends XenAPIObject { return Types.toMapOfStringString(result); } + /** + * Get the metadata_VDIs field of the given pool. + * + * @return value of the field + */ + public Set getMetadataVDIs(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "pool.get_metadata_VDIs"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfVDI(result); + } + /** * Set the name_label field of the given pool. * @@ -1537,15 +1565,16 @@ public class Pool extends XenAPIObject { * * @param name The name associated with the blob * @param mimeType The mime type for the data. Empty string translates to application/octet-stream + * @param _public True if the blob should be publicly available * @return Task */ - public Task createNewBlobAsync(Connection c, String name, String mimeType) throws + public Task createNewBlobAsync(Connection c, String name, String mimeType, Boolean _public) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "Async.pool.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1556,15 +1585,16 @@ public class Pool extends XenAPIObject { * * @param name The name associated with the blob * @param mimeType The mime type for the data. Empty string translates to application/octet-stream + * @param _public True if the blob should be publicly available * @return The reference of the blob, needed for populating its data */ - public Blob createNewBlob(Connection c, String name, String mimeType) throws + public Blob createNewBlob(Connection c, String name, String mimeType, Boolean _public) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "pool.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toBlob(result); @@ -1798,9 +1828,9 @@ public class Pool extends XenAPIObject { /** * Send the given body to the given host and port, using HTTPS, and print the response. This is used for debugging the SSL layer. * - * @param host - * @param port - * @param body + * @param host + * @param port + * @param body * @return Task */ public static Task sendTestPostAsync(Connection c, String host, Long port, String body) throws @@ -1818,9 +1848,9 @@ public class Pool extends XenAPIObject { /** * Send the given body to the given host and port, using HTTPS, and print the response. This is used for debugging the SSL layer. * - * @param host - * @param port - * @param body + * @param host + * @param port + * @param body * @return The response */ public static String sendTestPost(Connection c, String host, Long port, String body) throws @@ -2291,4 +2321,4 @@ public class Pool extends XenAPIObject { return Types.toMapOfPoolPoolRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/PoolPatch.java b/deps/XenServerJava/src/com/xensource/xenapi/PoolPatch.java index b2740247838..750a9f3225c 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/PoolPatch.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/PoolPatch.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class PoolPatch extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class PoolPatch extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -133,7 +138,7 @@ public class PoolPatch extends XenAPIObject { */ public String nameLabel; /** - * a notes field containg human-readable description + * a notes field containing human-readable description */ public String nameDescription; /** @@ -522,7 +527,7 @@ public class PoolPatch extends XenAPIObject { } /** - * Removes the patch's files from all hosts in the pool, but does not remove the database entries + * Removes the patch's files from the server * * @return Task */ @@ -539,7 +544,7 @@ public class PoolPatch extends XenAPIObject { } /** - * Removes the patch's files from all hosts in the pool, but does not remove the database entries + * Removes the patch's files from the server * */ public void clean(Connection c) throws @@ -553,6 +558,38 @@ public class PoolPatch extends XenAPIObject { return; } + /** + * Removes the patch's files from all hosts in the pool, but does not remove the database entries + * + * @return Task + */ + public Task poolCleanAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.pool_patch.pool_clean"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Removes the patch's files from all hosts in the pool, but does not remove the database entries + * + */ + public void poolClean(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "pool_patch.pool_clean"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + return; + } + /** * Removes the patch's files from all hosts in the pool, and removes the database entries. Only works on unapplied patches. * @@ -585,6 +622,40 @@ public class PoolPatch extends XenAPIObject { return; } + /** + * Removes the patch's files from the specified host + * + * @param host The host on which to clean the patch + * @return Task + */ + public Task cleanOnHostAsync(Connection c, Host host) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.pool_patch.clean_on_host"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Removes the patch's files from the specified host + * + * @param host The host on which to clean the patch + */ + public void cleanOnHost(Connection c, Host host) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "pool_patch.clean_on_host"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; + Map response = c.dispatch(method_call, method_params); + return; + } + /** * Return a list of all the pool_patchs known to the system. * @@ -619,4 +690,4 @@ public class PoolPatch extends XenAPIObject { return Types.toMapOfPoolPatchPoolPatchRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Role.java b/deps/XenServerJava/src/com/xensource/xenapi/Role.java index c64d18fae3f..f8dea77010b 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Role.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Role.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Role extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Role extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -356,4 +361,4 @@ public class Role extends XenAPIObject { return Types.toMapOfRoleRoleRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/SM.java b/deps/XenServerJava/src/com/xensource/xenapi/SM.java index 12b6a821abb..9c7341ceb10 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/SM.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/SM.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class SM extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class SM extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -139,7 +144,7 @@ public class SM extends XenAPIObject { */ public String nameLabel; /** - * a notes field containg human-readable description + * a notes field containing human-readable description */ public String nameDescription; /** @@ -520,4 +525,4 @@ public class SM extends XenAPIObject { return Types.toMapOfSMSMRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/SR.java b/deps/XenServerJava/src/com/xensource/xenapi/SR.java index 0f64aa58ca2..72314032506 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/SR.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/SR.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class SR extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class SR extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -113,6 +118,7 @@ public class SR extends XenAPIObject { print.printf("%1$20s: %2$s\n", "smConfig", this.smConfig); print.printf("%1$20s: %2$s\n", "blobs", this.blobs); print.printf("%1$20s: %2$s\n", "localCacheEnabled", this.localCacheEnabled); + print.printf("%1$20s: %2$s\n", "introducedBy", this.introducedBy); return writer.toString(); } @@ -139,6 +145,7 @@ public class SR extends XenAPIObject { map.put("sm_config", this.smConfig == null ? new HashMap() : this.smConfig); map.put("blobs", this.blobs == null ? new HashMap() : this.blobs); map.put("local_cache_enabled", this.localCacheEnabled == null ? false : this.localCacheEnabled); + map.put("introduced_by", this.introducedBy == null ? new DRTask("OpaqueRef:NULL") : this.introducedBy); return map; } @@ -151,7 +158,7 @@ public class SR extends XenAPIObject { */ public String nameLabel; /** - * a notes field containg human-readable description + * a notes field containing human-readable description */ public String nameDescription; /** @@ -214,6 +221,10 @@ public class SR extends XenAPIObject { * True if this SR is assigned to be the local cache for its host */ public Boolean localCacheEnabled; + /** + * The disaster recovery task which introduced this SR + */ + public DRTask introducedBy; } /** @@ -576,35 +587,20 @@ public class SR extends XenAPIObject { } /** - * Set the name/label field of the given SR. + * Get the introduced_by field of the given SR. * - * @param label New value to set + * @return value of the field */ - public void setNameLabel(Connection c, String label) throws + public DRTask getIntroducedBy(Connection c) throws BadServerResponse, XenAPIException, XmlRpcException { - String method_call = "SR.set_name_label"; + String method_call = "SR.get_introduced_by"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(label)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); - return; - } - - /** - * Set the name/description field of the given SR. - * - * @param description New value to set - */ - public void setNameDescription(Connection c, String description) throws - BadServerResponse, - XenAPIException, - XmlRpcException { - String method_call = "SR.set_name_description"; - String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(description)}; - Map response = c.dispatch(method_call, method_params); - return; + Object result = response.get("Value"); + return Types.toDRTask(result); } /** @@ -1322,20 +1318,89 @@ public class SR extends XenAPIObject { return; } + /** + * Set the name label of the SR + * + * @param value The name label for the SR + * @return Task + */ + public Task setNameLabelAsync(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.SR.set_name_label"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Set the name label of the SR + * + * @param value The name label for the SR + */ + public void setNameLabel(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "SR.set_name_label"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Set the name description of the SR + * + * @param value The name description for the SR + * @return Task + */ + public Task setNameDescriptionAsync(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.SR.set_name_description"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Set the name description of the SR + * + * @param value The name description for the SR + */ + public void setNameDescription(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "SR.set_name_description"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + /** * Create a placeholder for a named binary blob of data that is associated with this SR * * @param name The name associated with the blob * @param mimeType The mime type for the data. Empty string translates to application/octet-stream + * @param _public True if the blob should be publicly available * @return Task */ - public Task createNewBlobAsync(Connection c, String name, String mimeType) throws + public Task createNewBlobAsync(Connection c, String name, String mimeType, Boolean _public) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "Async.SR.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1346,15 +1411,16 @@ public class SR extends XenAPIObject { * * @param name The name associated with the blob * @param mimeType The mime type for the data. Empty string translates to application/octet-stream + * @param _public True if the blob should be publicly available * @return The reference of the blob, needed for populating its data */ - public Blob createNewBlob(Connection c, String name, String mimeType) throws + public Blob createNewBlob(Connection c, String name, String mimeType, Boolean _public) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "SR.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toBlob(result); @@ -1440,6 +1506,102 @@ public class SR extends XenAPIObject { return; } + /** + * Returns successfully if the given SR supports database replication. Otherwise returns an error to explain why not. + * + * @return Task + */ + public Task assertSupportsDatabaseReplicationAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.SR.assert_supports_database_replication"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Returns successfully if the given SR supports database replication. Otherwise returns an error to explain why not. + * + */ + public void assertSupportsDatabaseReplication(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "SR.assert_supports_database_replication"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * + * + * @return Task + */ + public Task enableDatabaseReplicationAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.SR.enable_database_replication"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * + * + */ + public void enableDatabaseReplication(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "SR.enable_database_replication"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * + * + * @return Task + */ + public Task disableDatabaseReplicationAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.SR.disable_database_replication"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * + * + */ + public void disableDatabaseReplication(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "SR.disable_database_replication"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + return; + } + /** * Return a list of all the SRs known to the system. * @@ -1474,4 +1636,4 @@ public class SR extends XenAPIObject { return Types.toMapOfSRSRRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Secret.java b/deps/XenServerJava/src/com/xensource/xenapi/Secret.java index 3a211a050a7..a9f8eddc847 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Secret.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Secret.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Secret extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Secret extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -97,6 +102,7 @@ public class Secret extends XenAPIObject { PrintWriter print = new PrintWriter(writer); print.printf("%1$20s: %2$s\n", "uuid", this.uuid); print.printf("%1$20s: %2$s\n", "value", this.value); + print.printf("%1$20s: %2$s\n", "otherConfig", this.otherConfig); return writer.toString(); } @@ -107,6 +113,7 @@ public class Secret extends XenAPIObject { Map map = new HashMap(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("value", this.value == null ? "" : this.value); + map.put("other_config", this.otherConfig == null ? new HashMap() : this.otherConfig); return map; } @@ -118,6 +125,10 @@ public class Secret extends XenAPIObject { * the secret */ public String value; + /** + * other_config + */ + public Map otherConfig; } /** @@ -259,6 +270,23 @@ public class Secret extends XenAPIObject { return Types.toString(result); } + /** + * Get the other_config field of the given secret. + * + * @return value of the field + */ + public Map getOtherConfig(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "secret.get_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfStringString(result); + } + /** * Set the value field of the given secret. * @@ -275,6 +303,55 @@ public class Secret extends XenAPIObject { return; } + /** + * Set the other_config field of the given secret. + * + * @param otherConfig New value to set + */ + public void setOtherConfig(Connection c, Map otherConfig) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "secret.set_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Add the given key-value pair to the other_config field of the given secret. + * + * @param key Key to add + * @param value Value to add + */ + public void addToOtherConfig(Connection c, String key, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "secret.add_to_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Remove the given key and its corresponding value from the other_config field of the given secret. If the key is not in that Map, then do nothing. + * + * @param key Key to remove + */ + public void removeFromOtherConfig(Connection c, String key) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "secret.remove_from_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; + Map response = c.dispatch(method_call, method_params); + return; + } + /** * Return a list of all the secrets known to the system. * @@ -309,4 +386,4 @@ public class Secret extends XenAPIObject { return Types.toMapOfSecretSecretRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Session.java b/deps/XenServerJava/src/com/xensource/xenapi/Session.java index 9be3388304b..f34476b162a 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Session.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Session.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Session extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Session extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -667,4 +672,4 @@ public class Session extends XenAPIObject { return; } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Subject.java b/deps/XenServerJava/src/com/xensource/xenapi/Subject.java index e760a5f751e..a181b58fda5 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Subject.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Subject.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Subject extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Subject extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -388,4 +393,4 @@ public class Subject extends XenAPIObject { return Types.toMapOfSubjectSubjectRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Task.java b/deps/XenServerJava/src/com/xensource/xenapi/Task.java index 884b283a91f..beb9686332e 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Task.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Task.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Task extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Task extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -147,7 +152,7 @@ public class Task extends XenAPIObject { */ public String nameLabel; /** - * a notes field containg human-readable description + * a notes field containing human-readable description */ public String nameDescription; /** @@ -175,7 +180,7 @@ public class Task extends XenAPIObject { */ public Host residentOn; /** - * if the task is still pending, this field contains the estimated fraction complete (0.-1.). If task has completed (successfully or unsuccessfully) this should be 1. + * This field contains the estimated fraction of the task which is complete. This field should not be used to determine whether the task is complete - for this the status field of the task should be used. */ public Double progress; /** @@ -680,4 +685,4 @@ public class Task extends XenAPIObject { return Types.toMapOfTaskTaskRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Tunnel.java b/deps/XenServerJava/src/com/xensource/xenapi/Tunnel.java index 17475238ed4..8289e8f35d2 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Tunnel.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Tunnel.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class Tunnel extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class Tunnel extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -466,4 +471,4 @@ public class Tunnel extends XenAPIObject { return Types.toMapOfTunnelTunnelRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/Types.java b/deps/XenServerJava/src/com/xensource/xenapi/Types.java index 31ac11a09eb..bde887a4ec3 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/Types.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/Types.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import java.util.Date; @@ -43,7 +45,7 @@ import org.apache.xmlrpc.XmlRpcException; /** * This class holds vital marshalling functions, enum types and exceptions. - * + * * @author Citrix Systems, Inc. */ public class Types @@ -143,7 +145,7 @@ public class Types * A call has been made which should not be made against this version of host. * Probably the host is out of date and cannot handle this call, or is * unable to comply with the details of the call. For instance SR.create - * on Miami (4.1) hosts takes an smConfig parameter, which must be an empty map + * on Miami (4.1) hosts takes an smConfig parameter, which must be an empty map * when making this call on Rio (4.0) hosts. */ public static class VersionException extends XenAPIException @@ -225,6 +227,11 @@ public class Types String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; throw new Types.VmHvmRequired(p1); } + if (ErrorDescription[0].equals("GPU_GROUP_CONTAINS_PGPU")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.GpuGroupContainsPgpu(p1); + } if (ErrorDescription[0].equals("PIF_TUNNEL_STILL_EXISTS")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -239,6 +246,11 @@ public class Types String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; throw new Types.PifAlreadyBonded(p1); } + if (ErrorDescription[0].equals("CANNOT_DESTROY_DISASTER_RECOVERY_TASK")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.CannotDestroyDisasterRecoveryTask(p1); + } if (ErrorDescription[0].equals("VLAN_TAG_INVALID")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -288,6 +300,11 @@ public class Types String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; throw new Types.PatchPrecheckFailedVmRunning(p1); } + if (ErrorDescription[0].equals("VM_REQUIRES_IOMMU")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.VmRequiresIommu(p1); + } if (ErrorDescription[0].equals("HA_HOST_CANNOT_SEE_PEERS")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -342,6 +359,11 @@ public class Types String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; throw new Types.VmNoSuspendSr(p1); } + if (ErrorDescription[0].equals("VM_HAS_TOO_MANY_SNAPSHOTS")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.VmHasTooManySnapshots(p1); + } if (ErrorDescription[0].equals("PATCH_APPLY_FAILED")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -358,6 +380,12 @@ public class Types String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; throw new Types.SrFull(p1, p2); } + if (ErrorDescription[0].equals("VM_REQUIRES_GPU")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; + throw new Types.VmRequiresGpu(p1, p2); + } if (ErrorDescription[0].equals("VDI_NOT_AVAILABLE")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -403,6 +431,11 @@ public class Types String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; throw new Types.XenVssReqErrorProvNotLoaded(p1, p2); } + if (ErrorDescription[0].equals("FEATURE_REQUIRES_HVM")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.FeatureRequiresHvm(p1); + } if (ErrorDescription[0].equals("SR_VDI_LOCKING_FAILED")) { throw new Types.SrVdiLockingFailed(); @@ -440,6 +473,11 @@ public class Types { throw new Types.WlbXenserverMalformedResponse(); } + if (ErrorDescription[0].equals("GPU_GROUP_CONTAINS_VGPU")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.GpuGroupContainsVgpu(p1); + } if (ErrorDescription[0].equals("POOL_AUTH_ENABLE_FAILED_DUPLICATE_HOSTNAME")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -471,6 +509,11 @@ public class Types String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; throw new Types.SrHasNoPbds(p1); } + if (ErrorDescription[0].equals("CANNOT_ADD_TUNNEL_TO_BOND_SLAVE")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.CannotAddTunnelToBondSlave(p1); + } if (ErrorDescription[0].equals("INVALID_PATCH")) { throw new Types.InvalidPatch(); @@ -496,6 +539,16 @@ public class Types { throw new Types.PoolJoiningHostMustHavePhysicalManagementNic(); } + if (ErrorDescription[0].equals("PIF_HAS_NO_V6_NETWORK_CONFIGURATION")) + { + throw new Types.PifHasNoV6NetworkConfiguration(); + } + if (ErrorDescription[0].equals("VM_IS_PART_OF_AN_APPLIANCE")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; + throw new Types.VmIsPartOfAnAppliance(p1, p2); + } if (ErrorDescription[0].equals("WLB_XENSERVER_AUTHENTICATION_FAILED")) { throw new Types.WlbXenserverAuthenticationFailed(); @@ -606,6 +659,17 @@ public class Types { throw new Types.HostCannotReadMetrics(); } + if (ErrorDescription[0].equals("VM_INCOMPATIBLE_WITH_THIS_HOST")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; + String p3 = ErrorDescription.length > 3 ? ErrorDescription[3] : ""; + throw new Types.VmIncompatibleWithThisHost(p1, p2, p3); + } + if (ErrorDescription[0].equals("NO_MORE_REDO_LOGS_ALLOWED")) + { + throw new Types.NoMoreRedoLogsAllowed(); + } if (ErrorDescription[0].equals("POOL_AUTH_ENABLE_FAILED")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -668,10 +732,21 @@ public class Types { throw new Types.WlbDisabled(); } + if (ErrorDescription[0].equals("VM_HOST_INCOMPATIBLE_VERSION")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; + throw new Types.VmHostIncompatibleVersion(p1, p2); + } if (ErrorDescription[0].equals("POOL_JOINING_EXTERNAL_AUTH_MISMATCH")) { throw new Types.PoolJoiningExternalAuthMismatch(); } + if (ErrorDescription[0].equals("DISK_VBD_MUST_BE_READWRITE_FOR_HVM")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.DiskVbdMustBeReadwriteForHvm(p1); + } if (ErrorDescription[0].equals("VM_BIOS_STRINGS_ALREADY_SET")) { throw new Types.VmBiosStringsAlreadySet(); @@ -718,6 +793,28 @@ public class Types String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; throw new Types.SrNotSharable(p1, p2); } + if (ErrorDescription[0].equals("VM_HAS_CHECKPOINT")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.VmHasCheckpoint(p1); + } + if (ErrorDescription[0].equals("SM_PLUGIN_COMMUNICATION_FAILURE")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.SmPluginCommunicationFailure(p1); + } + if (ErrorDescription[0].equals("VM_ASSIGNED_TO_PROTECTION_POLICY")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; + throw new Types.VmAssignedToProtectionPolicy(p1, p2); + } + if (ErrorDescription[0].equals("RBAC_PERMISSION_DENIED")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; + throw new Types.RbacPermissionDenied(p1, p2); + } if (ErrorDescription[0].equals("AUTH_DISABLE_FAILED_PERMISSION_DENIED")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -727,12 +824,6 @@ public class Types { throw new Types.LicenseCannotDowngradeWhileInPool(); } - if (ErrorDescription[0].equals("RBAC_PERMISSION_DENIED")) - { - String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; - String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; - throw new Types.RbacPermissionDenied(p1, p2); - } if (ErrorDescription[0].equals("TOO_MANY_PENDING_TASKS")) { throw new Types.TooManyPendingTasks(); @@ -742,6 +833,10 @@ public class Types String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; throw new Types.VmSnapshotWithQuiesceTimeout(p1); } + if (ErrorDescription[0].equals("HA_CANNOT_CHANGE_BOND_STATUS_OF_MGMT_IFACE")) + { + throw new Types.HaCannotChangeBondStatusOfMgmtIface(); + } if (ErrorDescription[0].equals("PATCH_ALREADY_APPLIED")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -757,6 +852,13 @@ public class Types String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; throw new Types.AuthEnableFailedDomainLookupFailed(p1); } + if (ErrorDescription[0].equals("PATCH_PRECHECK_FAILED_WRONG_SERVER_BUILD")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; + String p3 = ErrorDescription.length > 3 ? ErrorDescription[3] : ""; + throw new Types.PatchPrecheckFailedWrongServerBuild(p1, p2, p3); + } if (ErrorDescription[0].equals("INVALID_FEATURE_STRING")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -782,14 +884,20 @@ public class Types String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; throw new Types.VmShutdownTimeout(p1, p2); } + if (ErrorDescription[0].equals("ROLE_ALREADY_EXISTS")) + { + throw new Types.RoleAlreadyExists(); + } if (ErrorDescription[0].equals("NETWORK_CONTAINS_PIF")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; throw new Types.NetworkContainsPif(p1); } - if (ErrorDescription[0].equals("ROLE_ALREADY_EXISTS")) + if (ErrorDescription[0].equals("COULD_NOT_FIND_NETWORK_INTERFACE_WITH_SPECIFIED_DEVICE_NAME_AND_MAC_ADDRESS")) { - throw new Types.RoleAlreadyExists(); + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; + throw new Types.CouldNotFindNetworkInterfaceWithSpecifiedDeviceNameAndMacAddress(p1, p2); } if (ErrorDescription[0].equals("JOINING_HOST_SERVICE_FAILED")) { @@ -842,6 +950,12 @@ public class Types { throw new Types.LicenseProcessingError(); } + if (ErrorDescription[0].equals("ILLEGAL_VBD_DEVICE")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; + throw new Types.IllegalVbdDevice(p1, p2); + } if (ErrorDescription[0].equals("CRL_DOES_NOT_EXIST")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -906,6 +1020,11 @@ public class Types { throw new Types.PifCannotBondCrossHost(); } + if (ErrorDescription[0].equals("EVENT_FROM_TOKEN_PARSE_FAILURE")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.EventFromTokenParseFailure(p1); + } if (ErrorDescription[0].equals("SR_REQUIRES_UPGRADE")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -1018,6 +1137,11 @@ public class Types String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; throw new Types.HaHostIsArmed(p1); } + if (ErrorDescription[0].equals("EVENT_SUBSCRIPTION_PARSE_FAILURE")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.EventSubscriptionParseFailure(p1); + } if (ErrorDescription[0].equals("LICENSE_EXPIRED")) { throw new Types.LicenseExpired(); @@ -1035,6 +1159,10 @@ public class Types { throw new Types.VmppArchiveMoreFrequentThanBackup(); } + if (ErrorDescription[0].equals("V6D_FAILURE")) + { + throw new Types.V6dFailure(); + } if (ErrorDescription[0].equals("JOINING_HOST_CANNOT_BE_MASTER_OF_OTHER_HOSTS")) { throw new Types.JoiningHostCannotBeMasterOfOtherHosts(); @@ -1081,15 +1209,15 @@ public class Types { throw new Types.CannotFindStatePartition(); } + if (ErrorDescription[0].equals("WLB_AUTHENTICATION_FAILED")) + { + throw new Types.WlbAuthenticationFailed(); + } if (ErrorDescription[0].equals("AUTH_UNKNOWN_TYPE")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; throw new Types.AuthUnknownType(p1); } - if (ErrorDescription[0].equals("WLB_AUTHENTICATION_FAILED")) - { - throw new Types.WlbAuthenticationFailed(); - } if (ErrorDescription[0].equals("NOT_IN_EMERGENCY_MODE")) { throw new Types.NotInEmergencyMode(); @@ -1139,6 +1267,12 @@ public class Types { throw new Types.FeatureRestricted(); } + if (ErrorDescription[0].equals("VDI_CONTAINS_METADATA_OF_THIS_POOL")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; + throw new Types.VdiContainsMetadataOfThisPool(p1, p2); + } if (ErrorDescription[0].equals("CRL_NAME_INVALID")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -1194,18 +1328,33 @@ public class Types String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; throw new Types.SrHasPbd(p1); } - if (ErrorDescription[0].equals("HOST_STILL_BOOTING")) + if (ErrorDescription[0].equals("OPERATION_PARTIALLY_FAILED")) { - throw new Types.HostStillBooting(); + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.OperationPartiallyFailed(p1); } if (ErrorDescription[0].equals("WLB_MALFORMED_REQUEST")) { throw new Types.WlbMalformedRequest(); } + if (ErrorDescription[0].equals("HOST_STILL_BOOTING")) + { + throw new Types.HostStillBooting(); + } + if (ErrorDescription[0].equals("CANNOT_DESTROY_SYSTEM_NETWORK")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.CannotDestroySystemNetwork(p1); + } if (ErrorDescription[0].equals("OBJECT_NOLONGER_EXISTS")) { throw new Types.ObjectNolongerExists(); } + if (ErrorDescription[0].equals("VDI_NOT_IN_MAP")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.VdiNotInMap(p1); + } if (ErrorDescription[0].equals("HOSTS_NOT_HOMOGENEOUS")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -1253,6 +1402,11 @@ public class Types { throw new Types.ImportErrorPrematureEof(); } + if (ErrorDescription[0].equals("NOT_SYSTEM_DOMAIN")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.NotSystemDomain(p1); + } if (ErrorDescription[0].equals("VM_MEMORY_SIZE_TOO_LOW")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -1348,21 +1502,31 @@ public class Types String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; throw new Types.PatchPrecheckFailedPrerequisiteMissing(p1, p2); } + if (ErrorDescription[0].equals("VM_HAS_PCI_ATTACHED")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.VmHasPciAttached(p1); + } + if (ErrorDescription[0].equals("MIRROR_FAILED")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.MirrorFailed(p1); + } if (ErrorDescription[0].equals("WLB_XENSERVER_TIMEOUT")) { throw new Types.WlbXenserverTimeout(); } - if (ErrorDescription[0].equals("VM_SNAPSHOT_WITH_QUIESCE_FAILED")) - { - String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; - throw new Types.VmSnapshotWithQuiesceFailed(p1); - } if (ErrorDescription[0].equals("POOL_AUTH_DISABLE_FAILED_WRONG_CREDENTIALS")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; throw new Types.PoolAuthDisableFailedWrongCredentials(p1, p2); } + if (ErrorDescription[0].equals("VM_SNAPSHOT_WITH_QUIESCE_FAILED")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.VmSnapshotWithQuiesceFailed(p1); + } if (ErrorDescription[0].equals("CERTIFICATE_CORRUPT")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -1392,6 +1556,11 @@ public class Types { throw new Types.HostItsOwnSlave(); } + if (ErrorDescription[0].equals("CANNOT_ADD_VLAN_TO_BOND_SLAVE")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.CannotAddVlanToBondSlave(p1); + } if (ErrorDescription[0].equals("REDO_LOG_IS_ENABLED")) { throw new Types.RedoLogIsEnabled(); @@ -1431,6 +1600,11 @@ public class Types { throw new Types.VmsFailedToCooperate(); } + if (ErrorDescription[0].equals("TOO_MANY_STORAGE_MIGRATES")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.TooManyStorageMigrates(p1); + } if (ErrorDescription[0].equals("NETWORK_CONTAINS_VIF")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -1460,20 +1634,30 @@ public class Types { throw new Types.JoiningHostConnectionFailed(); } + if (ErrorDescription[0].equals("SUBJECT_CANNOT_BE_RESOLVED")) + { + throw new Types.SubjectCannotBeResolved(); + } if (ErrorDescription[0].equals("XEN_VSS_REQ_ERROR_ADDING_VOLUME_TO_SNAPSET_FAILED")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; throw new Types.XenVssReqErrorAddingVolumeToSnapsetFailed(p1, p2); } - if (ErrorDescription[0].equals("SUBJECT_CANNOT_BE_RESOLVED")) - { - throw new Types.SubjectCannotBeResolved(); - } if (ErrorDescription[0].equals("PROVISION_FAILED_OUT_OF_SPACE")) { throw new Types.ProvisionFailedOutOfSpace(); } + if (ErrorDescription[0].equals("VDI_NEEDS_VM_FOR_MIGRATE")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.VdiNeedsVmForMigrate(p1); + } + if (ErrorDescription[0].equals("COULD_NOT_IMPORT_DATABASE")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.CouldNotImportDatabase(p1); + } if (ErrorDescription[0].equals("VDI_IS_NOT_ISO")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -1513,6 +1697,10 @@ public class Types { throw new Types.LicenseDoesNotSupportXha(); } + if (ErrorDescription[0].equals("PIF_INCOMPATIBLE_PRIMARY_ADDRESS_TYPE")) + { + throw new Types.PifIncompatiblePrimaryAddressType(); + } if (ErrorDescription[0].equals("DEVICE_ALREADY_DETACHED")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -1599,6 +1787,18 @@ public class Types String p3 = ErrorDescription.length > 3 ? ErrorDescription[3] : ""; throw new Types.VmDuplicateVbdDevice(p1, p2, p3); } + if (ErrorDescription[0].equals("CANNOT_PLUG_BOND_SLAVE")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + throw new Types.CannotPlugBondSlave(p1); + } + if (ErrorDescription[0].equals("VM_TO_IMPORT_IS_NOT_NEWER_VERSION")) + { + String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; + String p2 = ErrorDescription.length > 2 ? ErrorDescription[2] : ""; + String p3 = ErrorDescription.length > 3 ? ErrorDescription[3] : ""; + throw new Types.VmToImportIsNotNewerVersion(p1, p2, p3); + } if (ErrorDescription[0].equals("CRL_CORRUPT")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -1722,6 +1922,10 @@ public class Types String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; throw new Types.InterfaceHasNoIp(p1); } + if (ErrorDescription[0].equals("HOSTS_NOT_COMPATIBLE")) + { + throw new Types.HostsNotCompatible(); + } if (ErrorDescription[0].equals("AUTH_ENABLE_FAILED_WRONG_CREDENTIALS")) { String p1 = ErrorDescription.length > 1 ? ErrorDescription[1] : ""; @@ -1787,7 +1991,25 @@ public class Types /** * Operations on this VDI are temporarily blocked */ - BLOCKED + BLOCKED; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == SCAN) return "scan"; + if (this == CLONE) return "clone"; + if (this == COPY) return "copy"; + if (this == RESIZE) return "resize"; + if (this == RESIZE_ONLINE) return "resize_online"; + if (this == SNAPSHOT) return "snapshot"; + if (this == DESTROY) return "destroy"; + if (this == FORGET) return "forget"; + if (this == UPDATE) return "update"; + if (this == FORCE_UNLOCK) return "force_unlock"; + if (this == GENERATE_CONFIG) return "generate_config"; + if (this == BLOCKED) return "blocked"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum Cls { @@ -1814,7 +2036,18 @@ public class Types /** * VMPP */ - VMPP + VMPP; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == VM) return "VM"; + if (this == HOST) return "Host"; + if (this == SR) return "SR"; + if (this == POOL) return "Pool"; + if (this == VMPP) return "VMPP"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum VdiType { @@ -1853,7 +2086,21 @@ public class Types /** * a disk used for a general metadata redo-log */ - REDO_LOG + REDO_LOG; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == SYSTEM) return "system"; + if (this == USER) return "user"; + if (this == EPHEMERAL) return "ephemeral"; + if (this == SUSPEND) return "suspend"; + if (this == CRASHDUMP) return "crashdump"; + if (this == HA_STATEFILE) return "ha_statefile"; + if (this == METADATA) return "metadata"; + if (this == REDO_LOG) return "redo_log"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum AfterApplyGuidance { @@ -1876,7 +2123,17 @@ public class Types /** * This patch requires XAPI to be restarted once applied. */ - RESTARTXAPI + RESTARTXAPI; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == RESTARTHVM) return "restartHVM"; + if (this == RESTARTPV) return "restartPV"; + if (this == RESTARTHOST) return "restartHost"; + if (this == RESTARTXAPI) return "restartXAPI"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum EventOperation { @@ -1895,7 +2152,39 @@ public class Types /** * An object has been modified */ - MOD + MOD; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == ADD) return "add"; + if (this == DEL) return "del"; + if (this == MOD) return "mod"; + /* This can never be reached */ + return "illegal enum"; + } + + }; + + public enum PrimaryAddressType { + /** + * The value does not belong to this enumeration + */ + UNRECOGNIZED, + /** + * Primary address is the IPv4 address + */ + IPV4, + /** + * Primary address is the IPv6 address + */ + IPV6; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == IPV4) return "IPv4"; + if (this == IPV6) return "IPv6"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum TaskAllowedOperations { @@ -1906,7 +2195,14 @@ public class Types /** * refers to the operation "cancel" */ - CANCEL + CANCEL; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == CANCEL) return "cancel"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum TaskStatusType { @@ -1933,7 +2229,18 @@ public class Types /** * task has been cancelled */ - CANCELLED + CANCELLED; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == PENDING) return "pending"; + if (this == SUCCESS) return "success"; + if (this == FAILURE) return "failure"; + if (this == CANCELLING) return "cancelling"; + if (this == CANCELLED) return "cancelled"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum NetworkOperations { @@ -1944,7 +2251,14 @@ public class Types /** * Indicates this network is attaching to a VIF or PIF */ - ATTACHING + ATTACHING; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == ATTACHING) return "attaching"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum ConsoleProtocol { @@ -1963,7 +2277,16 @@ public class Types /** * Remote Desktop Protocol */ - RDP + RDP; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == VT100) return "vt100"; + if (this == RFB) return "rfb"; + if (this == RDP) return "rdp"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum OnCrashBehaviour { @@ -1994,7 +2317,19 @@ public class Types /** * rename the crashed VM and start a new copy */ - RENAME_RESTART + RENAME_RESTART; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == DESTROY) return "destroy"; + if (this == COREDUMP_AND_DESTROY) return "coredump_and_destroy"; + if (this == RESTART) return "restart"; + if (this == COREDUMP_AND_RESTART) return "coredump_and_restart"; + if (this == PRESERVE) return "preserve"; + if (this == RENAME_RESTART) return "rename_restart"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum VmppBackupType { @@ -2009,7 +2344,15 @@ public class Types /** * The backup is a checkpoint */ - CHECKPOINT + CHECKPOINT; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == SNAPSHOT) return "snapshot"; + if (this == CHECKPOINT) return "checkpoint"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum OnNormalExit { @@ -2024,7 +2367,15 @@ public class Types /** * restart the VM */ - RESTART + RESTART; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == DESTROY) return "destroy"; + if (this == RESTART) return "restart"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum VifOperations { @@ -2043,7 +2394,16 @@ public class Types /** * Attempting to hot unplug this VIF */ - UNPLUG + UNPLUG; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == ATTACH) return "attach"; + if (this == PLUG) return "plug"; + if (this == UNPLUG) return "unplug"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum XenAPIObjects { @@ -2099,6 +2459,14 @@ public class Types * VM Protection Policy */ VMPP, + /** + * VM appliance + */ + VM_APPLIANCE, + /** + * DR task + */ + DR_TASK, /** * A physical host */ @@ -2140,7 +2508,7 @@ public class Types */ PIF_METRICS, /** - * + * */ BOND, /** @@ -2206,7 +2574,74 @@ public class Types /** * A tunnel for network traffic */ - TUNNEL + TUNNEL, + /** + * A PCI device + */ + PCI, + /** + * A physical GPU (pGPU) + */ + PGPU, + /** + * A group of compatible GPUs across the resource pool + */ + GPU_GROUP, + /** + * A virtual GPU (vGPU) + */ + VGPU; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == SESSION) return "session"; + if (this == AUTH) return "auth"; + if (this == SUBJECT) return "subject"; + if (this == ROLE) return "role"; + if (this == TASK) return "task"; + if (this == EVENT) return "event"; + if (this == POOL) return "pool"; + if (this == POOL_PATCH) return "pool_patch"; + if (this == VM) return "VM"; + if (this == VM_METRICS) return "VM_metrics"; + if (this == VM_GUEST_METRICS) return "VM_guest_metrics"; + if (this == VMPP) return "VMPP"; + if (this == VM_APPLIANCE) return "VM_appliance"; + if (this == DR_TASK) return "DR_task"; + if (this == HOST) return "host"; + if (this == HOST_CRASHDUMP) return "host_crashdump"; + if (this == HOST_PATCH) return "host_patch"; + if (this == HOST_METRICS) return "host_metrics"; + if (this == HOST_CPU) return "host_cpu"; + if (this == NETWORK) return "network"; + if (this == VIF) return "VIF"; + if (this == VIF_METRICS) return "VIF_metrics"; + if (this == PIF) return "PIF"; + if (this == PIF_METRICS) return "PIF_metrics"; + if (this == BOND) return "Bond"; + if (this == VLAN) return "VLAN"; + if (this == SM) return "SM"; + if (this == SR) return "SR"; + if (this == VDI) return "VDI"; + if (this == VBD) return "VBD"; + if (this == VBD_METRICS) return "VBD_metrics"; + if (this == PBD) return "PBD"; + if (this == CRASHDUMP) return "crashdump"; + if (this == VTPM) return "VTPM"; + if (this == CONSOLE) return "console"; + if (this == USER) return "user"; + if (this == DATA_SOURCE) return "data_source"; + if (this == BLOB) return "blob"; + if (this == MESSAGE) return "message"; + if (this == SECRET) return "secret"; + if (this == TUNNEL) return "tunnel"; + if (this == PCI) return "PCI"; + if (this == PGPU) return "PGPU"; + if (this == GPU_GROUP) return "GPU_group"; + if (this == VGPU) return "VGPU"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum HostAllowedOperations { @@ -2245,7 +2680,21 @@ public class Types /** * This host is the migration target of a VM */ - VM_MIGRATE + VM_MIGRATE; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == PROVISION) return "provision"; + if (this == EVACUATE) return "evacuate"; + if (this == SHUTDOWN) return "shutdown"; + if (this == REBOOT) return "reboot"; + if (this == POWER_ON) return "power_on"; + if (this == VM_START) return "vm_start"; + if (this == VM_RESUME) return "vm_resume"; + if (this == VM_MIGRATE) return "vm_migrate"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum VmppArchiveFrequency { @@ -2268,7 +2717,17 @@ public class Types /** * Weekly backups */ - WEEKLY + WEEKLY; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == NEVER) return "never"; + if (this == ALWAYS_AFTER_BACKUP) return "always_after_backup"; + if (this == DAILY) return "daily"; + if (this == WEEKLY) return "weekly"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum VmppArchiveTargetType { @@ -2287,7 +2746,16 @@ public class Types /** * NFS target config */ - NFS + NFS; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == NONE) return "none"; + if (this == CIFS) return "cifs"; + if (this == NFS) return "nfs"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum VbdMode { @@ -2302,7 +2770,48 @@ public class Types /** * read-write access will be allowed */ - RW + RW; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == RO) return "RO"; + if (this == RW) return "RW"; + /* This can never be reached */ + return "illegal enum"; + } + + }; + + public enum Ipv6ConfigurationMode { + /** + * The value does not belong to this enumeration + */ + UNRECOGNIZED, + /** + * Do not acquire an IPv6 address + */ + NONE, + /** + * Acquire an IPv6 address by DHCP + */ + DHCP, + /** + * Static IPv6 address configuration + */ + STATIC, + /** + * Router assigned prefix delegation IPv6 allocation + */ + AUTOCONF; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == NONE) return "None"; + if (this == DHCP) return "DHCP"; + if (this == STATIC) return "Static"; + if (this == AUTOCONF) return "Autoconf"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum VbdType { @@ -2317,7 +2826,15 @@ public class Types /** * VBD will appear to guest as disk */ - DISK + DISK; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == CD) return "CD"; + if (this == DISK) return "Disk"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum OnBoot { @@ -2332,7 +2849,48 @@ public class Types /** * Standard behaviour. */ - PERSIST + PERSIST; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == RESET) return "reset"; + if (this == PERSIST) return "persist"; + /* This can never be reached */ + return "illegal enum"; + } + + }; + + public enum VmApplianceOperation { + /** + * The value does not belong to this enumeration + */ + UNRECOGNIZED, + /** + * Start + */ + START, + /** + * Clean shutdown + */ + CLEAN_SHUTDOWN, + /** + * Hard shutdown + */ + HARD_SHUTDOWN, + /** + * Shutdown + */ + SHUTDOWN; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == START) return "start"; + if (this == CLEAN_SHUTDOWN) return "clean_shutdown"; + if (this == HARD_SHUTDOWN) return "hard_shutdown"; + if (this == SHUTDOWN) return "shutdown"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum VbdOperations { @@ -2371,7 +2929,21 @@ public class Types /** * Attempting to unpause a block device backend */ - UNPAUSE + UNPAUSE; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == ATTACH) return "attach"; + if (this == EJECT) return "eject"; + if (this == INSERT) return "insert"; + if (this == PLUG) return "plug"; + if (this == UNPLUG) return "unplug"; + if (this == UNPLUG_FORCE) return "unplug_force"; + if (this == PAUSE) return "pause"; + if (this == UNPAUSE) return "unpause"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum VmppBackupFrequency { @@ -2390,7 +2962,39 @@ public class Types /** * Weekly backups */ - WEEKLY + WEEKLY; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == HOURLY) return "hourly"; + if (this == DAILY) return "daily"; + if (this == WEEKLY) return "weekly"; + /* This can never be reached */ + return "illegal enum"; + } + + }; + + public enum NetworkDefaultLockingMode { + /** + * The value does not belong to this enumeration + */ + UNRECOGNIZED, + /** + * Treat all VIFs on this network with locking_mode = 'default' as if they have locking_mode = 'unlocked' + */ + UNLOCKED, + /** + * Treat all VIFs on this network with locking_mode = 'default' as if they have locking_mode = 'disabled' + */ + DISABLED; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == UNLOCKED) return "unlocked"; + if (this == DISABLED) return "disabled"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum VmPowerState { @@ -2413,7 +3017,17 @@ public class Types /** * VM state has been saved to disk and it is nolonger running. Note that disks remain in-use while the VM is suspended. */ - SUSPENDED + SUSPENDED; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == HALTED) return "Halted"; + if (this == PAUSED) return "Paused"; + if (this == RUNNING) return "Running"; + if (this == SUSPENDED) return "Suspended"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum VmOperations { @@ -2510,9 +3124,9 @@ public class Types */ POOL_MIGRATE, /** - * refers to the operation "migrate" + * refers to the operation "migrate_send" */ - MIGRATE, + MIGRATE_SEND, /** * refers to the operation "get_boot_record" */ @@ -2525,6 +3139,10 @@ public class Types * refers to the operation "send_trigger" */ SEND_TRIGGER, + /** + * refers to the operation "query_services" + */ + QUERY_SERVICES, /** * Changing the memory settings */ @@ -2545,10 +3163,6 @@ public class Types * Changing the memory limits */ CHANGING_MEMORY_LIMITS, - /** - * Querying the co-operativeness of the VM - */ - GET_COOPERATIVE, /** * Changing the shadow memory for a halted VM. */ @@ -2566,7 +3180,7 @@ public class Types */ CHANGING_VCPUS_LIVE, /** - * + * */ ASSERT_OPERATION_VALID, /** @@ -2574,7 +3188,7 @@ public class Types */ DATA_SOURCE_OP, /** - * + * */ UPDATE_ALLOWED_OPERATIONS, /** @@ -2600,7 +3214,86 @@ public class Types /** * refers to the act of uninstalling the VM */ - DESTROY + DESTROY; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == SNAPSHOT) return "snapshot"; + if (this == CLONE) return "clone"; + if (this == COPY) return "copy"; + if (this == CREATE_TEMPLATE) return "create_template"; + if (this == REVERT) return "revert"; + if (this == CHECKPOINT) return "checkpoint"; + if (this == SNAPSHOT_WITH_QUIESCE) return "snapshot_with_quiesce"; + if (this == PROVISION) return "provision"; + if (this == START) return "start"; + if (this == START_ON) return "start_on"; + if (this == PAUSE) return "pause"; + if (this == UNPAUSE) return "unpause"; + if (this == CLEAN_SHUTDOWN) return "clean_shutdown"; + if (this == CLEAN_REBOOT) return "clean_reboot"; + if (this == HARD_SHUTDOWN) return "hard_shutdown"; + if (this == POWER_STATE_RESET) return "power_state_reset"; + if (this == HARD_REBOOT) return "hard_reboot"; + if (this == SUSPEND) return "suspend"; + if (this == CSVM) return "csvm"; + if (this == RESUME) return "resume"; + if (this == RESUME_ON) return "resume_on"; + if (this == POOL_MIGRATE) return "pool_migrate"; + if (this == MIGRATE_SEND) return "migrate_send"; + if (this == GET_BOOT_RECORD) return "get_boot_record"; + if (this == SEND_SYSRQ) return "send_sysrq"; + if (this == SEND_TRIGGER) return "send_trigger"; + if (this == QUERY_SERVICES) return "query_services"; + if (this == CHANGING_MEMORY_LIVE) return "changing_memory_live"; + if (this == AWAITING_MEMORY_LIVE) return "awaiting_memory_live"; + if (this == CHANGING_DYNAMIC_RANGE) return "changing_dynamic_range"; + if (this == CHANGING_STATIC_RANGE) return "changing_static_range"; + if (this == CHANGING_MEMORY_LIMITS) return "changing_memory_limits"; + if (this == CHANGING_SHADOW_MEMORY) return "changing_shadow_memory"; + if (this == CHANGING_SHADOW_MEMORY_LIVE) return "changing_shadow_memory_live"; + if (this == CHANGING_VCPUS) return "changing_VCPUs"; + if (this == CHANGING_VCPUS_LIVE) return "changing_VCPUs_live"; + if (this == ASSERT_OPERATION_VALID) return "assert_operation_valid"; + if (this == DATA_SOURCE_OP) return "data_source_op"; + if (this == UPDATE_ALLOWED_OPERATIONS) return "update_allowed_operations"; + if (this == MAKE_INTO_TEMPLATE) return "make_into_template"; + if (this == IMPORT) return "import"; + if (this == EXPORT) return "export"; + if (this == METADATA_EXPORT) return "metadata_export"; + if (this == REVERTING) return "reverting"; + if (this == DESTROY) return "destroy"; + /* This can never be reached */ + return "illegal enum"; + } + + }; + + public enum BondMode { + /** + * The value does not belong to this enumeration + */ + UNRECOGNIZED, + /** + * Source-level balancing + */ + BALANCE_SLB, + /** + * Active/passive bonding: only one NIC is carrying traffic + */ + ACTIVE_BACKUP, + /** + * Link aggregation control protocol + */ + LACP; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == BALANCE_SLB) return "balance-slb"; + if (this == ACTIVE_BACKUP) return "active-backup"; + if (this == LACP) return "lacp"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum IpConfigurationMode { @@ -2619,7 +3312,16 @@ public class Types /** * Static IP address configuration */ - STATIC + STATIC; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == NONE) return "None"; + if (this == DHCP) return "DHCP"; + if (this == STATIC) return "Static"; + /* This can never be reached */ + return "illegal enum"; + } + }; public enum StorageOperations { @@ -2674,7 +3376,68 @@ public class Types /** * Snapshotting a VDI */ - VDI_SNAPSHOT + VDI_SNAPSHOT, + /** + * Creating a PBD for this SR + */ + PBD_CREATE, + /** + * Destroying one of this SR's PBDs + */ + PBD_DESTROY; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == SCAN) return "scan"; + if (this == DESTROY) return "destroy"; + if (this == FORGET) return "forget"; + if (this == PLUG) return "plug"; + if (this == UNPLUG) return "unplug"; + if (this == UPDATE) return "update"; + if (this == VDI_CREATE) return "vdi_create"; + if (this == VDI_INTRODUCE) return "vdi_introduce"; + if (this == VDI_DESTROY) return "vdi_destroy"; + if (this == VDI_RESIZE) return "vdi_resize"; + if (this == VDI_CLONE) return "vdi_clone"; + if (this == VDI_SNAPSHOT) return "vdi_snapshot"; + if (this == PBD_CREATE) return "pbd_create"; + if (this == PBD_DESTROY) return "pbd_destroy"; + /* This can never be reached */ + return "illegal enum"; + } + + }; + + public enum VifLockingMode { + /** + * The value does not belong to this enumeration + */ + UNRECOGNIZED, + /** + * No specific configuration set - default network policy applies + */ + NETWORK_DEFAULT, + /** + * Only traffic to a specific MAC and a list of IPv4 or IPv6 addresses is permitted + */ + LOCKED, + /** + * All traffic is permitted + */ + UNLOCKED, + /** + * No traffic is permitted + */ + DISABLED; + public String toString() { + if (this == UNRECOGNIZED) return "UNRECOGNIZED"; + if (this == NETWORK_DEFAULT) return "network_default"; + if (this == LOCKED) return "locked"; + if (this == UNLOCKED) return "unlocked"; + if (this == DISABLED) return "disabled"; + /* This can never be reached */ + return "illegal enum"; + } + }; @@ -2821,6 +3584,24 @@ public class Types } + /** + * The GPU group contains active PGPUs and cannot be deleted. + */ + public static class GpuGroupContainsPgpu extends XenAPIException { + public final String pgpus; + + /** + * Create a new GpuGroupContainsPgpu + * + * @param pgpus + */ + public GpuGroupContainsPgpu(String pgpus) { + super("The GPU group contains active PGPUs and cannot be deleted."); + this.pgpus = pgpus; + } + + } + /** * Operation cannot proceed while a tunnel exists on this interface. */ @@ -2871,6 +3652,24 @@ public class Types } + /** + * The disaster recovery task could not be cleanly destroyed. + */ + public static class CannotDestroyDisasterRecoveryTask extends XenAPIException { + public final String reason; + + /** + * Create a new CannotDestroyDisasterRecoveryTask + * + * @param reason + */ + public CannotDestroyDisasterRecoveryTask(String reason) { + super("The disaster recovery task could not be cleanly destroyed."); + this.reason = reason; + } + + } + /** * You tried to create a VLAN, but the tag you gave was invalid -- it must be between 0 and 4094. The parameter echoes the VLAN tag you gave. */ @@ -3044,6 +3843,24 @@ public class Types } + /** + * You attempted to run a VM on a host which doesn't have I/O virtualisation (IOMMU/VT-d) enabled, which is needed by the VM. + */ + public static class VmRequiresIommu extends XenAPIException { + public final String host; + + /** + * Create a new VmRequiresIommu + * + * @param host + */ + public VmRequiresIommu(String host) { + super("You attempted to run a VM on a host which doesn't have I/O virtualisation (IOMMU/VT-d) enabled, which is needed by the VM."); + this.host = host; + } + + } + /** * The operation failed because the HA software on the specified host could not see a subset of other hosts. Check your network connectivity. */ @@ -3235,6 +4052,24 @@ public class Types } + /** + * You attempted to migrate a VM with more than one snapshot. + */ + public static class VmHasTooManySnapshots extends XenAPIException { + public final String vm; + + /** + * Create a new VmHasTooManySnapshots + * + * @param vm + */ + public VmHasTooManySnapshots(String vm) { + super("You attempted to migrate a VM with more than one snapshot."); + this.vm = vm; + } + + } + /** * The patch apply failed. Please see attached output. */ @@ -3292,6 +4127,27 @@ public class Types } + /** + * You attempted to run a VM on a host which doesn't have a pGPU available in the GPU group needed by the VM. The VM has a vGPU attached to this GPU group. + */ + public static class VmRequiresGpu extends XenAPIException { + public final String vm; + public final String GPUGroup; + + /** + * Create a new VmRequiresGpu + * + * @param vm + * @param GPUGroup + */ + public VmRequiresGpu(String vm, String GPUGroup) { + super("You attempted to run a VM on a host which doesn't have a pGPU available in the GPU group needed by the VM. The VM has a vGPU attached to this GPU group."); + this.vm = vm; + this.GPUGroup = GPUGroup; + } + + } + /** * This operation cannot be performed because this VDI could not be properly attached to the VM. */ @@ -3450,6 +4306,24 @@ public class Types } + /** + * The VM is set up to use a feature that requires it to boot as HVM. + */ + public static class FeatureRequiresHvm extends XenAPIException { + public final String details; + + /** + * Create a new FeatureRequiresHvm + * + * @param details + */ + public FeatureRequiresHvm(String details) { + super("The VM is set up to use a feature that requires it to boot as HVM."); + this.details = details; + } + + } + /** * The operation could not proceed because necessary VDIs were already locked at the storage level. */ @@ -3579,6 +4453,24 @@ public class Types } + /** + * The GPU group contains active VGPUs and cannot be deleted. + */ + public static class GpuGroupContainsVgpu extends XenAPIException { + public final String vgpus; + + /** + * Create a new GpuGroupContainsVgpu + * + * @param vgpus + */ + public GpuGroupContainsVgpu(String vgpus) { + super("The GPU group contains active VGPUs and cannot be deleted."); + this.vgpus = vgpus; + } + + } + /** * The pool failed to enable external authentication. */ @@ -3689,6 +4581,24 @@ public class Types } + /** + * This PIF is a bond slave and cannot have a tunnel on it. + */ + public static class CannotAddTunnelToBondSlave extends XenAPIException { + public final String PIF; + + /** + * Create a new CannotAddTunnelToBondSlave + * + * @param PIF + */ + public CannotAddTunnelToBondSlave(String PIF) { + super("This PIF is a bond slave and cannot have a tunnel on it."); + this.PIF = PIF; + } + + } + /** * The uploaded patch file is invalid */ @@ -3777,6 +4687,41 @@ public class Types } + /** + * PIF has no IPv6 configuration (mode curently set to 'none') + */ + public static class PifHasNoV6NetworkConfiguration extends XenAPIException { + + /** + * Create a new PifHasNoV6NetworkConfiguration + */ + public PifHasNoV6NetworkConfiguration() { + super("PIF has no IPv6 configuration (mode curently set to 'none')"); + } + + } + + /** + * This operation is not allowed as the VM is part of an appliance. + */ + public static class VmIsPartOfAnAppliance extends XenAPIException { + public final String vm; + public final String appliance; + + /** + * Create a new VmIsPartOfAnAppliance + * + * @param vm + * @param appliance + */ + public VmIsPartOfAnAppliance(String vm, String appliance) { + super("This operation is not allowed as the VM is part of an appliance."); + this.vm = vm; + this.appliance = appliance; + } + + } + /** * The WLB server reported that XenServer rejected its configured authentication details. */ @@ -4167,6 +5112,44 @@ public class Types } + /** + * The VM is incompatible with the CPU features of this host. + */ + public static class VmIncompatibleWithThisHost extends XenAPIException { + public final String vm; + public final String host; + public final String reason; + + /** + * Create a new VmIncompatibleWithThisHost + * + * @param vm + * @param host + * @param reason + */ + public VmIncompatibleWithThisHost(String vm, String host, String reason) { + super("The VM is incompatible with the CPU features of this host."); + this.vm = vm; + this.host = host; + this.reason = reason; + } + + } + + /** + * The upper limit of active redo log instances was reached. + */ + public static class NoMoreRedoLogsAllowed extends XenAPIException { + + /** + * Create a new NoMoreRedoLogsAllowed + */ + public NoMoreRedoLogsAllowed() { + super("The upper limit of active redo log instances was reached."); + } + + } + /** * The pool failed to enable external authentication. */ @@ -4386,6 +5369,27 @@ public class Types } + /** + * This VM operation cannot be performed on an older-versioned host during an upgrade. + */ + public static class VmHostIncompatibleVersion extends XenAPIException { + public final String host; + public final String vm; + + /** + * Create a new VmHostIncompatibleVersion + * + * @param host + * @param vm + */ + public VmHostIncompatibleVersion(String host, String vm) { + super("This VM operation cannot be performed on an older-versioned host during an upgrade."); + this.host = host; + this.vm = vm; + } + + } + /** * Cannot join pool whose external authentication configuration is different. */ @@ -4400,6 +5404,24 @@ public class Types } + /** + * All VBDs of type 'disk' must be read/write for HVM guests + */ + public static class DiskVbdMustBeReadwriteForHvm extends XenAPIException { + public final String vbd; + + /** + * Create a new DiskVbdMustBeReadwriteForHvm + * + * @param vbd + */ + public DiskVbdMustBeReadwriteForHvm(String vbd) { + super("All VBDs of type 'disk' must be read/write for HVM guests"); + this.vbd = vbd; + } + + } + /** * The BIOS strings for this VM have already been set and cannot be changed anymore. */ @@ -4563,6 +5585,84 @@ public class Types } + /** + * You attempted to migrate a VM which has a checkpoint. + */ + public static class VmHasCheckpoint extends XenAPIException { + public final String vm; + + /** + * Create a new VmHasCheckpoint + * + * @param vm + */ + public VmHasCheckpoint(String vm) { + super("You attempted to migrate a VM which has a checkpoint."); + this.vm = vm; + } + + } + + /** + * The SM plugin did not respond to a query. + */ + public static class SmPluginCommunicationFailure extends XenAPIException { + public final String sm; + + /** + * Create a new SmPluginCommunicationFailure + * + * @param sm + */ + public SmPluginCommunicationFailure(String sm) { + super("The SM plugin did not respond to a query."); + this.sm = sm; + } + + } + + /** + * This VM is assigned to a protection policy. + */ + public static class VmAssignedToProtectionPolicy extends XenAPIException { + public final String vm; + public final String vmpp; + + /** + * Create a new VmAssignedToProtectionPolicy + * + * @param vm + * @param vmpp + */ + public VmAssignedToProtectionPolicy(String vm, String vmpp) { + super("This VM is assigned to a protection policy."); + this.vm = vm; + this.vmpp = vmpp; + } + + } + + /** + * RBAC permission denied. + */ + public static class RbacPermissionDenied extends XenAPIException { + public final String permission; + public final String message; + + /** + * Create a new RbacPermissionDenied + * + * @param permission + * @param message + */ + public RbacPermissionDenied(String permission, String message) { + super("RBAC permission denied."); + this.permission = permission; + this.message = message; + } + + } + /** * The host failed to disable external authentication. */ @@ -4595,27 +5695,6 @@ public class Types } - /** - * RBAC permission denied. - */ - public static class RbacPermissionDenied extends XenAPIException { - public final String permission; - public final String message; - - /** - * Create a new RbacPermissionDenied - * - * @param permission - * @param message - */ - public RbacPermissionDenied(String permission, String message) { - super("RBAC permission denied."); - this.permission = permission; - this.message = message; - } - - } - /** * The request was rejected because there are too many pending tasks on the server. */ @@ -4648,6 +5727,20 @@ public class Types } + /** + * This operation cannot be performed because creating or deleting a bond involving the management interface is not allowed while HA is on. In order to do that, disable HA, create or delete the bond then re-enable HA. + */ + public static class HaCannotChangeBondStatusOfMgmtIface extends XenAPIException { + + /** + * Create a new HaCannotChangeBondStatusOfMgmtIface + */ + public HaCannotChangeBondStatusOfMgmtIface() { + super("This operation cannot be performed because creating or deleting a bond involving the management interface is not allowed while HA is on. In order to do that, disable HA, create or delete the bond then re-enable HA."); + } + + } + /** * This patch has already been applied */ @@ -4702,6 +5795,30 @@ public class Types } + /** + * The patch precheck stage failed: the server is of an incorrect build. + */ + public static class PatchPrecheckFailedWrongServerBuild extends XenAPIException { + public final String patch; + public final String foundBuild; + public final String requiredBuild; + + /** + * Create a new PatchPrecheckFailedWrongServerBuild + * + * @param patch + * @param foundBuild + * @param requiredBuild + */ + public PatchPrecheckFailedWrongServerBuild(String patch, String foundBuild, String requiredBuild) { + super("The patch precheck stage failed: the server is of an incorrect build."); + this.patch = patch; + this.foundBuild = foundBuild; + this.requiredBuild = requiredBuild; + } + + } + /** * The given feature string is not valid. */ @@ -4790,6 +5907,20 @@ public class Types } + /** + * Role already exists. + */ + public static class RoleAlreadyExists extends XenAPIException { + + /** + * Create a new RoleAlreadyExists + */ + public RoleAlreadyExists() { + super("Role already exists."); + } + + } + /** * The network contains active PIFs and cannot be deleted. */ @@ -4809,15 +5940,22 @@ public class Types } /** - * Role already exists. + * Could not find a network interface with the specified device name and MAC address. */ - public static class RoleAlreadyExists extends XenAPIException { + public static class CouldNotFindNetworkInterfaceWithSpecifiedDeviceNameAndMacAddress extends XenAPIException { + public final String device; + public final String mac; /** - * Create a new RoleAlreadyExists + * Create a new CouldNotFindNetworkInterfaceWithSpecifiedDeviceNameAndMacAddress + * + * @param device + * @param mac */ - public RoleAlreadyExists() { - super("Role already exists."); + public CouldNotFindNetworkInterfaceWithSpecifiedDeviceNameAndMacAddress(String device, String mac) { + super("Could not find a network interface with the specified device name and MAC address."); + this.device = device; + this.mac = mac; } } @@ -5002,6 +6140,27 @@ public class Types } + /** + * The specified VBD device is not recognised: please use a non-negative integer + */ + public static class IllegalVbdDevice extends XenAPIException { + public final String vbd; + public final String device; + + /** + * Create a new IllegalVbdDevice + * + * @param vbd + * @param device + */ + public IllegalVbdDevice(String vbd, String device) { + super("The specified VBD device is not recognised: please use a non-negative integer"); + this.vbd = vbd; + this.device = device; + } + + } + /** * The specified CRL does not exist. */ @@ -5229,6 +6388,24 @@ public class Types } + /** + * The event.from token could not be parsed. Valid values include: '', and a value returned from a previous event.from call. + */ + public static class EventFromTokenParseFailure extends XenAPIException { + public final String token; + + /** + * Create a new EventFromTokenParseFailure + * + * @param token + */ + public EventFromTokenParseFailure(String token) { + super("The event.from token could not be parsed. Valid values include: '', and a value returned from a previous event.from call."); + this.token = token; + } + + } + /** * The operation cannot be performed until the SR has been upgraded */ @@ -5625,6 +6802,24 @@ public class Types } + /** + * The server failed to parse your event subscription. Valid values include: *, class-name, class-name/object-reference. + */ + public static class EventSubscriptionParseFailure extends XenAPIException { + public final String subscription; + + /** + * Create a new EventSubscriptionParseFailure + * + * @param subscription + */ + public EventSubscriptionParseFailure(String subscription) { + super("The server failed to parse your event subscription. Valid values include: *, class-name, class-name/object-reference."); + this.subscription = subscription; + } + + } + /** * Your license has expired. Please contact your support representative. */ @@ -5685,6 +6880,20 @@ public class Types } + /** + * There was a problem with the license daemon (v6d). Is it running? + */ + public static class V6dFailure extends XenAPIException { + + /** + * Create a new V6dFailure + */ + public V6dFailure() { + super("There was a problem with the license daemon (v6d). Is it running?"); + } + + } + /** * The host joining the pool cannot already be a master of another pool. */ @@ -5848,6 +7057,20 @@ public class Types } + /** + * The WLB server rejected our configured authentication details. + */ + public static class WlbAuthenticationFailed extends XenAPIException { + + /** + * Create a new WlbAuthenticationFailed + */ + public WlbAuthenticationFailed() { + super("The WLB server rejected our configured authentication details."); + } + + } + /** * Unknown type of external authentication. */ @@ -5866,20 +7089,6 @@ public class Types } - /** - * The WLB server rejected our configured authentication details. - */ - public static class WlbAuthenticationFailed extends XenAPIException { - - /** - * Create a new WlbAuthenticationFailed - */ - public WlbAuthenticationFailed() { - super("The WLB server rejected our configured authentication details."); - } - - } - /** * This pool is not in emergency mode. */ @@ -6054,6 +7263,27 @@ public class Types } + /** + * The VDI could not be opened for metadata recovery as it contains the current pool's metadata. + */ + public static class VdiContainsMetadataOfThisPool extends XenAPIException { + public final String vdi; + public final String pool; + + /** + * Create a new VdiContainsMetadataOfThisPool + * + * @param vdi + * @param pool + */ + public VdiContainsMetadataOfThisPool(String vdi, String pool) { + super("The VDI could not be opened for metadata recovery as it contains the current pool's metadata."); + this.vdi = vdi; + this.pool = pool; + } + + } + /** * The specified CRL name is invalid. */ @@ -6230,7 +7460,7 @@ public class Types } /** - * The SR is still connected to a host via a PBD. It cannot be destroyed. + * The SR is still connected to a host via a PBD. It cannot be destroyed or forgotten. */ public static class SrHasPbd extends XenAPIException { public final String sr; @@ -6241,22 +7471,26 @@ public class Types * @param sr */ public SrHasPbd(String sr) { - super("The SR is still connected to a host via a PBD. It cannot be destroyed."); + super("The SR is still connected to a host via a PBD. It cannot be destroyed or forgotten."); this.sr = sr; } } /** - * The host is still booting. + * Some VMs belonging to the appliance threw an exception while carrying out the specified operation */ - public static class HostStillBooting extends XenAPIException { + public static class OperationPartiallyFailed extends XenAPIException { + public final String operation; /** - * Create a new HostStillBooting + * Create a new OperationPartiallyFailed + * + * @param operation */ - public HostStillBooting() { - super("The host is still booting."); + public OperationPartiallyFailed(String operation) { + super("Some VMs belonging to the appliance threw an exception while carrying out the specified operation"); + this.operation = operation; } } @@ -6275,6 +7509,38 @@ public class Types } + /** + * The host toolstack is still initialising. Please wait. + */ + public static class HostStillBooting extends XenAPIException { + + /** + * Create a new HostStillBooting + */ + public HostStillBooting() { + super("The host toolstack is still initialising. Please wait."); + } + + } + + /** + * You tried to destroy a system network: these cannot be destroyed. + */ + public static class CannotDestroySystemNetwork extends XenAPIException { + public final String network; + + /** + * Create a new CannotDestroySystemNetwork + * + * @param network + */ + public CannotDestroySystemNetwork(String network) { + super("You tried to destroy a system network: these cannot be destroyed."); + this.network = network; + } + + } + /** * The specified object no longer exists. */ @@ -6289,6 +7555,24 @@ public class Types } + /** + * This VDI was not mapped to a destination SR in VM.migrate_send operation + */ + public static class VdiNotInMap extends XenAPIException { + public final String vdi; + + /** + * Create a new VdiNotInMap + * + * @param vdi + */ + public VdiNotInMap(String vdi) { + super("This VDI was not mapped to a destination SR in VM.migrate_send operation"); + this.vdi = vdi; + } + + } + /** * The hosts in this pool are not homogeneous. */ @@ -6390,7 +7674,7 @@ public class Types } /** - * The edition name you supplied is invalid. + * The edition you supplied is invalid. */ public static class InvalidEdition extends XenAPIException { public final String edition; @@ -6401,7 +7685,7 @@ public class Types * @param edition */ public InvalidEdition(String edition) { - super("The edition name you supplied is invalid."); + super("The edition you supplied is invalid."); this.edition = edition; } @@ -6457,6 +7741,24 @@ public class Types } + /** + * The given VM is not registered as a system domain. This operation can only be performed on a registered system domain. + */ + public static class NotSystemDomain extends XenAPIException { + public final String vm; + + /** + * Create a new NotSystemDomain + * + * @param vm + */ + public NotSystemDomain(String vm) { + super("The given VM is not registered as a system domain. This operation can only be performed on a registered system domain."); + this.vm = vm; + } + + } + /** * The specified VM has too little memory to be started. */ @@ -6476,7 +7778,7 @@ public class Types } /** - * There is at least on VM assigned to this protection policy. + * There is at least one VM assigned to this protection policy. */ public static class VmppHasVm extends XenAPIException { @@ -6484,7 +7786,7 @@ public class Types * Create a new VmppHasVm */ public VmppHasVm() { - super("There is at least on VM assigned to this protection policy."); + super("There is at least one VM assigned to this protection policy."); } } @@ -6791,6 +8093,42 @@ public class Types } + /** + * This operation could not be performed, because the VM has one or more PCI devices passed through. + */ + public static class VmHasPciAttached extends XenAPIException { + public final String vm; + + /** + * Create a new VmHasPciAttached + * + * @param vm + */ + public VmHasPciAttached(String vm) { + super("This operation could not be performed, because the VM has one or more PCI devices passed through."); + this.vm = vm; + } + + } + + /** + * The VDI mirroring cannot be performed + */ + public static class MirrorFailed extends XenAPIException { + public final String vdi; + + /** + * Create a new MirrorFailed + * + * @param vdi + */ + public MirrorFailed(String vdi) { + super("The VDI mirroring cannot be performed"); + this.vdi = vdi; + } + + } + /** * The WLB server reported that communication with XenServer timed out. */ @@ -6805,24 +8143,6 @@ public class Types } - /** - * The quiesced-snapshot operation failed for an unexpected reason - */ - public static class VmSnapshotWithQuiesceFailed extends XenAPIException { - public final String vm; - - /** - * Create a new VmSnapshotWithQuiesceFailed - * - * @param vm - */ - public VmSnapshotWithQuiesceFailed(String vm) { - super("The quiesced-snapshot operation failed for an unexpected reason"); - this.vm = vm; - } - - } - /** * The pool failed to disable the external authentication of at least one host. */ @@ -6844,6 +8164,24 @@ public class Types } + /** + * The quiesced-snapshot operation failed for an unexpected reason + */ + public static class VmSnapshotWithQuiesceFailed extends XenAPIException { + public final String vm; + + /** + * Create a new VmSnapshotWithQuiesceFailed + * + * @param vm + */ + public VmSnapshotWithQuiesceFailed(String vm) { + super("The quiesced-snapshot operation failed for an unexpected reason"); + this.vm = vm; + } + + } + /** * The specified certificate is corrupt or unreadable. */ @@ -6947,6 +8285,24 @@ public class Types } + /** + * This PIF is a bond slave and cannot have a VLAN on it. + */ + public static class CannotAddVlanToBondSlave extends XenAPIException { + public final String PIF; + + /** + * Create a new CannotAddVlanToBondSlave + * + * @param PIF + */ + public CannotAddVlanToBondSlave(String PIF) { + super("This PIF is a bond slave and cannot have a VLAN on it."); + this.PIF = PIF; + } + + } + /** * The operation could not be performed because a redo log is enabled on the Pool. */ @@ -7086,6 +8442,24 @@ public class Types } + /** + * You reached the maximal number of concurrently migrating VMs. + */ + public static class TooManyStorageMigrates extends XenAPIException { + public final String number; + + /** + * Create a new TooManyStorageMigrates + * + * @param number + */ + public TooManyStorageMigrates(String number) { + super("You reached the maximal number of concurrently migrating VMs."); + this.number = number; + } + + } + /** * The network contains active VIFs and cannot be deleted. */ @@ -7189,6 +8563,20 @@ public class Types } + /** + * Subject cannot be resolved by the external directory service. + */ + public static class SubjectCannotBeResolved extends XenAPIException { + + /** + * Create a new SubjectCannotBeResolved + */ + public SubjectCannotBeResolved() { + super("Subject cannot be resolved by the external directory service."); + } + + } + /** * Some volumes to be snapshot could not be added to the VSS snapshot set */ @@ -7210,20 +8598,6 @@ public class Types } - /** - * Subject cannot be resolved by the external directory service. - */ - public static class SubjectCannotBeResolved extends XenAPIException { - - /** - * Create a new SubjectCannotBeResolved - */ - public SubjectCannotBeResolved() { - super("Subject cannot be resolved by the external directory service."); - } - - } - /** * The provision call failed because it ran out of space. */ @@ -7238,6 +8612,42 @@ public class Types } + /** + * You attempted to migrate a VDI which is not attached to a runnning VM. + */ + public static class VdiNeedsVmForMigrate extends XenAPIException { + public final String vdi; + + /** + * Create a new VdiNeedsVmForMigrate + * + * @param vdi + */ + public VdiNeedsVmForMigrate(String vdi) { + super("You attempted to migrate a VDI which is not attached to a runnning VM."); + this.vdi = vdi; + } + + } + + /** + * An error occurred while attempting to import a database from a metadata VDI + */ + public static class CouldNotImportDatabase extends XenAPIException { + public final String reason; + + /** + * Create a new CouldNotImportDatabase + * + * @param reason + */ + public CouldNotImportDatabase(String reason) { + super("An error occurred while attempting to import a database from a metadata VDI"); + this.reason = reason; + } + + } + /** * This operation can only be performed on CD VDIs (iso files or CDROM drives) */ @@ -7377,6 +8787,20 @@ public class Types } + /** + * The primary address types are not compatible + */ + public static class PifIncompatiblePrimaryAddressType extends XenAPIException { + + /** + * Create a new PifIncompatiblePrimaryAddressType + */ + public PifIncompatiblePrimaryAddressType() { + super("The primary address types are not compatible"); + } + + } + /** * The device is not currently attached */ @@ -7681,6 +9105,48 @@ public class Types } + /** + * This PIF is a bond slave and cannot be plugged. + */ + public static class CannotPlugBondSlave extends XenAPIException { + public final String PIF; + + /** + * Create a new CannotPlugBondSlave + * + * @param PIF + */ + public CannotPlugBondSlave(String PIF) { + super("This PIF is a bond slave and cannot be plugged."); + this.PIF = PIF; + } + + } + + /** + * The VM cannot be imported unforced because it is either the same version or an older version of an existing VM. + */ + public static class VmToImportIsNotNewerVersion extends XenAPIException { + public final String vm; + public final String existingVersion; + public final String versionToImport; + + /** + * Create a new VmToImportIsNotNewerVersion + * + * @param vm + * @param existingVersion + * @param versionToImport + */ + public VmToImportIsNotNewerVersion(String vm, String existingVersion, String versionToImport) { + super("The VM cannot be imported unforced because it is either the same version or an older version of an existing VM."); + this.vm = vm; + this.existingVersion = existingVersion; + this.versionToImport = versionToImport; + } + + } + /** * The specified CRL is corrupt or unreadable. */ @@ -8064,7 +9530,7 @@ public class Types } /** - * This operation is not supported during an upgrade + * This operation is not supported during an upgrade. */ public static class NotSupportedDuringUpgrade extends XenAPIException { @@ -8072,7 +9538,7 @@ public class Types * Create a new NotSupportedDuringUpgrade */ public NotSupportedDuringUpgrade() { - super("This operation is not supported during an upgrade"); + super("This operation is not supported during an upgrade."); } } @@ -8116,6 +9582,20 @@ public class Types } + /** + * The hosts in this pool are not compatible. + */ + public static class HostsNotCompatible extends XenAPIException { + + /** + * Create a new HostsNotCompatible + */ + public HostsNotCompatible() { + super("The hosts in this pool are not compatible."); + } + + } + /** * The host failed to enable external authentication. */ @@ -8170,8 +9650,8 @@ public class Types try { return (Date) object; } catch (ClassCastException e){ - //Occasionally the date comes back as an ocaml float rather than - //in the xmlrpc format! Catch this and convert. + //Occasionally the date comes back as an ocaml float rather than + //in the xmlrpc format! Catch this and convert. return (new Date((long) (1000*Double.parseDouble((String) object)))); } } @@ -8181,7 +9661,7 @@ public class Types return null; } try { - return XenAPIObjects.valueOf(((String) object).toUpperCase()); + return XenAPIObjects.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return XenAPIObjects.UNRECOGNIZED; } @@ -8192,18 +9672,29 @@ public class Types return null; } try { - return AfterApplyGuidance.valueOf(((String) object).toUpperCase()); + return AfterApplyGuidance.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return AfterApplyGuidance.UNRECOGNIZED; } } + public static Types.BondMode toBondMode(Object object) { + if (object == null) { + return null; + } + try { + return BondMode.valueOf(((String) object).toUpperCase().replace('-','_')); + } catch (IllegalArgumentException ex) { + return BondMode.UNRECOGNIZED; + } + } + public static Types.Cls toCls(Object object) { if (object == null) { return null; } try { - return Cls.valueOf(((String) object).toUpperCase()); + return Cls.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return Cls.UNRECOGNIZED; } @@ -8214,7 +9705,7 @@ public class Types return null; } try { - return ConsoleProtocol.valueOf(((String) object).toUpperCase()); + return ConsoleProtocol.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return ConsoleProtocol.UNRECOGNIZED; } @@ -8225,7 +9716,7 @@ public class Types return null; } try { - return EventOperation.valueOf(((String) object).toUpperCase()); + return EventOperation.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return EventOperation.UNRECOGNIZED; } @@ -8236,7 +9727,7 @@ public class Types return null; } try { - return HostAllowedOperations.valueOf(((String) object).toUpperCase()); + return HostAllowedOperations.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return HostAllowedOperations.UNRECOGNIZED; } @@ -8247,18 +9738,40 @@ public class Types return null; } try { - return IpConfigurationMode.valueOf(((String) object).toUpperCase()); + return IpConfigurationMode.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return IpConfigurationMode.UNRECOGNIZED; } } + public static Types.Ipv6ConfigurationMode toIpv6ConfigurationMode(Object object) { + if (object == null) { + return null; + } + try { + return Ipv6ConfigurationMode.valueOf(((String) object).toUpperCase().replace('-','_')); + } catch (IllegalArgumentException ex) { + return Ipv6ConfigurationMode.UNRECOGNIZED; + } + } + + public static Types.NetworkDefaultLockingMode toNetworkDefaultLockingMode(Object object) { + if (object == null) { + return null; + } + try { + return NetworkDefaultLockingMode.valueOf(((String) object).toUpperCase().replace('-','_')); + } catch (IllegalArgumentException ex) { + return NetworkDefaultLockingMode.UNRECOGNIZED; + } + } + public static Types.NetworkOperations toNetworkOperations(Object object) { if (object == null) { return null; } try { - return NetworkOperations.valueOf(((String) object).toUpperCase()); + return NetworkOperations.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return NetworkOperations.UNRECOGNIZED; } @@ -8269,7 +9782,7 @@ public class Types return null; } try { - return OnBoot.valueOf(((String) object).toUpperCase()); + return OnBoot.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return OnBoot.UNRECOGNIZED; } @@ -8280,7 +9793,7 @@ public class Types return null; } try { - return OnCrashBehaviour.valueOf(((String) object).toUpperCase()); + return OnCrashBehaviour.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return OnCrashBehaviour.UNRECOGNIZED; } @@ -8291,18 +9804,29 @@ public class Types return null; } try { - return OnNormalExit.valueOf(((String) object).toUpperCase()); + return OnNormalExit.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return OnNormalExit.UNRECOGNIZED; } } + public static Types.PrimaryAddressType toPrimaryAddressType(Object object) { + if (object == null) { + return null; + } + try { + return PrimaryAddressType.valueOf(((String) object).toUpperCase().replace('-','_')); + } catch (IllegalArgumentException ex) { + return PrimaryAddressType.UNRECOGNIZED; + } + } + public static Types.StorageOperations toStorageOperations(Object object) { if (object == null) { return null; } try { - return StorageOperations.valueOf(((String) object).toUpperCase()); + return StorageOperations.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return StorageOperations.UNRECOGNIZED; } @@ -8313,7 +9837,7 @@ public class Types return null; } try { - return TaskAllowedOperations.valueOf(((String) object).toUpperCase()); + return TaskAllowedOperations.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return TaskAllowedOperations.UNRECOGNIZED; } @@ -8324,7 +9848,7 @@ public class Types return null; } try { - return TaskStatusType.valueOf(((String) object).toUpperCase()); + return TaskStatusType.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return TaskStatusType.UNRECOGNIZED; } @@ -8335,7 +9859,7 @@ public class Types return null; } try { - return VbdMode.valueOf(((String) object).toUpperCase()); + return VbdMode.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return VbdMode.UNRECOGNIZED; } @@ -8346,7 +9870,7 @@ public class Types return null; } try { - return VbdOperations.valueOf(((String) object).toUpperCase()); + return VbdOperations.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return VbdOperations.UNRECOGNIZED; } @@ -8357,7 +9881,7 @@ public class Types return null; } try { - return VbdType.valueOf(((String) object).toUpperCase()); + return VbdType.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return VbdType.UNRECOGNIZED; } @@ -8368,7 +9892,7 @@ public class Types return null; } try { - return VdiOperations.valueOf(((String) object).toUpperCase()); + return VdiOperations.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return VdiOperations.UNRECOGNIZED; } @@ -8379,29 +9903,51 @@ public class Types return null; } try { - return VdiType.valueOf(((String) object).toUpperCase()); + return VdiType.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return VdiType.UNRECOGNIZED; } } + public static Types.VifLockingMode toVifLockingMode(Object object) { + if (object == null) { + return null; + } + try { + return VifLockingMode.valueOf(((String) object).toUpperCase().replace('-','_')); + } catch (IllegalArgumentException ex) { + return VifLockingMode.UNRECOGNIZED; + } + } + public static Types.VifOperations toVifOperations(Object object) { if (object == null) { return null; } try { - return VifOperations.valueOf(((String) object).toUpperCase()); + return VifOperations.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return VifOperations.UNRECOGNIZED; } } + public static Types.VmApplianceOperation toVmApplianceOperation(Object object) { + if (object == null) { + return null; + } + try { + return VmApplianceOperation.valueOf(((String) object).toUpperCase().replace('-','_')); + } catch (IllegalArgumentException ex) { + return VmApplianceOperation.UNRECOGNIZED; + } + } + public static Types.VmOperations toVmOperations(Object object) { if (object == null) { return null; } try { - return VmOperations.valueOf(((String) object).toUpperCase()); + return VmOperations.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return VmOperations.UNRECOGNIZED; } @@ -8412,7 +9958,7 @@ public class Types return null; } try { - return VmPowerState.valueOf(((String) object).toUpperCase()); + return VmPowerState.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return VmPowerState.UNRECOGNIZED; } @@ -8423,7 +9969,7 @@ public class Types return null; } try { - return VmppArchiveFrequency.valueOf(((String) object).toUpperCase()); + return VmppArchiveFrequency.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return VmppArchiveFrequency.UNRECOGNIZED; } @@ -8434,7 +9980,7 @@ public class Types return null; } try { - return VmppArchiveTargetType.valueOf(((String) object).toUpperCase()); + return VmppArchiveTargetType.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return VmppArchiveTargetType.UNRECOGNIZED; } @@ -8445,7 +9991,7 @@ public class Types return null; } try { - return VmppBackupFrequency.valueOf(((String) object).toUpperCase()); + return VmppBackupFrequency.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return VmppBackupFrequency.UNRECOGNIZED; } @@ -8456,7 +10002,7 @@ public class Types return null; } try { - return VmppBackupType.valueOf(((String) object).toUpperCase()); + return VmppBackupType.valueOf(((String) object).toUpperCase().replace('-','_')); } catch (IllegalArgumentException ex) { return VmppBackupType.UNRECOGNIZED; } @@ -8579,6 +10125,19 @@ public class Types return result; } + public static Set toSetOfVmApplianceOperation(Object object) { + if (object == null) { + return null; + } + Object[] items = (Object[]) object; + Set result = new LinkedHashSet(); + for(Object item: items) { + Types.VmApplianceOperation typed = toVmApplianceOperation(item); + result.add(typed); + } + return result; + } + public static Set toSetOfVmOperations(Object object) { if (object == null) { return null; @@ -8605,6 +10164,32 @@ public class Types return result; } + public static Set toSetOfDRTask(Object object) { + if (object == null) { + return null; + } + Object[] items = (Object[]) object; + Set result = new LinkedHashSet(); + for(Object item: items) { + DRTask typed = toDRTask(item); + result.add(typed); + } + return result; + } + + public static Set toSetOfGPUGroup(Object object) { + if (object == null) { + return null; + } + Object[] items = (Object[]) object; + Set result = new LinkedHashSet(); + for(Object item: items) { + GPUGroup typed = toGPUGroup(item); + result.add(typed); + } + return result; + } + public static Set toSetOfPBD(Object object) { if (object == null) { return null; @@ -8618,6 +10203,32 @@ public class Types return result; } + public static Set toSetOfPCI(Object object) { + if (object == null) { + return null; + } + Object[] items = (Object[]) object; + Set result = new LinkedHashSet(); + for(Object item: items) { + PCI typed = toPCI(item); + result.add(typed); + } + return result; + } + + public static Set toSetOfPGPU(Object object) { + if (object == null) { + return null; + } + Object[] items = (Object[]) object; + Set result = new LinkedHashSet(); + for(Object item: items) { + PGPU typed = toPGPU(item); + result.add(typed); + } + return result; + } + public static Set toSetOfPIF(Object object) { if (object == null) { return null; @@ -8709,6 +10320,19 @@ public class Types return result; } + public static Set toSetOfVGPU(Object object) { + if (object == null) { + return null; + } + Object[] items = (Object[]) object; + Set result = new LinkedHashSet(); + for(Object item: items) { + VGPU typed = toVGPU(item); + result.add(typed); + } + return result; + } + public static Set toSetOfVIF(Object object) { if (object == null) { return null; @@ -8774,6 +10398,19 @@ public class Types return result; } + public static Set toSetOfVMAppliance(Object object) { + if (object == null) { + return null; + } + Object[] items = (Object[]) object; + Set result = new LinkedHashSet(); + for(Object item: items) { + VMAppliance typed = toVMAppliance(item); + result.add(typed); + } + return result; + } + public static Set toSetOfVMGuestMetrics(Object object) { if (object == null) { return null; @@ -9180,6 +10817,21 @@ public class Types return result; } + public static Map toMapOfStringVmApplianceOperation(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + Map result = new HashMap(); + Set entries = map.entrySet(); + for(Map.Entry entry: entries) { + String key = toString(entry.getKey()); + Types.VmApplianceOperation value = toVmApplianceOperation(entry.getValue()); + result.put(key, value); + } + return result; + } + public static Map toMapOfStringVmOperations(Object object) { if (object == null) { return null; @@ -9285,6 +10937,36 @@ public class Types return result; } + public static Map toMapOfDRTaskDRTaskRecord(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + Map result = new HashMap(); + Set entries = map.entrySet(); + for(Map.Entry entry: entries) { + DRTask key = toDRTask(entry.getKey()); + DRTask.Record value = toDRTaskRecord(entry.getValue()); + result.put(key, value); + } + return result; + } + + public static Map toMapOfGPUGroupGPUGroupRecord(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + Map result = new HashMap(); + Set entries = map.entrySet(); + for(Map.Entry entry: entries) { + GPUGroup key = toGPUGroup(entry.getKey()); + GPUGroup.Record value = toGPUGroupRecord(entry.getValue()); + result.put(key, value); + } + return result; + } + public static Map toMapOfPBDPBDRecord(Object object) { if (object == null) { return null; @@ -9300,6 +10982,36 @@ public class Types return result; } + public static Map toMapOfPCIPCIRecord(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + Map result = new HashMap(); + Set entries = map.entrySet(); + for(Map.Entry entry: entries) { + PCI key = toPCI(entry.getKey()); + PCI.Record value = toPCIRecord(entry.getValue()); + result.put(key, value); + } + return result; + } + + public static Map toMapOfPGPUPGPURecord(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + Map result = new HashMap(); + Set entries = map.entrySet(); + for(Map.Entry entry: entries) { + PGPU key = toPGPU(entry.getKey()); + PGPU.Record value = toPGPURecord(entry.getValue()); + result.put(key, value); + } + return result; + } + public static Map toMapOfPIFPIFRecord(Object object) { if (object == null) { return null; @@ -9390,6 +11102,21 @@ public class Types return result; } + public static Map toMapOfVDISR(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + Map result = new HashMap(); + Set entries = map.entrySet(); + for(Map.Entry entry: entries) { + VDI key = toVDI(entry.getKey()); + SR value = toSR(entry.getValue()); + result.put(key, value); + } + return result; + } + public static Map toMapOfVDIVDIRecord(Object object) { if (object == null) { return null; @@ -9405,6 +11132,36 @@ public class Types return result; } + public static Map toMapOfVGPUVGPURecord(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + Map result = new HashMap(); + Set entries = map.entrySet(); + for(Map.Entry entry: entries) { + VGPU key = toVGPU(entry.getKey()); + VGPU.Record value = toVGPURecord(entry.getValue()); + result.put(key, value); + } + return result; + } + + public static Map toMapOfVIFNetwork(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + Map result = new HashMap(); + Set entries = map.entrySet(); + for(Map.Entry entry: entries) { + VIF key = toVIF(entry.getKey()); + Network value = toNetwork(entry.getValue()); + result.put(key, value); + } + return result; + } + public static Map toMapOfVIFVIFRecord(Object object) { if (object == null) { return null; @@ -9525,6 +11282,21 @@ public class Types return result; } + public static Map toMapOfVMApplianceVMApplianceRecord(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + Map result = new HashMap(); + Set entries = map.entrySet(); + for(Map.Entry entry: entries) { + VMAppliance key = toVMAppliance(entry.getKey()); + VMAppliance.Record value = toVMApplianceRecord(entry.getValue()); + result.put(key, value); + } + return result; + } + public static Map toMapOfVMGuestMetricsVMGuestMetricsRecord(Object object) { if (object == null) { return null; @@ -9832,6 +11604,20 @@ public class Types return new Bond((String) object); } + public static DRTask toDRTask(Object object) { + if (object == null) { + return null; + } + return new DRTask((String) object); + } + + public static GPUGroup toGPUGroup(Object object) { + if (object == null) { + return null; + } + return new GPUGroup((String) object); + } + public static PBD toPBD(Object object) { if (object == null) { return null; @@ -9839,6 +11625,20 @@ public class Types return new PBD((String) object); } + public static PCI toPCI(Object object) { + if (object == null) { + return null; + } + return new PCI((String) object); + } + + public static PGPU toPGPU(Object object) { + if (object == null) { + return null; + } + return new PGPU((String) object); + } + public static PIF toPIF(Object object) { if (object == null) { return null; @@ -9888,6 +11688,13 @@ public class Types return new VDI((String) object); } + public static VGPU toVGPU(Object object) { + if (object == null) { + return null; + } + return new VGPU((String) object); + } + public static VIF toVIF(Object object) { if (object == null) { return null; @@ -9923,6 +11730,13 @@ public class Types return new VMPP((String) object); } + public static VMAppliance toVMAppliance(Object object) { + if (object == null) { + return null; + } + return new VMAppliance((String) object); + } + public static VMGuestMetrics toVMGuestMetrics(Object object) { if (object == null) { return null; @@ -10087,6 +11901,37 @@ public class Types record.master = toPIF(map.get("master")); record.slaves = toSetOfPIF(map.get("slaves")); record.otherConfig = toMapOfStringString(map.get("other_config")); + record.primarySlave = toPIF(map.get("primary_slave")); + record.mode = toBondMode(map.get("mode")); + record.properties = toMapOfStringString(map.get("properties")); + record.linksUp = toLong(map.get("links_up")); + return record; + } + + public static DRTask.Record toDRTaskRecord(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + DRTask.Record record = new DRTask.Record(); + record.uuid = toString(map.get("uuid")); + record.introducedSRs = toSetOfSR(map.get("introduced_SRs")); + return record; + } + + public static GPUGroup.Record toGPUGroupRecord(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + GPUGroup.Record record = new GPUGroup.Record(); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.PGPUs = toSetOfPGPU(map.get("PGPUs")); + record.VGPUs = toSetOfVGPU(map.get("VGPUs")); + record.GPUTypes = toSetOfString(map.get("GPU_types")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -10105,6 +11950,37 @@ public class Types return record; } + public static PCI.Record toPCIRecord(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + PCI.Record record = new PCI.Record(); + record.uuid = toString(map.get("uuid")); + record.clazzName = toString(map.get("class_name")); + record.vendorName = toString(map.get("vendor_name")); + record.deviceName = toString(map.get("device_name")); + record.host = toHost(map.get("host")); + record.pciId = toString(map.get("pci_id")); + record.dependencies = toSetOfPCI(map.get("dependencies")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + return record; + } + + public static PGPU.Record toPGPURecord(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + PGPU.Record record = new PGPU.Record(); + record.uuid = toString(map.get("uuid")); + record.PCI = toPCI(map.get("PCI")); + record.GPUGroup = toGPUGroup(map.get("GPU_group")); + record.host = toHost(map.get("host")); + record.otherConfig = toMapOfStringString(map.get("other_config")); + return record; + } + public static PIF.Record toPIFRecord(Object object) { if (object == null) { return null; @@ -10135,6 +12011,10 @@ public class Types record.disallowUnplug = toBoolean(map.get("disallow_unplug")); record.tunnelAccessPIFOf = toSetOfTunnel(map.get("tunnel_access_PIF_of")); record.tunnelTransportPIFOf = toSetOfTunnel(map.get("tunnel_transport_PIF_of")); + record.ipv6ConfigurationMode = toIpv6ConfigurationMode(map.get("ipv6_configuration_mode")); + record.IPv6 = toSetOfString(map.get("IPv6")); + record.ipv6Gateway = toString(map.get("ipv6_gateway")); + record.primaryAddressType = toPrimaryAddressType(map.get("primary_address_type")); return record; } @@ -10205,6 +12085,7 @@ public class Types record.smConfig = toMapOfStringString(map.get("sm_config")); record.blobs = toMapOfStringBlob(map.get("blobs")); record.localCacheEnabled = toBoolean(map.get("local_cache_enabled")); + record.introducedBy = toDRTask(map.get("introduced_by")); return record; } @@ -10287,6 +12168,23 @@ public class Types record.tags = toSetOfString(map.get("tags")); record.allowCaching = toBoolean(map.get("allow_caching")); record.onBoot = toOnBoot(map.get("on_boot")); + record.metadataOfPool = toPool(map.get("metadata_of_pool")); + record.metadataLatest = toBoolean(map.get("metadata_latest")); + return record; + } + + public static VGPU.Record toVGPURecord(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + VGPU.Record record = new VGPU.Record(); + record.uuid = toString(map.get("uuid")); + record.VM = toVM(map.get("VM")); + record.GPUGroup = toGPUGroup(map.get("GPU_group")); + record.device = toString(map.get("device")); + record.currentlyAttached = toBoolean(map.get("currently_attached")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -10314,6 +12212,9 @@ public class Types record.qosSupportedAlgorithms = toSetOfString(map.get("qos_supported_algorithms")); record.metrics = toVIFMetrics(map.get("metrics")); record.MACAutogenerated = toBoolean(map.get("MAC_autogenerated")); + record.lockingMode = toVifLockingMode(map.get("locking_mode")); + record.ipv4Allowed = toSetOfString(map.get("ipv4_allowed")); + record.ipv6Allowed = toSetOfString(map.get("ipv6_allowed")); return record; } @@ -10417,6 +12318,14 @@ public class Types record.biosStrings = toMapOfStringString(map.get("bios_strings")); record.protectionPolicy = toVMPP(map.get("protection_policy")); record.isSnapshotFromVmpp = toBoolean(map.get("is_snapshot_from_vmpp")); + record.appliance = toVMAppliance(map.get("appliance")); + record.startDelay = toLong(map.get("start_delay")); + record.shutdownDelay = toLong(map.get("shutdown_delay")); + record.order = toLong(map.get("order")); + record.VGPUs = toSetOfVGPU(map.get("VGPUs")); + record.attachedPCIs = toSetOfPCI(map.get("attached_PCIs")); + record.suspendSR = toSR(map.get("suspend_SR")); + record.version = toLong(map.get("version")); return record; } @@ -10449,6 +12358,21 @@ public class Types return record; } + public static VMAppliance.Record toVMApplianceRecord(Object object) { + if (object == null) { + return null; + } + Map map = (Map) object; + VMAppliance.Record record = new VMAppliance.Record(); + record.uuid = toString(map.get("uuid")); + record.nameLabel = toString(map.get("name_label")); + record.nameDescription = toString(map.get("name_description")); + record.allowedOperations = toSetOfVmApplianceOperation(map.get("allowed_operations")); + record.currentOperations = toMapOfStringVmApplianceOperation(map.get("current_operations")); + record.VMs = toSetOfVM(map.get("VMs")); + return record; + } + public static VMGuestMetrics.Record toVMGuestMetricsRecord(Object object) { if (object == null) { return null; @@ -10512,6 +12436,7 @@ public class Types record.nameLabel = toString(map.get("name_label")); record.nameDescription = toString(map.get("name_description")); record.size = toLong(map.get("size")); + record._public = toBoolean(map.get("public")); record.lastUpdated = toDate(map.get("last_updated")); record.mimeType = toString(map.get("mime_type")); return record; @@ -10590,6 +12515,8 @@ public class Types case VM_METRICS: b = toVMMetricsRecord(a); break; case VM_GUEST_METRICS: b = toVMGuestMetricsRecord(a); break; case VMPP: b = toVMPPRecord(a); break; + case VM_APPLIANCE: b = toVMApplianceRecord(a); break; + case DR_TASK: b = toDRTaskRecord(a); break; case HOST: b = toHostRecord(a); break; case HOST_CRASHDUMP: b = toHostCrashdumpRecord(a); break; case HOST_PATCH: b = toHostPatchRecord(a); break; @@ -10617,6 +12544,10 @@ public class Types case MESSAGE: b = toMessageRecord(a); break; case SECRET: b = toSecretRecord(a); break; case TUNNEL: b = toTunnelRecord(a); break; + case PCI: b = toPCIRecord(a); break; + case PGPU: b = toPGPURecord(a); break; + case GPU_GROUP: b = toGPUGroupRecord(a); break; + case VGPU: b = toVGPURecord(a); break; default: throw new RuntimeException("Internal error in auto-generated code whilst unmarshalling event snapshot"); } record.snapshot = b; @@ -10673,6 +12604,9 @@ public class Types record.powerOnMode = toString(map.get("power_on_mode")); record.powerOnConfig = toMapOfStringString(map.get("power_on_config")); record.localCacheSr = toSR(map.get("local_cache_sr")); + record.chipsetInfo = toMapOfStringString(map.get("chipset_info")); + record.PCIs = toSetOfPCI(map.get("PCIs")); + record.PGPUs = toSetOfPGPU(map.get("PGPUs")); return record; } @@ -10780,6 +12714,7 @@ public class Types record.bridge = toString(map.get("bridge")); record.blobs = toMapOfStringBlob(map.get("blobs")); record.tags = toSetOfString(map.get("tags")); + record.defaultLockingMode = toNetworkDefaultLockingMode(map.get("default_locking_mode")); return record; } @@ -10815,6 +12750,7 @@ public class Types record.redoLogVdi = toVDI(map.get("redo_log_vdi")); record.vswitchController = toString(map.get("vswitch_controller")); record.restrictions = toMapOfStringString(map.get("restrictions")); + record.metadataVDIs = toSetOfVDI(map.get("metadata_VDIs")); return record; } @@ -10857,6 +12793,7 @@ public class Types Secret.Record record = new Secret.Record(); record.uuid = toString(map.get("uuid")); record.value = toString(map.get("value")); + record.otherConfig = toMapOfStringString(map.get("other_config")); return record; } @@ -10953,10 +12890,26 @@ public class Types return Types.toBond(parseResult(task.getResult(connection))); } + public static DRTask toDRTask(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ + return Types.toDRTask(parseResult(task.getResult(connection))); + } + + public static GPUGroup toGPUGroup(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ + return Types.toGPUGroup(parseResult(task.getResult(connection))); + } + public static PBD toPBD(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ return Types.toPBD(parseResult(task.getResult(connection))); } + public static PCI toPCI(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ + return Types.toPCI(parseResult(task.getResult(connection))); + } + + public static PGPU toPGPU(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ + return Types.toPGPU(parseResult(task.getResult(connection))); + } + public static PIF toPIF(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ return Types.toPIF(parseResult(task.getResult(connection))); } @@ -10985,6 +12938,10 @@ public class Types return Types.toVDI(parseResult(task.getResult(connection))); } + public static VGPU toVGPU(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ + return Types.toVGPU(parseResult(task.getResult(connection))); + } + public static VIF toVIF(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ return Types.toVIF(parseResult(task.getResult(connection))); } @@ -11005,6 +12962,10 @@ public class Types return Types.toVMPP(parseResult(task.getResult(connection))); } + public static VMAppliance toVMAppliance(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ + return Types.toVMAppliance(parseResult(task.getResult(connection))); + } + public static VMGuestMetrics toVMGuestMetrics(Task task, Connection connection) throws XenAPIException, BadServerResponse, XmlRpcException, BadAsyncResult{ return Types.toVMGuestMetrics(parseResult(task.getResult(connection))); } diff --git a/deps/XenServerJava/src/com/xensource/xenapi/User.java b/deps/XenServerJava/src/com/xensource/xenapi/User.java index 9cf239d60ee..0d2e4fd81d8 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/User.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/User.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class User extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class User extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -376,4 +381,4 @@ public class User extends XenAPIObject { return; } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VBD.java b/deps/XenServerJava/src/com/xensource/xenapi/VBD.java index cb793398ee3..18cbb7b488d 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VBD.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VBD.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class VBD extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class VBD extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -1153,4 +1158,4 @@ public class VBD extends XenAPIObject { return Types.toMapOfVBDVBDRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VBDMetrics.java b/deps/XenServerJava/src/com/xensource/xenapi/VBDMetrics.java index 59928e9bd59..adb6bb513de 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VBDMetrics.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VBDMetrics.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class VBDMetrics extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class VBDMetrics extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -341,4 +346,4 @@ public class VBDMetrics extends XenAPIObject { return Types.toMapOfVBDMetricsVBDMetricsRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VDI.java b/deps/XenServerJava/src/com/xensource/xenapi/VDI.java index e4d20ebf8ba..4ea9daff1fa 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VDI.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VDI.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class VDI extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class VDI extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -123,6 +128,8 @@ public class VDI extends XenAPIObject { print.printf("%1$20s: %2$s\n", "tags", this.tags); print.printf("%1$20s: %2$s\n", "allowCaching", this.allowCaching); print.printf("%1$20s: %2$s\n", "onBoot", this.onBoot); + print.printf("%1$20s: %2$s\n", "metadataOfPool", this.metadataOfPool); + print.printf("%1$20s: %2$s\n", "metadataLatest", this.metadataLatest); return writer.toString(); } @@ -159,6 +166,8 @@ public class VDI extends XenAPIObject { map.put("tags", this.tags == null ? new LinkedHashSet() : this.tags); map.put("allow_caching", this.allowCaching == null ? false : this.allowCaching); map.put("on_boot", this.onBoot == null ? Types.OnBoot.UNRECOGNIZED : this.onBoot); + map.put("metadata_of_pool", this.metadataOfPool == null ? new Pool("OpaqueRef:NULL") : this.metadataOfPool); + map.put("metadata_latest", this.metadataLatest == null ? false : this.metadataLatest); return map; } @@ -171,7 +180,7 @@ public class VDI extends XenAPIObject { */ public String nameLabel; /** - * a notes field containg human-readable description + * a notes field containing human-readable description */ public String nameDescription; /** @@ -227,7 +236,7 @@ public class VDI extends XenAPIObject { */ public String location; /** - * + * */ public Boolean managed; /** @@ -274,6 +283,14 @@ public class VDI extends XenAPIObject { * The behaviour of this VDI on a VM boot */ public Types.OnBoot onBoot; + /** + * The pool whose metadata is contained in this VDI + */ + public Pool metadataOfPool; + /** + * Whether this VDI contains the latest known accessible metadata for the pool + */ + public Boolean metadataLatest; } /** @@ -876,35 +893,37 @@ public class VDI extends XenAPIObject { } /** - * Set the name/label field of the given VDI. + * Get the metadata_of_pool field of the given VDI. * - * @param label New value to set + * @return value of the field */ - public void setNameLabel(Connection c, String label) throws + public Pool getMetadataOfPool(Connection c) throws BadServerResponse, XenAPIException, XmlRpcException { - String method_call = "VDI.set_name_label"; + String method_call = "VDI.get_metadata_of_pool"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(label)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); - return; + Object result = response.get("Value"); + return Types.toPool(result); } /** - * Set the name/description field of the given VDI. + * Get the metadata_latest field of the given VDI. * - * @param description New value to set + * @return value of the field */ - public void setNameDescription(Connection c, String description) throws + public Boolean getMetadataLatest(Connection c) throws BadServerResponse, XenAPIException, XmlRpcException { - String method_call = "VDI.set_name_description"; + String method_call = "VDI.get_metadata_latest"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(description)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); - return; + Object result = response.get("Value"); + return Types.toBoolean(result); } /** @@ -1380,16 +1399,23 @@ public class VDI extends XenAPIObject { * @param location location information * @param xenstoreData Data to insert into xenstore * @param smConfig Storage-specific config + * @param managed Storage-specific config + * @param virtualSize Storage-specific config + * @param physicalUtilisation Storage-specific config + * @param metadataOfPool Storage-specific config + * @param isASnapshot Storage-specific config + * @param snapshotTime Storage-specific config + * @param snapshotOf Storage-specific config * @return Task */ - public static Task introduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, Map otherConfig, String location, Map xenstoreData, Map smConfig) throws + public static Task introduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, Map otherConfig, String location, Map xenstoreData, Map smConfig, Boolean managed, Long virtualSize, Long physicalUtilisation, Pool metadataOfPool, Boolean isASnapshot, Date snapshotTime, VDI snapshotOf) throws BadServerResponse, XenAPIException, XmlRpcException, Types.SrOperationNotSupported { String method_call = "Async.VDI.introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig), Marshalling.toXMLRPC(managed), Marshalling.toXMLRPC(virtualSize), Marshalling.toXMLRPC(physicalUtilisation), Marshalling.toXMLRPC(metadataOfPool), Marshalling.toXMLRPC(isASnapshot), Marshalling.toXMLRPC(snapshotTime), Marshalling.toXMLRPC(snapshotOf)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1409,16 +1435,23 @@ public class VDI extends XenAPIObject { * @param location location information * @param xenstoreData Data to insert into xenstore * @param smConfig Storage-specific config + * @param managed Storage-specific config + * @param virtualSize Storage-specific config + * @param physicalUtilisation Storage-specific config + * @param metadataOfPool Storage-specific config + * @param isASnapshot Storage-specific config + * @param snapshotTime Storage-specific config + * @param snapshotOf Storage-specific config * @return The ref of the newly created VDI record. */ - public static VDI introduce(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, Map otherConfig, String location, Map xenstoreData, Map smConfig) throws + public static VDI introduce(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, Map otherConfig, String location, Map xenstoreData, Map smConfig, Boolean managed, Long virtualSize, Long physicalUtilisation, Pool metadataOfPool, Boolean isASnapshot, Date snapshotTime, VDI snapshotOf) throws BadServerResponse, XenAPIException, XmlRpcException, Types.SrOperationNotSupported { String method_call = "VDI.introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig), Marshalling.toXMLRPC(managed), Marshalling.toXMLRPC(virtualSize), Marshalling.toXMLRPC(physicalUtilisation), Marshalling.toXMLRPC(metadataOfPool), Marshalling.toXMLRPC(isASnapshot), Marshalling.toXMLRPC(snapshotTime), Marshalling.toXMLRPC(snapshotOf)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toVDI(result); @@ -1438,15 +1471,22 @@ public class VDI extends XenAPIObject { * @param location location information * @param xenstoreData Data to insert into xenstore * @param smConfig Storage-specific config + * @param managed Storage-specific config + * @param virtualSize Storage-specific config + * @param physicalUtilisation Storage-specific config + * @param metadataOfPool Storage-specific config + * @param isASnapshot Storage-specific config + * @param snapshotTime Storage-specific config + * @param snapshotOf Storage-specific config * @return Task */ - public static Task dbIntroduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, Map otherConfig, String location, Map xenstoreData, Map smConfig) throws + public static Task dbIntroduceAsync(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, Map otherConfig, String location, Map xenstoreData, Map smConfig, Boolean managed, Long virtualSize, Long physicalUtilisation, Pool metadataOfPool, Boolean isASnapshot, Date snapshotTime, VDI snapshotOf) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "Async.VDI.db_introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig), Marshalling.toXMLRPC(managed), Marshalling.toXMLRPC(virtualSize), Marshalling.toXMLRPC(physicalUtilisation), Marshalling.toXMLRPC(metadataOfPool), Marshalling.toXMLRPC(isASnapshot), Marshalling.toXMLRPC(snapshotTime), Marshalling.toXMLRPC(snapshotOf)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -1466,15 +1506,22 @@ public class VDI extends XenAPIObject { * @param location location information * @param xenstoreData Data to insert into xenstore * @param smConfig Storage-specific config + * @param managed Storage-specific config + * @param virtualSize Storage-specific config + * @param physicalUtilisation Storage-specific config + * @param metadataOfPool Storage-specific config + * @param isASnapshot Storage-specific config + * @param snapshotTime Storage-specific config + * @param snapshotOf Storage-specific config * @return The ref of the newly created VDI record. */ - public static VDI dbIntroduce(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, Map otherConfig, String location, Map xenstoreData, Map smConfig) throws + public static VDI dbIntroduce(Connection c, String uuid, String nameLabel, String nameDescription, SR SR, Types.VdiType type, Boolean sharable, Boolean readOnly, Map otherConfig, String location, Map xenstoreData, Map smConfig, Boolean managed, Long virtualSize, Long physicalUtilisation, Pool metadataOfPool, Boolean isASnapshot, Date snapshotTime, VDI snapshotOf) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "VDI.db_introduce"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid), Marshalling.toXMLRPC(nameLabel), Marshalling.toXMLRPC(nameDescription), Marshalling.toXMLRPC(SR), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(sharable), Marshalling.toXMLRPC(readOnly), Marshalling.toXMLRPC(otherConfig), Marshalling.toXMLRPC(location), Marshalling.toXMLRPC(xenstoreData), Marshalling.toXMLRPC(smConfig), Marshalling.toXMLRPC(managed), Marshalling.toXMLRPC(virtualSize), Marshalling.toXMLRPC(physicalUtilisation), Marshalling.toXMLRPC(metadataOfPool), Marshalling.toXMLRPC(isASnapshot), Marshalling.toXMLRPC(snapshotTime), Marshalling.toXMLRPC(snapshotOf)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toVDI(result); @@ -1710,6 +1757,138 @@ public class VDI extends XenAPIObject { return; } + /** + * Sets whether this VDI is a snapshot + * + * @param value The new value indicating whether this VDI is a snapshot + */ + public void setIsASnapshot(Connection c, Boolean value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VDI.set_is_a_snapshot"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Sets the VDI of which this VDI is a snapshot + * + * @param value The VDI of which this VDI is a snapshot + */ + public void setSnapshotOf(Connection c, VDI value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VDI.set_snapshot_of"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Sets the snapshot time of this VDI. + * + * @param value The snapshot time of this VDI. + */ + public void setSnapshotTime(Connection c, Date value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VDI.set_snapshot_time"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Records the pool whose metadata is contained by this VDI. + * + * @param value The pool whose metadata is contained by this VDI + */ + public void setMetadataOfPool(Connection c, Pool value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VDI.set_metadata_of_pool"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Set the name label of the VDI. This can only happen when then its SR is currently attached. + * + * @param value The name lable for the VDI + * @return Task + */ + public Task setNameLabelAsync(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VDI.set_name_label"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Set the name label of the VDI. This can only happen when then its SR is currently attached. + * + * @param value The name lable for the VDI + */ + public void setNameLabel(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VDI.set_name_label"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Set the name description of the VDI. This can only happen when its SR is currently attached. + * + * @param value The name description for the VDI + * @return Task + */ + public Task setNameDescriptionAsync(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VDI.set_name_description"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Set the name description of the VDI. This can only happen when its SR is currently attached. + * + * @param value The name description for the VDI + */ + public void setNameDescription(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VDI.set_name_description"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + /** * Set the value of the on_boot parameter. This value can only be changed when the VDI is not attached to a running VM. * @@ -1778,6 +1957,112 @@ public class VDI extends XenAPIObject { return; } + /** + * Load the metadata found on the supplied VDI and return a session reference which can be used in XenAPI calls to query its contents. + * + * @return Task + */ + public Task openDatabaseAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VDI.open_database"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Load the metadata found on the supplied VDI and return a session reference which can be used in XenAPI calls to query its contents. + * + * @return A session which can be used to query the database + */ + public Session openDatabase(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VDI.open_database"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSession(result); + } + + /** + * Check the VDI cache for the pool UUID of the database on this VDI. + * + * @return Task + */ + public Task readDatabasePoolUuidAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VDI.read_database_pool_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Check the VDI cache for the pool UUID of the database on this VDI. + * + * @return The cached pool UUID of the database on the VDI. + */ + public String readDatabasePoolUuid(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VDI.read_database_pool_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Migrate a VDI, which may be attached to a running guest, to a different SR. The destination SR must be visible to the guest. + * + * @param sr The destination SR + * @param options Other parameters + * @return Task + */ + public Task poolMigrateAsync(Connection c, SR sr, Map options) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VDI.pool_migrate"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sr), Marshalling.toXMLRPC(options)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Migrate a VDI, which may be attached to a running guest, to a different SR. The destination SR must be visible to the guest. + * + * @param sr The destination SR + * @param options Other parameters + * @return The new reference of the migrated VDI. + */ + public VDI poolMigrate(Connection c, SR sr, Map options) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VDI.pool_migrate"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sr), Marshalling.toXMLRPC(options)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toVDI(result); + } + /** * Return a list of all the VDIs known to the system. * @@ -1812,4 +2097,4 @@ public class VDI extends XenAPIObject { return Types.toMapOfVDIVDIRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VGPU.java b/deps/XenServerJava/src/com/xensource/xenapi/VGPU.java new file mode 100644 index 00000000000..075ab54757c --- /dev/null +++ b/deps/XenServerJava/src/com/xensource/xenapi/VGPU.java @@ -0,0 +1,446 @@ +/* + * Copyright (c) Citrix Systems, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1) Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2) Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +package com.xensource.xenapi; + +import com.xensource.xenapi.Types.BadServerResponse; +import com.xensource.xenapi.Types.VersionException; +import com.xensource.xenapi.Types.XenAPIException; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.xmlrpc.XmlRpcException; + +/** + * A virtual GPU (vGPU) + * + * @author Citrix Systems, Inc. + */ +public class VGPU extends XenAPIObject { + + /** + * The XenAPI reference (OpaqueRef) to this object. + */ + protected final String ref; + + /** + * For internal use only. + */ + VGPU(String ref) { + this.ref = ref; + } + + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ + public String toWireString() { + return this.ref; + } + + /** + * If obj is a VGPU, compares XenAPI references for equality. + */ + @Override + public boolean equals(Object obj) + { + if (obj != null && obj instanceof VGPU) + { + VGPU other = (VGPU) obj; + return other.ref.equals(this.ref); + } else + { + return false; + } + } + + @Override + public int hashCode() + { + return ref.hashCode(); + } + + /** + * Represents all the fields in a VGPU + */ + public static class Record implements Types.Record { + public String toString() { + StringWriter writer = new StringWriter(); + PrintWriter print = new PrintWriter(writer); + print.printf("%1$20s: %2$s\n", "uuid", this.uuid); + print.printf("%1$20s: %2$s\n", "VM", this.VM); + print.printf("%1$20s: %2$s\n", "GPUGroup", this.GPUGroup); + print.printf("%1$20s: %2$s\n", "device", this.device); + print.printf("%1$20s: %2$s\n", "currentlyAttached", this.currentlyAttached); + print.printf("%1$20s: %2$s\n", "otherConfig", this.otherConfig); + return writer.toString(); + } + + /** + * Convert a VGPU.Record to a Map + */ + public Map toMap() { + Map map = new HashMap(); + map.put("uuid", this.uuid == null ? "" : this.uuid); + map.put("VM", this.VM == null ? new VM("OpaqueRef:NULL") : this.VM); + map.put("GPU_group", this.GPUGroup == null ? new GPUGroup("OpaqueRef:NULL") : this.GPUGroup); + map.put("device", this.device == null ? "" : this.device); + map.put("currently_attached", this.currentlyAttached == null ? false : this.currentlyAttached); + map.put("other_config", this.otherConfig == null ? new HashMap() : this.otherConfig); + return map; + } + + /** + * Unique identifier/object reference + */ + public String uuid; + /** + * VM that owns the vGPU + */ + public VM VM; + /** + * GPU group used by the vGPU + */ + public GPUGroup GPUGroup; + /** + * Order in which the devices are plugged into the VM + */ + public String device; + /** + * Reflects whether the virtual device is currently connected to a physical device + */ + public Boolean currentlyAttached; + /** + * Additional configuration + */ + public Map otherConfig; + } + + /** + * Get a record containing the current state of the given VGPU. + * + * @return all fields from the object + */ + public VGPU.Record getRecord(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.get_record"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toVGPURecord(result); + } + + /** + * Get a reference to the VGPU instance with the specified UUID. + * + * @param uuid UUID of object to return + * @return reference to the object + */ + public static VGPU getByUuid(Connection c, String uuid) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.get_by_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toVGPU(result); + } + + /** + * Get the uuid field of the given VGPU. + * + * @return value of the field + */ + public String getUuid(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.get_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the VM field of the given VGPU. + * + * @return value of the field + */ + public VM getVM(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.get_VM"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toVM(result); + } + + /** + * Get the GPU_group field of the given VGPU. + * + * @return value of the field + */ + public GPUGroup getGPUGroup(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.get_GPU_group"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toGPUGroup(result); + } + + /** + * Get the device field of the given VGPU. + * + * @return value of the field + */ + public String getDevice(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.get_device"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the currently_attached field of the given VGPU. + * + * @return value of the field + */ + public Boolean getCurrentlyAttached(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.get_currently_attached"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toBoolean(result); + } + + /** + * Get the other_config field of the given VGPU. + * + * @return value of the field + */ + public Map getOtherConfig(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.get_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfStringString(result); + } + + /** + * Set the other_config field of the given VGPU. + * + * @param otherConfig New value to set + */ + public void setOtherConfig(Connection c, Map otherConfig) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.set_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Add the given key-value pair to the other_config field of the given VGPU. + * + * @param key Key to add + * @param value Value to add + */ + public void addToOtherConfig(Connection c, String key, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.add_to_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Remove the given key and its corresponding value from the other_config field of the given VGPU. If the key is not in that Map, then do nothing. + * + * @param key Key to remove + */ + public void removeFromOtherConfig(Connection c, String key) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.remove_from_other_config"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * + * + * @param VM + * @param GPUGroup + * @param device + * @param otherConfig + * @return Task + */ + public static Task createAsync(Connection c, VM VM, GPUGroup GPUGroup, String device, Map otherConfig) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VGPU.create"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(VM), Marshalling.toXMLRPC(GPUGroup), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(otherConfig)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * + * + * @param VM + * @param GPUGroup + * @param device + * @param otherConfig + * @return reference to the newly created object + */ + public static VGPU create(Connection c, VM VM, GPUGroup GPUGroup, String device, Map otherConfig) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.create"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(VM), Marshalling.toXMLRPC(GPUGroup), Marshalling.toXMLRPC(device), Marshalling.toXMLRPC(otherConfig)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toVGPU(result); + } + + /** + * + * + * @return Task + */ + public Task destroyAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VGPU.destroy"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * + * + */ + public void destroy(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.destroy"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Return a list of all the VGPUs known to the system. + * + * @return references to all objects + */ + public static Set getAll(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.get_all"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfVGPU(result); + } + + /** + * Return a map of VGPU references to VGPU records for all VGPUs known to the system. + * + * @return records of all objects + */ + public static Map getAllRecords(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VGPU.get_all_records"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfVGPUVGPURecord(result); + } + +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VIF.java b/deps/XenServerJava/src/com/xensource/xenapi/VIF.java index 4ba78076b15..c1d25b445ac 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VIF.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VIF.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class VIF extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class VIF extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -113,6 +118,9 @@ public class VIF extends XenAPIObject { print.printf("%1$20s: %2$s\n", "qosSupportedAlgorithms", this.qosSupportedAlgorithms); print.printf("%1$20s: %2$s\n", "metrics", this.metrics); print.printf("%1$20s: %2$s\n", "MACAutogenerated", this.MACAutogenerated); + print.printf("%1$20s: %2$s\n", "lockingMode", this.lockingMode); + print.printf("%1$20s: %2$s\n", "ipv4Allowed", this.ipv4Allowed); + print.printf("%1$20s: %2$s\n", "ipv6Allowed", this.ipv6Allowed); return writer.toString(); } @@ -139,6 +147,9 @@ public class VIF extends XenAPIObject { map.put("qos_supported_algorithms", this.qosSupportedAlgorithms == null ? new LinkedHashSet() : this.qosSupportedAlgorithms); map.put("metrics", this.metrics == null ? new VIFMetrics("OpaqueRef:NULL") : this.metrics); map.put("MAC_autogenerated", this.MACAutogenerated == null ? false : this.MACAutogenerated); + map.put("locking_mode", this.lockingMode == null ? Types.VifLockingMode.UNRECOGNIZED : this.lockingMode); + map.put("ipv4_allowed", this.ipv4Allowed == null ? new LinkedHashSet() : this.ipv4Allowed); + map.put("ipv6_allowed", this.ipv6Allowed == null ? new LinkedHashSet() : this.ipv6Allowed); return map; } @@ -214,6 +225,18 @@ public class VIF extends XenAPIObject { * true if the MAC was autogenerated; false indicates it was set manually */ public Boolean MACAutogenerated; + /** + * current locking mode of the VIF + */ + public Types.VifLockingMode lockingMode; + /** + * A list of IPv4 addresses which can be used to filter traffic passing through this VIF + */ + public Set ipv4Allowed; + /** + * A list of IPv6 addresses which can be used to filter traffic passing through this VIF + */ + public Set ipv6Allowed; } /** @@ -627,6 +650,57 @@ public class VIF extends XenAPIObject { return Types.toBoolean(result); } + /** + * Get the locking_mode field of the given VIF. + * + * @return value of the field + */ + public Types.VifLockingMode getLockingMode(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VIF.get_locking_mode"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toVifLockingMode(result); + } + + /** + * Get the ipv4_allowed field of the given VIF. + * + * @return value of the field + */ + public Set getIpv4Allowed(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VIF.get_ipv4_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfString(result); + } + + /** + * Get the ipv6_allowed field of the given VIF. + * + * @return value of the field + */ + public Set getIpv6Allowed(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VIF.get_ipv6_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfString(result); + } + /** * Set the other_config field of the given VIF. * @@ -805,6 +879,276 @@ public class VIF extends XenAPIObject { return; } + /** + * Forcibly unplug the specified VIF + * + * @return Task + */ + public Task unplugForceAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VIF.unplug_force"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Forcibly unplug the specified VIF + * + */ + public void unplugForce(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VIF.unplug_force"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Set the locking mode for this VIF + * + * @param value The new locking mode for the VIF + * @return Task + */ + public Task setLockingModeAsync(Connection c, Types.VifLockingMode value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VIF.set_locking_mode"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Set the locking mode for this VIF + * + * @param value The new locking mode for the VIF + */ + public void setLockingMode(Connection c, Types.VifLockingMode value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VIF.set_locking_mode"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Set the IPv4 addresses to which traffic on this VIF can be restricted + * + * @param value The IP addresses which will be associated with the VIF + * @return Task + */ + public Task setIpv4AllowedAsync(Connection c, Set value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VIF.set_ipv4_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Set the IPv4 addresses to which traffic on this VIF can be restricted + * + * @param value The IP addresses which will be associated with the VIF + */ + public void setIpv4Allowed(Connection c, Set value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VIF.set_ipv4_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Associates an IPv4 address with this VIF + * + * @param value The IP address which will be associated with the VIF + * @return Task + */ + public Task addIpv4AllowedAsync(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VIF.add_ipv4_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Associates an IPv4 address with this VIF + * + * @param value The IP address which will be associated with the VIF + */ + public void addIpv4Allowed(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VIF.add_ipv4_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Removes an IPv4 address from this VIF + * + * @param value The IP address which will be removed from the VIF + * @return Task + */ + public Task removeIpv4AllowedAsync(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VIF.remove_ipv4_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Removes an IPv4 address from this VIF + * + * @param value The IP address which will be removed from the VIF + */ + public void removeIpv4Allowed(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VIF.remove_ipv4_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Set the IPv6 addresses to which traffic on this VIF can be restricted + * + * @param value The IP addresses which will be associated with the VIF + * @return Task + */ + public Task setIpv6AllowedAsync(Connection c, Set value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VIF.set_ipv6_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Set the IPv6 addresses to which traffic on this VIF can be restricted + * + * @param value The IP addresses which will be associated with the VIF + */ + public void setIpv6Allowed(Connection c, Set value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VIF.set_ipv6_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Associates an IPv6 address with this VIF + * + * @param value The IP address which will be associated with the VIF + * @return Task + */ + public Task addIpv6AllowedAsync(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VIF.add_ipv6_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Associates an IPv6 address with this VIF + * + * @param value The IP address which will be associated with the VIF + */ + public void addIpv6Allowed(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VIF.add_ipv6_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Removes an IPv6 address from this VIF + * + * @param value The IP address which will be removed from the VIF + * @return Task + */ + public Task removeIpv6AllowedAsync(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VIF.remove_ipv6_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Removes an IPv6 address from this VIF + * + * @param value The IP address which will be removed from the VIF + */ + public void removeIpv6Allowed(Connection c, String value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VIF.remove_ipv6_allowed"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + /** * Return a list of all the VIFs known to the system. * @@ -839,4 +1183,4 @@ public class VIF extends XenAPIObject { return Types.toMapOfVIFVIFRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VIFMetrics.java b/deps/XenServerJava/src/com/xensource/xenapi/VIFMetrics.java index 6c0212fcaa3..ed7504c17b1 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VIFMetrics.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VIFMetrics.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class VIFMetrics extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class VIFMetrics extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -341,4 +346,4 @@ public class VIFMetrics extends XenAPIObject { return Types.toMapOfVIFMetricsVIFMetricsRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VLAN.java b/deps/XenServerJava/src/com/xensource/xenapi/VLAN.java index b8c968b1df3..232640527ac 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VLAN.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VLAN.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class VLAN extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class VLAN extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -413,4 +418,4 @@ public class VLAN extends XenAPIObject { return Types.toMapOfVLANVLANRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VM.java b/deps/XenServerJava/src/com/xensource/xenapi/VM.java index 165dcfab4a3..736026654d7 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VM.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VM.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class VM extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class VM extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -161,6 +166,14 @@ public class VM extends XenAPIObject { print.printf("%1$20s: %2$s\n", "biosStrings", this.biosStrings); print.printf("%1$20s: %2$s\n", "protectionPolicy", this.protectionPolicy); print.printf("%1$20s: %2$s\n", "isSnapshotFromVmpp", this.isSnapshotFromVmpp); + print.printf("%1$20s: %2$s\n", "appliance", this.appliance); + print.printf("%1$20s: %2$s\n", "startDelay", this.startDelay); + print.printf("%1$20s: %2$s\n", "shutdownDelay", this.shutdownDelay); + print.printf("%1$20s: %2$s\n", "order", this.order); + print.printf("%1$20s: %2$s\n", "VGPUs", this.VGPUs); + print.printf("%1$20s: %2$s\n", "attachedPCIs", this.attachedPCIs); + print.printf("%1$20s: %2$s\n", "suspendSR", this.suspendSR); + print.printf("%1$20s: %2$s\n", "version", this.version); return writer.toString(); } @@ -235,6 +248,14 @@ public class VM extends XenAPIObject { map.put("bios_strings", this.biosStrings == null ? new HashMap() : this.biosStrings); map.put("protection_policy", this.protectionPolicy == null ? new VMPP("OpaqueRef:NULL") : this.protectionPolicy); map.put("is_snapshot_from_vmpp", this.isSnapshotFromVmpp == null ? false : this.isSnapshotFromVmpp); + map.put("appliance", this.appliance == null ? new VMAppliance("OpaqueRef:NULL") : this.appliance); + map.put("start_delay", this.startDelay == null ? 0 : this.startDelay); + map.put("shutdown_delay", this.shutdownDelay == null ? 0 : this.shutdownDelay); + map.put("order", this.order == null ? 0 : this.order); + map.put("VGPUs", this.VGPUs == null ? new LinkedHashSet() : this.VGPUs); + map.put("attached_PCIs", this.attachedPCIs == null ? new LinkedHashSet() : this.attachedPCIs); + map.put("suspend_SR", this.suspendSR == null ? new SR("OpaqueRef:NULL") : this.suspendSR); + map.put("version", this.version == null ? 0 : this.version); return map; } @@ -259,7 +280,7 @@ public class VM extends XenAPIObject { */ public String nameLabel; /** - * a notes field containg human-readable description + * a notes field containing human-readable description */ public String nameDescription; /** @@ -439,7 +460,7 @@ public class VM extends XenAPIObject { */ public Boolean haAlwaysRun; /** - * Only defined if ha_always_run is set possible values: "best-effort" meaning "try to restart this VM if possible but don't consider the Pool to be overcommitted if this is not possible"; and a numerical restart priority (e.g. 1, 2, 3,...) + * has possible values: "best-effort" meaning "try to restart this VM if possible but don't consider the Pool to be overcommitted if this is not possible"; "restart" meaning "this VM should be restarted"; "" meaning "do not try to restart this VM" */ public String haRestartPriority; /** @@ -502,6 +523,38 @@ public class VM extends XenAPIObject { * true if this snapshot was created by the protection policy */ public Boolean isSnapshotFromVmpp; + /** + * the appliance to which this VM belongs + */ + public VMAppliance appliance; + /** + * The delay to wait before proceeding to the next order in the startup sequence (seconds) + */ + public Long startDelay; + /** + * The delay to wait before proceeding to the next order in the shutdown sequence (seconds) + */ + public Long shutdownDelay; + /** + * The point in the startup or shutdown sequence at which this VM will be started + */ + public Long order; + /** + * Virtual GPUs + */ + public Set VGPUs; + /** + * Currently passed-through PCI devices + */ + public Set attachedPCIs; + /** + * The SR on which a suspend image is stored + */ + public SR suspendSR; + /** + * The number of times this VM has been recovered + */ + public Long version; } /** @@ -1276,10 +1329,11 @@ public class VM extends XenAPIObject { /** * Get the PCI_bus field of the given VM. + * @deprecated * * @return value of the field */ - public String getPCIBus(Connection c) throws + @Deprecated public String getPCIBus(Connection c) throws BadServerResponse, XenAPIException, XmlRpcException { @@ -1463,10 +1517,11 @@ public class VM extends XenAPIObject { /** * Get the ha_always_run field of the given VM. + * @deprecated * * @return value of the field */ - public Boolean getHaAlwaysRun(Connection c) throws + @Deprecated public Boolean getHaAlwaysRun(Connection c) throws BadServerResponse, XenAPIException, XmlRpcException { @@ -1750,6 +1805,142 @@ public class VM extends XenAPIObject { return Types.toBoolean(result); } + /** + * Get the appliance field of the given VM. + * + * @return value of the field + */ + public VMAppliance getAppliance(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.get_appliance"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toVMAppliance(result); + } + + /** + * Get the start_delay field of the given VM. + * + * @return value of the field + */ + public Long getStartDelay(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.get_start_delay"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toLong(result); + } + + /** + * Get the shutdown_delay field of the given VM. + * + * @return value of the field + */ + public Long getShutdownDelay(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.get_shutdown_delay"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toLong(result); + } + + /** + * Get the order field of the given VM. + * + * @return value of the field + */ + public Long getOrder(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.get_order"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toLong(result); + } + + /** + * Get the VGPUs field of the given VM. + * + * @return value of the field + */ + public Set getVGPUs(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.get_VGPUs"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfVGPU(result); + } + + /** + * Get the attached_PCIs field of the given VM. + * + * @return value of the field + */ + public Set getAttachedPCIs(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.get_attached_PCIs"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfPCI(result); + } + + /** + * Get the suspend_SR field of the given VM. + * + * @return value of the field + */ + public SR getSuspendSR(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.get_suspend_SR"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSR(result); + } + + /** + * Get the version field of the given VM. + * + * @return value of the field + */ + public Long getVersion(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.get_version"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toLong(result); + } + /** * Set the name/label field of the given VM. * @@ -2139,10 +2330,11 @@ public class VM extends XenAPIObject { /** * Set the PCI_bus field of the given VM. + * @deprecated * * @param PCIBus New value to set */ - public void setPCIBus(Connection c, String PCIBus) throws + @Deprecated public void setPCIBus(Connection c, String PCIBus) throws BadServerResponse, XenAPIException, XmlRpcException { @@ -2364,6 +2556,22 @@ public class VM extends XenAPIObject { return; } + /** + * Set the suspend_SR field of the given VM. + * + * @param suspendSR New value to set + */ + public void setSuspendSR(Connection c, SR suspendSR) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.set_suspend_SR"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(suspendSR)}; + Map response = c.dispatch(method_call, method_params); + return; + } + /** * Snapshots the specified VM, making a new VM. Snapshot automatically exploits the capabilities of the underlying storage repository in which the VM's disk images are stored (e.g. Copy on Write). * @@ -3302,10 +3510,11 @@ public class VM extends XenAPIObject { /** * Set the value of the ha_always_run + * @deprecated * * @param value The value */ - public void setHaAlwaysRun(Connection c, Boolean value) throws + @Deprecated public void setHaAlwaysRun(Connection c, Boolean value) throws BadServerResponse, XenAPIException, XmlRpcException { @@ -3599,10 +3808,11 @@ public class VM extends XenAPIObject { /** * Return true if the VM is currently 'co-operative' i.e. is expected to reach a balloon target and actually has done + * @deprecated * * @return Task */ - public Task getCooperativeAsync(Connection c) throws + @Deprecated public Task getCooperativeAsync(Connection c) throws BadServerResponse, XenAPIException, XmlRpcException { @@ -3616,10 +3826,11 @@ public class VM extends XenAPIObject { /** * Return true if the VM is currently 'co-operative' i.e. is expected to reach a balloon target and actually has done + * @deprecated * * @return true if the VM is currently 'co-operative'; false otherwise */ - public Boolean getCooperative(Connection c) throws + @Deprecated public Boolean getCooperative(Connection c) throws BadServerResponse, XenAPIException, XmlRpcException { @@ -3823,6 +4034,92 @@ public class VM extends XenAPIObject { return Types.toLong(result); } + /** + * Migrate the VM to another host. This can only be called when the specified VM is in the Running state. + * + * @param dest The result of a Host.migrate_receive call. + * @param live Live migration + * @param vdiMap Map of source VDI to destination SR + * @param vifMap Map of source VIF to destination network + * @param options Other parameters + * @return Task + */ + public Task migrateSendAsync(Connection c, Map dest, Boolean live, Map vdiMap, Map vifMap, Map options) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState { + String method_call = "Async.VM.migrate_send"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dest), Marshalling.toXMLRPC(live), Marshalling.toXMLRPC(vdiMap), Marshalling.toXMLRPC(vifMap), Marshalling.toXMLRPC(options)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Migrate the VM to another host. This can only be called when the specified VM is in the Running state. + * + * @param dest The result of a Host.migrate_receive call. + * @param live Live migration + * @param vdiMap Map of source VDI to destination SR + * @param vifMap Map of source VIF to destination network + * @param options Other parameters + */ + public void migrateSend(Connection c, Map dest, Boolean live, Map vdiMap, Map vifMap, Map options) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmBadPowerState { + String method_call = "VM.migrate_send"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dest), Marshalling.toXMLRPC(live), Marshalling.toXMLRPC(vdiMap), Marshalling.toXMLRPC(vifMap), Marshalling.toXMLRPC(options)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Assert whether a VM can be migrated to the specified destination. + * + * @param dest The result of a VM.migrate_receive call. + * @param live Live migration + * @param vdiMap Map of source VDI to destination SR + * @param vifMap Map of source VIF to destination network + * @param options Other parameters + * @return Task + */ + public Task assertCanMigrateAsync(Connection c, Map dest, Boolean live, Map vdiMap, Map vifMap, Map options) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VM.assert_can_migrate"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dest), Marshalling.toXMLRPC(live), Marshalling.toXMLRPC(vdiMap), Marshalling.toXMLRPC(vifMap), Marshalling.toXMLRPC(options)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Assert whether a VM can be migrated to the specified destination. + * + * @param dest The result of a VM.migrate_receive call. + * @param live Live migration + * @param vdiMap Map of source VDI to destination SR + * @param vifMap Map of source VIF to destination network + * @param options Other parameters + */ + public void assertCanMigrate(Connection c, Map dest, Boolean live, Map vdiMap, Map vifMap, Map options) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.assert_can_migrate"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(dest), Marshalling.toXMLRPC(live), Marshalling.toXMLRPC(vdiMap), Marshalling.toXMLRPC(vifMap), Marshalling.toXMLRPC(options)}; + Map response = c.dispatch(method_call, method_params); + return; + } + /** * Returns a record describing the VM's dynamic state, initialised when the VM boots and updated to reflect runtime configuration changes e.g. CPU hotplug * @@ -3841,7 +4138,7 @@ public class VM extends XenAPIObject { } /** - * + * * * @return A set of data sources */ @@ -4052,7 +4349,8 @@ public class VM extends XenAPIObject { XenAPIException, XmlRpcException, Types.HostNotEnoughFreeMemory, - Types.VmRequiresSr { + Types.VmRequiresSr, + Types.VmHostIncompatibleVersion { String method_call = "Async.VM.assert_can_boot_here"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; @@ -4071,7 +4369,8 @@ public class VM extends XenAPIObject { XenAPIException, XmlRpcException, Types.HostNotEnoughFreeMemory, - Types.VmRequiresSr { + Types.VmRequiresSr, + Types.VmHostIncompatibleVersion { String method_call = "VM.assert_can_boot_here"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(host)}; @@ -4084,15 +4383,16 @@ public class VM extends XenAPIObject { * * @param name The name associated with the blob * @param mimeType The mime type for the data. Empty string translates to application/octet-stream + * @param _public True if the blob should be publicly available * @return Task */ - public Task createNewBlobAsync(Connection c, String name, String mimeType) throws + public Task createNewBlobAsync(Connection c, String name, String mimeType, Boolean _public) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "Async.VM.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); @@ -4103,15 +4403,16 @@ public class VM extends XenAPIObject { * * @param name The name associated with the blob * @param mimeType The mime type for the data. Empty string translates to application/octet-stream + * @param _public True if the blob should be publicly available * @return The reference of the blob, needed for populating its data */ - public Blob createNewBlob(Connection c, String name, String mimeType) throws + public Blob createNewBlob(Connection c, String name, String mimeType, Boolean _public) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = "VM.create_new_blob"; String session = c.getSessionReference(); - Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)}; + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType), Marshalling.toXMLRPC(_public)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toBlob(result); @@ -4233,6 +4534,326 @@ public class VM extends XenAPIObject { return; } + /** + * Set this VM's start delay in seconds + * + * @param value This VM's start delay in seconds + * @return Task + */ + public Task setStartDelayAsync(Connection c, Long value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VM.set_start_delay"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Set this VM's start delay in seconds + * + * @param value This VM's start delay in seconds + */ + public void setStartDelay(Connection c, Long value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.set_start_delay"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Set this VM's shutdown delay in seconds + * + * @param value This VM's shutdown delay in seconds + * @return Task + */ + public Task setShutdownDelayAsync(Connection c, Long value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VM.set_shutdown_delay"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Set this VM's shutdown delay in seconds + * + * @param value This VM's shutdown delay in seconds + */ + public void setShutdownDelay(Connection c, Long value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.set_shutdown_delay"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Set this VM's boot order + * + * @param value This VM's boot order + * @return Task + */ + public Task setOrderAsync(Connection c, Long value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VM.set_order"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Set this VM's boot order + * + * @param value This VM's boot order + */ + public void setOrder(Connection c, Long value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.set_order"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Set this VM's suspend VDI, which must be indentical to its current one + * + * @param value The suspend VDI uuid + * @return Task + */ + public Task setSuspendVDIAsync(Connection c, VDI value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VM.set_suspend_VDI"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Set this VM's suspend VDI, which must be indentical to its current one + * + * @param value The suspend VDI uuid + */ + public void setSuspendVDI(Connection c, VDI value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.set_suspend_VDI"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Assert whether all SRs required to recover this VM are available. + * + * @param sessionTo The session to which the VM is to be recovered. + * @return Task + */ + public Task assertCanBeRecoveredAsync(Connection c, Session sessionTo) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmIsPartOfAnAppliance, + Types.VmRequiresSr { + String method_call = "Async.VM.assert_can_be_recovered"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Assert whether all SRs required to recover this VM are available. + * + * @param sessionTo The session to which the VM is to be recovered. + */ + public void assertCanBeRecovered(Connection c, Session sessionTo) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmIsPartOfAnAppliance, + Types.VmRequiresSr { + String method_call = "VM.assert_can_be_recovered"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Recover the VM + * + * @param sessionTo The session to which the VM is to be recovered. + * @param force Whether the VM should replace newer versions of itself. + * @return Task + */ + public Task recoverAsync(Connection c, Session sessionTo, Boolean force) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VM.recover"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo), Marshalling.toXMLRPC(force)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Recover the VM + * + * @param sessionTo The session to which the VM is to be recovered. + * @param force Whether the VM should replace newer versions of itself. + */ + public void recover(Connection c, Session sessionTo, Boolean force) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.recover"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo), Marshalling.toXMLRPC(force)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Import using a conversion service. + * + * @param type Type of the conversion + * @param username Admin username on the host + * @param password Password on the host + * @param sr The destination SR + * @param remoteConfig Remote configuration options + * @return Task + */ + public static Task importConvertAsync(Connection c, String type, String username, String password, SR sr, Map remoteConfig) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VM.import_convert"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(username), Marshalling.toXMLRPC(password), Marshalling.toXMLRPC(sr), Marshalling.toXMLRPC(remoteConfig)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Import using a conversion service. + * + * @param type Type of the conversion + * @param username Admin username on the host + * @param password Password on the host + * @param sr The destination SR + * @param remoteConfig Remote configuration options + */ + public static void importConvert(Connection c, String type, String username, String password, SR sr, Map remoteConfig) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.import_convert"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(type), Marshalling.toXMLRPC(username), Marshalling.toXMLRPC(password), Marshalling.toXMLRPC(sr), Marshalling.toXMLRPC(remoteConfig)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Assign this VM to an appliance. + * + * @param value The appliance to which this VM should be assigned. + * @return Task + */ + public Task setApplianceAsync(Connection c, VMAppliance value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VM.set_appliance"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Assign this VM to an appliance. + * + * @param value The appliance to which this VM should be assigned. + */ + public void setAppliance(Connection c, VMAppliance value) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.set_appliance"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Query the system services advertised by this VM and register them. This can only be applied to a system domain. + * + * @return Task + */ + public Task queryServicesAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VM.query_services"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Query the system services advertised by this VM and register them. This can only be applied to a system domain. + * + * @return map of service type to name + */ + public Map queryServices(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM.query_services"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfStringString(result); + } + /** * Return a list of all the VMs known to the system. * @@ -4267,4 +4888,4 @@ public class VM extends XenAPIObject { return Types.toMapOfVMVMRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VMAppliance.java b/deps/XenServerJava/src/com/xensource/xenapi/VMAppliance.java new file mode 100644 index 00000000000..a04026314b9 --- /dev/null +++ b/deps/XenServerJava/src/com/xensource/xenapi/VMAppliance.java @@ -0,0 +1,655 @@ +/* + * Copyright (c) Citrix Systems, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1) Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2) Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +package com.xensource.xenapi; + +import com.xensource.xenapi.Types.BadServerResponse; +import com.xensource.xenapi.Types.VersionException; +import com.xensource.xenapi.Types.XenAPIException; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.xmlrpc.XmlRpcException; + +/** + * VM appliance + * + * @author Citrix Systems, Inc. + */ +public class VMAppliance extends XenAPIObject { + + /** + * The XenAPI reference (OpaqueRef) to this object. + */ + protected final String ref; + + /** + * For internal use only. + */ + VMAppliance(String ref) { + this.ref = ref; + } + + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ + public String toWireString() { + return this.ref; + } + + /** + * If obj is a VMAppliance, compares XenAPI references for equality. + */ + @Override + public boolean equals(Object obj) + { + if (obj != null && obj instanceof VMAppliance) + { + VMAppliance other = (VMAppliance) obj; + return other.ref.equals(this.ref); + } else + { + return false; + } + } + + @Override + public int hashCode() + { + return ref.hashCode(); + } + + /** + * Represents all the fields in a VMAppliance + */ + public static class Record implements Types.Record { + public String toString() { + StringWriter writer = new StringWriter(); + PrintWriter print = new PrintWriter(writer); + print.printf("%1$20s: %2$s\n", "uuid", this.uuid); + print.printf("%1$20s: %2$s\n", "nameLabel", this.nameLabel); + print.printf("%1$20s: %2$s\n", "nameDescription", this.nameDescription); + print.printf("%1$20s: %2$s\n", "allowedOperations", this.allowedOperations); + print.printf("%1$20s: %2$s\n", "currentOperations", this.currentOperations); + print.printf("%1$20s: %2$s\n", "VMs", this.VMs); + return writer.toString(); + } + + /** + * Convert a VM_appliance.Record to a Map + */ + public Map toMap() { + Map map = new HashMap(); + map.put("uuid", this.uuid == null ? "" : this.uuid); + map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); + map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); + map.put("allowed_operations", this.allowedOperations == null ? new LinkedHashSet() : this.allowedOperations); + map.put("current_operations", this.currentOperations == null ? new HashMap() : this.currentOperations); + map.put("VMs", this.VMs == null ? new LinkedHashSet() : this.VMs); + return map; + } + + /** + * Unique identifier/object reference + */ + public String uuid; + /** + * a human-readable name + */ + public String nameLabel; + /** + * a notes field containing human-readable description + */ + public String nameDescription; + /** + * list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client. + */ + public Set allowedOperations; + /** + * links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task. + */ + public Map currentOperations; + /** + * all VMs in this appliance + */ + public Set VMs; + } + + /** + * Get a record containing the current state of the given VM_appliance. + * + * @return all fields from the object + */ + public VMAppliance.Record getRecord(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.get_record"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toVMApplianceRecord(result); + } + + /** + * Get a reference to the VM_appliance instance with the specified UUID. + * + * @param uuid UUID of object to return + * @return reference to the object + */ + public static VMAppliance getByUuid(Connection c, String uuid) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.get_by_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toVMAppliance(result); + } + + /** + * Create a new VM_appliance instance, and return its handle. + * + * @param record All constructor arguments + * @return Task + */ + public static Task createAsync(Connection c, VMAppliance.Record record) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VM_appliance.create"; + String session = c.getSessionReference(); + Map record_map = record.toMap(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Create a new VM_appliance instance, and return its handle. + * + * @param record All constructor arguments + * @return reference to the newly created object + */ + public static VMAppliance create(Connection c, VMAppliance.Record record) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.create"; + String session = c.getSessionReference(); + Map record_map = record.toMap(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toVMAppliance(result); + } + + /** + * Destroy the specified VM_appliance instance. + * + * @return Task + */ + public Task destroyAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "Async.VM_appliance.destroy"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Destroy the specified VM_appliance instance. + * + */ + public void destroy(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.destroy"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Get all the VM_appliance instances with the given label. + * + * @param label label of object to return + * @return references to objects with matching names + */ + public static Set getByNameLabel(Connection c, String label) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.get_by_name_label"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfVMAppliance(result); + } + + /** + * Get the uuid field of the given VM_appliance. + * + * @return value of the field + */ + public String getUuid(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.get_uuid"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the name/label field of the given VM_appliance. + * + * @return value of the field + */ + public String getNameLabel(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.get_name_label"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the name/description field of the given VM_appliance. + * + * @return value of the field + */ + public String getNameDescription(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.get_name_description"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toString(result); + } + + /** + * Get the allowed_operations field of the given VM_appliance. + * + * @return value of the field + */ + public Set getAllowedOperations(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.get_allowed_operations"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfVmApplianceOperation(result); + } + + /** + * Get the current_operations field of the given VM_appliance. + * + * @return value of the field + */ + public Map getCurrentOperations(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.get_current_operations"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfStringVmApplianceOperation(result); + } + + /** + * Get the VMs field of the given VM_appliance. + * + * @return value of the field + */ + public Set getVMs(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.get_VMs"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfVM(result); + } + + /** + * Set the name/label field of the given VM_appliance. + * + * @param label New value to set + */ + public void setNameLabel(Connection c, String label) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.set_name_label"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(label)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Set the name/description field of the given VM_appliance. + * + * @param description New value to set + */ + public void setNameDescription(Connection c, String description) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.set_name_description"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(description)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Start all VMs in the appliance + * + * @param paused Instantiate all VMs belonging to this appliance in paused state if set to true. + * @return Task + */ + public Task startAsync(Connection c, Boolean paused) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { + String method_call = "Async.VM_appliance.start"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(paused)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Start all VMs in the appliance + * + * @param paused Instantiate all VMs belonging to this appliance in paused state if set to true. + */ + public void start(Connection c, Boolean paused) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { + String method_call = "VM_appliance.start"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(paused)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Perform a clean shutdown of all the VMs in the appliance + * + * @return Task + */ + public Task cleanShutdownAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { + String method_call = "Async.VM_appliance.clean_shutdown"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Perform a clean shutdown of all the VMs in the appliance + * + */ + public void cleanShutdown(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { + String method_call = "VM_appliance.clean_shutdown"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Perform a hard shutdown of all the VMs in the appliance + * + * @return Task + */ + public Task hardShutdownAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { + String method_call = "Async.VM_appliance.hard_shutdown"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Perform a hard shutdown of all the VMs in the appliance + * + */ + public void hardShutdown(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { + String method_call = "VM_appliance.hard_shutdown"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * For each VM in the appliance, try to shut it down cleanly. If this fails, perform a hard shutdown of the VM. + * + * @return Task + */ + public Task shutdownAsync(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { + String method_call = "Async.VM_appliance.shutdown"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * For each VM in the appliance, try to shut it down cleanly. If this fails, perform a hard shutdown of the VM. + * + */ + public void shutdown(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.OperationPartiallyFailed { + String method_call = "VM_appliance.shutdown"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Assert whether all SRs required to recover this VM appliance are available. + * + * @param sessionTo The session to which the VM appliance is to be recovered. + * @return Task + */ + public Task assertCanBeRecoveredAsync(Connection c, Session sessionTo) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmRequiresSr { + String method_call = "Async.VM_appliance.assert_can_be_recovered"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Assert whether all SRs required to recover this VM appliance are available. + * + * @param sessionTo The session to which the VM appliance is to be recovered. + */ + public void assertCanBeRecovered(Connection c, Session sessionTo) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmRequiresSr { + String method_call = "VM_appliance.assert_can_be_recovered"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Recover the VM appliance + * + * @param sessionTo The session to which the VM appliance is to be recovered. + * @param force Whether the VMs should replace newer versions of themselves. + * @return Task + */ + public Task recoverAsync(Connection c, Session sessionTo, Boolean force) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmRequiresSr { + String method_call = "Async.VM_appliance.recover"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo), Marshalling.toXMLRPC(force)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toTask(result); + } + + /** + * Recover the VM appliance + * + * @param sessionTo The session to which the VM appliance is to be recovered. + * @param force Whether the VMs should replace newer versions of themselves. + */ + public void recover(Connection c, Session sessionTo, Boolean force) throws + BadServerResponse, + XenAPIException, + XmlRpcException, + Types.VmRequiresSr { + String method_call = "VM_appliance.recover"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(sessionTo), Marshalling.toXMLRPC(force)}; + Map response = c.dispatch(method_call, method_params); + return; + } + + /** + * Return a list of all the VM_appliances known to the system. + * + * @return references to all objects + */ + public static Set getAll(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.get_all"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toSetOfVMAppliance(result); + } + + /** + * Return a map of VM_appliance references to VM_appliance records for all VM_appliances known to the system. + * + * @return records of all objects + */ + public static Map getAllRecords(Connection c) throws + BadServerResponse, + XenAPIException, + XmlRpcException { + String method_call = "VM_appliance.get_all_records"; + String session = c.getSessionReference(); + Object[] method_params = {Marshalling.toXMLRPC(session)}; + Map response = c.dispatch(method_call, method_params); + Object result = response.get("Value"); + return Types.toMapOfVMApplianceVMApplianceRecord(result); + } + +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VMGuestMetrics.java b/deps/XenServerJava/src/com/xensource/xenapi/VMGuestMetrics.java index 8b27955df87..9a6caf052bd 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VMGuestMetrics.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VMGuestMetrics.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class VMGuestMetrics extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class VMGuestMetrics extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -479,4 +484,4 @@ public class VMGuestMetrics extends XenAPIObject { return Types.toMapOfVMGuestMetricsVMGuestMetricsRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VMMetrics.java b/deps/XenServerJava/src/com/xensource/xenapi/VMMetrics.java index c2d35b35afa..8544e42e143 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VMMetrics.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VMMetrics.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class VMMetrics extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class VMMetrics extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -502,4 +507,4 @@ public class VMMetrics extends XenAPIObject { return Types.toMapOfVMMetricsVMMetricsRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VMPP.java b/deps/XenServerJava/src/com/xensource/xenapi/VMPP.java index aeb0d03fdbe..3e8d2fbdd42 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VMPP.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VMPP.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class VMPP extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class VMPP extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -155,7 +160,7 @@ public class VMPP extends XenAPIObject { */ public String nameLabel; /** - * a notes field containg human-readable description + * a notes field containing human-readable description */ public String nameDescription; /** @@ -809,7 +814,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param value the value to set */ @@ -841,7 +846,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param value the value to set */ @@ -873,7 +878,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param value the value to set */ @@ -905,7 +910,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param value the value to set */ @@ -937,7 +942,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param value the value to set */ @@ -953,7 +958,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param key the key to add * @param value the value to add @@ -970,7 +975,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param key the key to add * @param value the value to add @@ -987,7 +992,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param key the key to add * @param value the value to add @@ -1004,7 +1009,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param key the key to add * @param value the value to add @@ -1021,7 +1026,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param key the key to remove */ @@ -1037,7 +1042,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param key the key to remove */ @@ -1053,7 +1058,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param key the key to remove */ @@ -1069,7 +1074,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param key the key to remove */ @@ -1085,7 +1090,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param value the value to set */ @@ -1101,7 +1106,7 @@ public class VMPP extends XenAPIObject { } /** - * + * * * @param value the value to set */ @@ -1150,4 +1155,4 @@ public class VMPP extends XenAPIObject { return Types.toMapOfVMPPVMPPRecord(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/VTPM.java b/deps/XenServerJava/src/com/xensource/xenapi/VTPM.java index c82fa3f4606..71736a01664 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/VTPM.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/VTPM.java @@ -1,18 +1,19 @@ -/* Copyright (c) Citrix Systems, Inc. +/* + * Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS @@ -27,6 +28,7 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ + package com.xensource.xenapi; import com.xensource.xenapi.Types.BadServerResponse; @@ -51,7 +53,7 @@ import org.apache.xmlrpc.XmlRpcException; public class VTPM extends XenAPIObject { /** - * The XenAPI reference to this object. + * The XenAPI reference (OpaqueRef) to this object. */ protected final String ref; @@ -62,6 +64,9 @@ public class VTPM extends XenAPIObject { this.ref = ref; } + /** + * @return The XenAPI reference (OpaqueRef) to this object. + */ public String toWireString() { return this.ref; } @@ -282,4 +287,4 @@ public class VTPM extends XenAPIObject { return Types.toVM(result); } -} +} \ No newline at end of file diff --git a/deps/XenServerJava/src/com/xensource/xenapi/XenAPIObject.java b/deps/XenServerJava/src/com/xensource/xenapi/XenAPIObject.java index b500024255b..b678a7fa1ec 100644 --- a/deps/XenServerJava/src/com/xensource/xenapi/XenAPIObject.java +++ b/deps/XenServerJava/src/com/xensource/xenapi/XenAPIObject.java @@ -1,18 +1,18 @@ /* Copyright (c) Citrix Systems, Inc. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. - * + * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS diff --git a/docs/README.txt b/docs/README.txt index 7f096e4b117..e327fb9101c 100644 --- a/docs/README.txt +++ b/docs/README.txt @@ -201,7 +201,7 @@ TAGS FOR A SECTION
Text of the section title Here's the text of a paragraph in this section. - Always use &PRODUCT; rather than typing CloudStack or CloudPlatform. + Always use &PRODUCT; rather than typing CloudStack. Indent with 4 spaces, not with tab characters. To hyperlink to a URL outside this document: Display text of the link here To hyperlink to another section in this document: diff --git a/docs/en-US/Book_Info_Release_Notes_4.0.xml b/docs/en-US/Book_Info_Release_Notes_4-0.xml similarity index 100% rename from docs/en-US/Book_Info_Release_Notes_4.0.xml rename to docs/en-US/Book_Info_Release_Notes_4-0.xml diff --git a/docs/en-US/API_Developers_Guide.ent b/docs/en-US/Developers_Guide.ent similarity index 100% rename from docs/en-US/API_Developers_Guide.ent rename to docs/en-US/Developers_Guide.ent diff --git a/docs/en-US/API_Developers_Guide.xml b/docs/en-US/Developers_Guide.xml similarity index 85% rename from docs/en-US/API_Developers_Guide.xml rename to docs/en-US/Developers_Guide.xml index c691ad02cf6..6c09354f6a8 100644 --- a/docs/en-US/API_Developers_Guide.xml +++ b/docs/en-US/Developers_Guide.xml @@ -24,14 +24,14 @@ - &PRODUCT; API Developer's Guide + &PRODUCT; Developer's Guide Apache CloudStack 4.0.0-incubating - How to integrate with &PRODUCT; using the &PRODUCT; API. + This guide shows how to develop &PRODUCT;, use the API for operation and integration, access the usage data and use &PRODUCT; specific tools to ease development, testing and integration. @@ -45,10 +45,12 @@ + + diff --git a/docs/en-US/Release_Notes.xml b/docs/en-US/Release_Notes.xml index 17f9079cc01..c8cc6869737 100644 --- a/docs/en-US/Release_Notes.xml +++ b/docs/en-US/Release_Notes.xml @@ -19,7 +19,7 @@ under the License. --> - + Submitting Feedback and Getting Help The Apache CloudStack project has mailing lists for users and developers. These are the diff --git a/docs/en-US/about-password-encryption.xml b/docs/en-US/about-password-encryption.xml index 3f7c4c84350..3cd84d19508 100644 --- a/docs/en-US/about-password-encryption.xml +++ b/docs/en-US/about-password-encryption.xml @@ -54,8 +54,8 @@ external source during Management Server startup. This key can be provided in one of two ways: loaded from a file or provided by the &PRODUCT; administrator. The &PRODUCT; database has a new configuration setting that lets it know which of these methods will be used. If the encryption - type is set to “file,†the key must be in a file in a known location. If the encryption type is - set to “web,†the administrator runs the utility + type is set to "file," the key must be in a file in a known location. If the encryption type is + set to "web," the administrator runs the utility com.cloud.utils.crypt.EncryptionSecretKeySender, which relays the key to the Management Server over a known port. The encryption type, database secret key, and Management Server secret key are set during diff --git a/docs/en-US/added-API-commands-4.0.xml b/docs/en-US/added-API-commands-4-0.xml similarity index 100% rename from docs/en-US/added-API-commands-4.0.xml rename to docs/en-US/added-API-commands-4-0.xml diff --git a/docs/en-US/building-devcloud.xml b/docs/en-US/building-devcloud.xml new file mode 100644 index 00000000000..5f792c375a2 --- /dev/null +++ b/docs/en-US/building-devcloud.xml @@ -0,0 +1,32 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Building DevCloud + The DevCloud appliance can be downloaded from the wiki at . It can also be built from scratch. Code is being developed to provide this alternative build. It is based on veewee, Vagrant and Puppet. + The goal is to automate the DevCloud build and make this automation capability available to all within the source release of &PRODUCT; + This is under heavy development. The code is located in the source tree under tools/devcloud + A preliminary wiki page describes the build at https://cwiki.pache.org/CLOUDSTACK/building-devcloud.html + +
diff --git a/docs/en-US/building-prerequisites.xml b/docs/en-US/building-prerequisites.xml new file mode 100644 index 00000000000..d97ca40f2a3 --- /dev/null +++ b/docs/en-US/building-prerequisites.xml @@ -0,0 +1,66 @@ + + +%BOOK_ENTITIES; +]> + + + + +
+ Build Procedure Prerequisites + In this section we will assume that you are using the Ubuntu Linux distribution with the Advanced Packaging Tool (APT). If you are using a different distribution or OS and a different packaging tool, adapt the following instructions to your environment. To build &PRODUCT; you will need: + + + git, http://git-scm.com + sudo apt-get install git-core + + + maven, http://maven.apache.org + sudo apt-get install maven + Make sure that you installed maven 3 + $ mvn --version +Apache Maven 3.0.4 +Maven home: /usr/share/maven +Java version: 1.6.0_24, vendor: Sun Microsystems Inc. +Java home: /usr/lib/jvm/java-6-openjdk-amd64/jre +Default locale: en_US, platform encoding: UTF-8 +OS name: "linux", version: "3.2.0-33-generic", arch: "amd64", family: "unix" + + + java + set the JAVA_HOME environment variable + $ export JAVA_HOME=/usr/lib/jvm/java-6-openjdk + + + + In addition, to deploy and run &PRODUCT; in a development environment you will need: + + + Mysql + sudo apt-get install mysql-server-5.5 + Start the mysqld service and create a cloud user with cloud as a password + + + Tomcat 6 + sudo apt-get install tomcat6 + + + +
diff --git a/docs/en-US/building-with-maven-deploy.xml b/docs/en-US/building-with-maven-deploy.xml new file mode 100644 index 00000000000..e4b9801aa30 --- /dev/null +++ b/docs/en-US/building-with-maven-deploy.xml @@ -0,0 +1,39 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Deployment and Testing Steps + Deploying the &PRODUCT; code that you compiled is a two step process: + + If you have not configured the database or modified its properties do: + mvn -P developer -pl developer -Ddeploydb + + Then you need to run the &PRODUCT; management server. To attach a debugger to it, do: + export MAVEN_OPTS="-Xmx1024 -Xdebug -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n" + mvn -pl :cloud-client-ui jetty:run + + + When dealing with the database, remember that you may wipe it entirely and lose any data center configuration that you may have set previously. +
+ diff --git a/docs/en-US/building-with-maven-steps.xml b/docs/en-US/building-with-maven-steps.xml new file mode 100644 index 00000000000..319654fb290 --- /dev/null +++ b/docs/en-US/building-with-maven-steps.xml @@ -0,0 +1,33 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Building Steps + &PRODUCT; uses git for source version control, first make sure you have the source code by pulling it: + git clone https://git-wip-us.apache.org/repos/asf/incubator-cloudstack.git + Several Project Object Models (POM) are defined to deal with the various build targets of &PRODUCT;. Certain features require some packages that are not compatible with the Apache license and therefore need to be downloaded on your own. Check the wiki for additional information https://cwiki.apache.org/CLOUDSTACK/building-with-maven.html. In order to build all the open source targets of &PRODUCT; do: + mvn clean install + The resulting jar files will be in the target directory of the subdirectory of the compiled module. +
+ diff --git a/docs/en-US/building-with-maven.xml b/docs/en-US/building-with-maven.xml new file mode 100644 index 00000000000..5363b1d754a --- /dev/null +++ b/docs/en-US/building-with-maven.xml @@ -0,0 +1,32 @@ + + +%BOOK_ENTITIES; +]> + + + + + Using Maven to Build &PRODUCT; + + + + + + diff --git a/docs/en-US/change-database-config.xml b/docs/en-US/change-database-config.xml index fadb64c27e7..34e767251e0 100644 --- a/docs/en-US/change-database-config.xml +++ b/docs/en-US/change-database-config.xml @@ -24,5 +24,5 @@
Changing the Database Configuration - The &PRODUCT; Management Server stores database configuration information (e.g., hostname, port, credentials) in the file /etc/cloud/management/db.properties. To effect a change, edit this file on each Management Server, then restart the Management Server. -
\ No newline at end of file + The &PRODUCT; Management Server stores database configuration information (e.g., hostname, port, credentials) in the file /etc/cloud/management/db.properties. To effect a change, edit this file on each Management Server, then restart the Management Server. +
diff --git a/docs/en-US/change-database-password.xml b/docs/en-US/change-database-password.xml new file mode 100644 index 00000000000..0ab52675e3c --- /dev/null +++ b/docs/en-US/change-database-password.xml @@ -0,0 +1,76 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Changing the Database Password + You may need to change the password for the MySQL account used by CloudStack. If so, you'll need to change the password in MySQL, and then add the encrypted password to /etc/cloud/management/db.properties. + + + Before changing the password, you'll need to stop CloudStack's management server and the usage engine if you've deployed that component. + +# service cloud-management stop +# service cloud-usage stop + + + + Next, you'll update the password for the CloudStack user on the MySQL server. + +# mysql -u root -p + + At the MySQL shell, you'll change the password and flush privileges: + +update mysql.user set password=PASSWORD("newpassword123") where User='cloud'; +flush privileges; +quit; + + + + The next step is to encrypt the password and copy the encrypted password to CloudStack's database configuration (/etc/cloud/management/db.properties). + +# java -classpath /usr/share/java/cloud-jasypt-1.8.jar \ +org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI encrypt.sh \ +input="newpassword123" password="`cat /etc/cloud/management/key`" \ +verbose=false + + +File encryption type + Note that this is for the file encryption type. If you're using the web encryption type then you'll use password="management_server_secret_key" + + + + Now, you'll update /etc/cloud/management/db.properties with the new ciphertext. Open /etc/cloud/management/db.properties in a text editor, and update these parameters: + +db.cloud.password=ENC(encrypted_password_from_above) +db.usage.password=ENC(encrypted_password_from_above) + + + + After copying the new password over, you can now start CloudStack (and the usage engine, if necessary). + + # service cloud-management start + # service cloud-usage start + + + +
diff --git a/docs/en-US/changed-apicommands-4.0.xml b/docs/en-US/changed-apicommands-4-0.xml similarity index 100% rename from docs/en-US/changed-apicommands-4.0.xml rename to docs/en-US/changed-apicommands-4-0.xml diff --git a/docs/en-US/devcloud-usage-mode.xml b/docs/en-US/devcloud-usage-mode.xml new file mode 100644 index 00000000000..bb65f904ccd --- /dev/null +++ b/docs/en-US/devcloud-usage-mode.xml @@ -0,0 +1,60 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ DevCloud Usage Mode + DevCloud can be used in several different ways: + + + Full sandbox. Where &PRODUCT; is run within the DevCloud instance started in Virtual Box. + In this mode, the &PRODUCT; management server runs within the instance and nested virtualization allows instantiation of tiny VMs within DevCloud itself. &PRODUCT; code modifications are done within DevCloud. + The following diagram shows the architecture of the SandBox mode. + + + + + + DevCloud.png: Schematic of the DevCloud SandBox architecture + + + + + A deployment environment. Where &PRODUCT; code is developed in the localhost of the developer and the resulting build is deployed within DevCloud + This mode was used in the testing procedure of &PRODUCT; 4.0.0 incubating release. See the following screencast to see how: http://vimeo.com/54621457 + + + A host-only mode. Where DevCloud is used only as a host. &PRODUCT; management server is run in the localhost of the developer + This mode makes use of a host-only interface defined in the Virtual Box preferences. Check the following screencast to see how: http://vimeo.com/54610161 + The following schematic shows the architecture of the Host-Only mode. + + + + + + DevCloud-hostonly.png: Schematic of the DevCloud host-only architecture + + + + +
diff --git a/docs/en-US/devcloud.xml b/docs/en-US/devcloud.xml new file mode 100644 index 00000000000..677818700ae --- /dev/null +++ b/docs/en-US/devcloud.xml @@ -0,0 +1,38 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ DevCloud + DevCloud is the &PRODUCT; sandbox. It is provided as a Virtual Box appliance. It is meant to be used as a development environment to easily test new &PRODUCT; development. It has also been used for training and &PRODUCT; demos since it provides a Cloud in a box. + + DevCloud is provided as a convenience by community members. It is not an official &PRODUCT; release artifact. + The &PRODUCT; source code however, contains tools to build your own DevCloud. + + + DevCloud is under development and should be considered a Work In Progress (WIP), the wiki is the most up to date documentation: + + + + +
diff --git a/docs/en-US/developer-introduction.xml b/docs/en-US/developer-introduction.xml index bb5251b4f26..9d54f31dae9 100644 --- a/docs/en-US/developer-introduction.xml +++ b/docs/en-US/developer-introduction.xml @@ -23,7 +23,7 @@ --> - Introduction for Developers + Introduction to the &PRODUCT; API diff --git a/docs/en-US/images/DevCloud-hostonly.png b/docs/en-US/images/DevCloud-hostonly.png new file mode 100644 index 00000000000..111f93ac700 Binary files /dev/null and b/docs/en-US/images/DevCloud-hostonly.png differ diff --git a/docs/en-US/images/DevCloud.png b/docs/en-US/images/DevCloud.png new file mode 100644 index 00000000000..5e83ca946c7 Binary files /dev/null and b/docs/en-US/images/DevCloud.png differ diff --git a/docs/en-US/loadbalancer-policy-port-forwarding-rule-usage-record-format.xml b/docs/en-US/lb-policy-pfwd-rule-usage-record-format.xml similarity index 100% rename from docs/en-US/loadbalancer-policy-port-forwarding-rule-usage-record-format.xml rename to docs/en-US/lb-policy-pfwd-rule-usage-record-format.xml diff --git a/docs/en-US/manage-cloud.xml b/docs/en-US/manage-cloud.xml index 3e29d09cdc1..f5df2c62325 100644 --- a/docs/en-US/manage-cloud.xml +++ b/docs/en-US/manage-cloud.xml @@ -26,7 +26,8 @@ Managing the Cloud + - \ No newline at end of file + diff --git a/docs/en-US/management-server-install-nfs-shares.xml b/docs/en-US/management-server-install-nfs-shares.xml index 28e3fa30de1..e917a8e0b6c 100644 --- a/docs/en-US/management-server-install-nfs-shares.xml +++ b/docs/en-US/management-server-install-nfs-shares.xml @@ -25,11 +25,13 @@
Prepare NFS Shares &PRODUCT; needs a place to keep primary and secondary storage (see Cloud Infrastructure Overview). Both of these can be NFS shares. This section tells how to set up the NFS shares before adding the storage to &PRODUCT;. - For primary storage, you can use iSCSI instead. + Alternative Storage + NFS is not the only option for primary or secondary storage. For example, you may use a Ceph RDB cluster, GlusterFS, iSCSI, and otthers. + The requirements for primary and secondary storage are described in: - About Primary Storage - About Secondary Storage + + A production installation typically uses a separate NFS server. See . You can also use the Management Server node as the NFS server. This is more typical of a trial installation, but is technically possible in a larger deployment. See . diff --git a/docs/en-US/management-server-install-systemvm.xml b/docs/en-US/management-server-install-systemvm.xml index 6cd1ef7a0ff..df2c3738abf 100644 --- a/docs/en-US/management-server-install-systemvm.xml +++ b/docs/en-US/management-server-install-systemvm.xml @@ -37,8 +37,7 @@ If your secondary storage mount point is not named /mnt/secondary, substitute your own mount point name. If you set the &PRODUCT; database encryption type to "web" when you set up the database, - you must now add the parameter -s <management-server-secret-key>. See About Password - and Key Encryption. + you must now add the parameter -s <management-server-secret-key>. See . This process will require approximately 5 GB of free space on the local file system and up to 30 minutes each time it runs. diff --git a/docs/en-US/marvin.xml b/docs/en-US/marvin.xml new file mode 100644 index 00000000000..062616ac888 --- /dev/null +++ b/docs/en-US/marvin.xml @@ -0,0 +1,32 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Marvin + Marvin is the &PRODUCT; automation framework. It originated as a tool for integration testing but is now also used to build DevCloud as well as to provide a Python &PRODUCT; API binding. + + Marvin's complete documenation is on the wiki at https://cwiki.apache.org/CLOUDSTACK/testing-with-python.html + The source code is located at tools/marvin + +
diff --git a/docs/en-US/nfs-shares-on-management-server.xml b/docs/en-US/nfs-shares-on-management-server.xml index 2c9b324d1a2..c000ce4818d 100644 --- a/docs/en-US/nfs-shares-on-management-server.xml +++ b/docs/en-US/nfs-shares-on-management-server.xml @@ -23,10 +23,15 @@ -->
- Using the Management Server As the NFS Server + Using the Management Server as the NFS Server This section tells how to set up NFS shares for primary and secondary storage on the same node with the Management Server. This is more typical of a trial installation, but is technically possible in a larger deployment. It is assumed that you will have less than 16TB of storage on the host. The exact commands for the following steps may vary depending on your operating system version. + On Ubuntu/Debian systems, you'll need to install the nfs-kernel-server package: + +$ sudo apt-get install nfs-kernel-server + + On the Management Server host, create two directories that you will use for primary and secondary storage. For example: # mkdir -p /export/primary diff --git a/docs/en-US/ongoing-configuration-of-external-firewalls-loadbalancer.xml b/docs/en-US/ongoing-config-of-ext-firewalls-lb.xml similarity index 100% rename from docs/en-US/ongoing-configuration-of-external-firewalls-loadbalancer.xml rename to docs/en-US/ongoing-config-of-ext-firewalls-lb.xml diff --git a/docs/en-US/primary-storage.xml b/docs/en-US/primary-storage.xml index 7010868d24b..e1736a9d30e 100644 --- a/docs/en-US/primary-storage.xml +++ b/docs/en-US/primary-storage.xml @@ -24,7 +24,8 @@
Primary Storage - This section gives concepts and technical details about &PRODUCT; primary storage. For information about how to install and configure primary storage through the &PRODUCT; UI, see the Advanced Installation Guide. + This section gives concepts and technical details about &PRODUCT; primary storage. For information about how to install and configure primary storage through the &PRODUCT; UI, see the Installation Guide. + diff --git a/docs/en-US/provisioning-steps.xml.orig b/docs/en-US/provisioning-steps.xml.orig deleted file mode 100644 index b532783b2d2..00000000000 --- a/docs/en-US/provisioning-steps.xml.orig +++ /dev/null @@ -1,42 +0,0 @@ - - -%BOOK_ENTITIES; -]> - - - - - Steps to Provisioning Your Cloud Infrastructure - This section tells how to add zones, pods, clusters, hosts, storage, and networks to your cloud. If you are unfamiliar with these entities, please begin by looking through . - - - - - - - - - -<<<<<<< HEAD - -
-======= - ->>>>>>> Promote sections to chapters: Cloud Infrastructure Concepts and Provisioning Steps. diff --git a/docs/en-US/secondary-storage.xml b/docs/en-US/secondary-storage.xml index e755b56734d..a254b1e2f6e 100644 --- a/docs/en-US/secondary-storage.xml +++ b/docs/en-US/secondary-storage.xml @@ -24,6 +24,7 @@
Secondary Storage - This section gives concepts and technical details about &PRODUCT; secondary storage. For information about how to install and configure secondary storage through the &PRODUCT; UI, see the Advanced Installation Guide. + This section gives concepts and technical details about &PRODUCT; secondary storage. For information about how to install and configure secondary storage through the &PRODUCT; UI, see the Advanced Installation Guide. +
diff --git a/docs/en-US/source-build.xml b/docs/en-US/source-build.xml new file mode 100644 index 00000000000..33218962174 --- /dev/null +++ b/docs/en-US/source-build.xml @@ -0,0 +1,49 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Building &PRODUCT; from Source + + Prior to the 4.0.0 incubating release, Ant was used to build &PRODUCT;. Starting with 4.0.0 a migration to Maven is underway. + The website and the wiki contain up to date information on the build procedure at: + + https://cwiki.apache.org/CLOUDSTACK/building-with-maven.html + http://incubator.apache.org/cloudstack/develop/environment.html + + + The overarching steps to build &PRODUCT; are:. + + Install the prerequisites and setup your environment + Understand that various Maven profiles and build targets + Deploy and test your build + If needed, learn how to build binaries + + + + Learning Maven is outside the scope of this documentation. + Go to the Maven website at http://maven.apache.org/guides/getting-started/index.html + + +
+ diff --git a/docs/en-US/tools.xml b/docs/en-US/tools.xml new file mode 100644 index 00000000000..66fe894e171 --- /dev/null +++ b/docs/en-US/tools.xml @@ -0,0 +1,29 @@ + + +%BOOK_ENTITIES; +]> + + + + + Tools + + + diff --git a/docs/en-US/troubleshooting.xml b/docs/en-US/troubleshooting.xml index dd736fe18e0..24ecab5489a 100644 --- a/docs/en-US/troubleshooting.xml +++ b/docs/en-US/troubleshooting.xml @@ -26,10 +26,10 @@ Troubleshooting - + - + - \ No newline at end of file + diff --git a/docs/en-US/troubleshooting-dataloss-on-exported-primary-storage.xml b/docs/en-US/troublesht-dataloss-on-exp-primary-storage.xml similarity index 100% rename from docs/en-US/troubleshooting-dataloss-on-exported-primary-storage.xml rename to docs/en-US/troublesht-dataloss-on-exp-primary-storage.xml diff --git a/docs/en-US/troubleshooting-maintenance-mode-not-working-on-vCenter.xml b/docs/en-US/troublesht-mtn-mode-not-working-on-vCenter.xml similarity index 100% rename from docs/en-US/troubleshooting-maintenance-mode-not-working-on-vCenter.xml rename to docs/en-US/troublesht-mtn-mode-not-working-on-vCenter.xml diff --git a/docs/en-US/usage-record-format.xml b/docs/en-US/usage-record-format.xml index d40bd63a91e..7f7db06df26 100644 --- a/docs/en-US/usage-record-format.xml +++ b/docs/en-US/usage-record-format.xml @@ -29,7 +29,7 @@ - +
diff --git a/docs/en-US/whats-new.xml b/docs/en-US/whats-new.xml index 5f13db3a854..77b3ec3df22 100644 --- a/docs/en-US/whats-new.xml +++ b/docs/en-US/whats-new.xml @@ -27,8 +27,8 @@ The following describes any new major features of each &PRODUCT; version as it applies to API usage.
What's New in the API for 4.0 - - + +
What's New in the API for 3.0 diff --git a/docs/publican-devguide.cfg b/docs/publican-devguide.cfg index 006c0d16d00..a8e28aea37b 100644 --- a/docs/publican-devguide.cfg +++ b/docs/publican-devguide.cfg @@ -20,7 +20,7 @@ xml_lang: en-US type: Book -docname: API_Developers_Guide +docname: Developers_Guide brand: cloudstack chunk_first: 1 chunk_section_depth: 1 diff --git a/patches/systemvm/debian/config/etc/init.d/cloud-early-config b/patches/systemvm/debian/config/etc/init.d/cloud-early-config index 11380b4105d..fe536cbb5a9 100755 --- a/patches/systemvm/debian/config/etc/init.d/cloud-early-config +++ b/patches/systemvm/debian/config/etc/init.d/cloud-early-config @@ -364,6 +364,11 @@ setup_common() { ping -n -c 3 $LOCAL_GW & sleep 3 pkill ping + #This code is added to address ARP issue by pinging MGMT_GW + MGMT_GW=$(echo $MGMTNET | awk -F "." '{print $1"."$2"."$3".1"}') + ping -n -c 3 $MGMT_GW & + sleep 3 + pkill ping fi } @@ -472,6 +477,7 @@ setup_redundant_router() { cp /root/redundant_router/check_bumpup.sh $rrouter_bin_path/ cp /root/redundant_router/disable_pubip.sh $rrouter_bin_path/ cp /root/redundant_router/checkrouter.sh.templ /opt/cloud/bin/checkrouter.sh + cp /root/redundant_router/services.sh $rrouter_bin_path/ sed -i "s/\[ROUTER_ID\]/$NAME/g" /etc/keepalived/keepalived.conf sed -i "s/\[ROUTER_IP\]/$GUEST_GW\/$GUEST_CIDR_SIZE/g" /etc/keepalived/keepalived.conf sed -i "s/\[BOARDCAST\]/$GUEST_BRD/g" /etc/keepalived/keepalived.conf diff --git a/patches/systemvm/debian/config/etc/sysctl.conf b/patches/systemvm/debian/config/etc/sysctl.conf index 7f945b0d4b1..961d471dfa9 100644 --- a/patches/systemvm/debian/config/etc/sysctl.conf +++ b/patches/systemvm/debian/config/etc/sysctl.conf @@ -8,7 +8,7 @@ net.ipv4.ip_forward = 1 # Controls source route verification -net.ipv4.conf.default.rp_filter = 1 +net.ipv4.conf.default.rp_filter = 0 # Do not accept source routing net.ipv4.conf.default.accept_source_route = 0 diff --git a/patches/systemvm/debian/config/opt/cloud/bin/ipassoc.sh b/patches/systemvm/debian/config/opt/cloud/bin/ipassoc.sh index c9a5e14e56b..5af5d9233a7 100755 --- a/patches/systemvm/debian/config/opt/cloud/bin/ipassoc.sh +++ b/patches/systemvm/debian/config/opt/cloud/bin/ipassoc.sh @@ -137,7 +137,7 @@ copy_routes_from_main() { ip_addr_add() { local dev="$1" local ip="$2" - sudo ip addr add dev $dev $ip > /dev/null + sudo ip addr add dev $dev $ip brd + > /dev/null } @@ -294,7 +294,7 @@ remove_an_ip () { then continue fi - sudo ip addr add dev $ethDev $ipMask + sudo ip addr add dev $ethDev $ipMask brd + done remove_routing $1 diff --git a/patches/systemvm/debian/config/opt/cloud/bin/passwd_server b/patches/systemvm/debian/config/opt/cloud/bin/passwd_server index 71349dd0336..0f4a7728874 100755 --- a/patches/systemvm/debian/config/opt/cloud/bin/passwd_server +++ b/patches/systemvm/debian/config/opt/cloud/bin/passwd_server @@ -19,5 +19,5 @@ ips=$(ip addr show dev eth0 | grep inet | grep eth0 | awk '{print $2}' ); echo $ips for ip in $ips; do addr=$(echo $ip | awk -F'/' '{print $1}') - /opt/cloud/bin/passwd_server_ip $addr & + /opt/cloud/bin/passwd_server_ip $addr >> /var/log/cloud.log 2>&1 & done; diff --git a/patches/systemvm/debian/config/root/edithosts.sh b/patches/systemvm/debian/config/root/edithosts.sh index 3c6102d61d5..37c75a53022 100755 --- a/patches/systemvm/debian/config/root/edithosts.sh +++ b/patches/systemvm/debian/config/root/edithosts.sh @@ -88,7 +88,7 @@ echo "0 $mac $ip $host *" >> $DHCP_LEASES #edit hosts file as well sed -i /"$ip "/d $HOSTS -sed -i /"$host "/d $HOSTS +sed -i /" $host$"/d $HOSTS echo "$ip $host" >> $HOSTS if [ "$dflt" != "" ] diff --git a/patches/systemvm/debian/config/root/redundant_router/disable_pubip.sh b/patches/systemvm/debian/config/root/redundant_router/disable_pubip.sh index af5edbfd2a1..ee4e894ba69 100644 --- a/patches/systemvm/debian/config/root/redundant_router/disable_pubip.sh +++ b/patches/systemvm/debian/config/root/redundant_router/disable_pubip.sh @@ -21,5 +21,3 @@ while read i do ifconfig $i down done < /tmp/iflist -service cloud-passwd-srvr stop -service dnsmasq stop diff --git a/patches/systemvm/debian/config/root/redundant_router/enable_pubip.sh.templ b/patches/systemvm/debian/config/root/redundant_router/enable_pubip.sh.templ index ccdef0b7ea6..0e42ec4968a 100644 --- a/patches/systemvm/debian/config/root/redundant_router/enable_pubip.sh.templ +++ b/patches/systemvm/debian/config/root/redundant_router/enable_pubip.sh.templ @@ -30,6 +30,4 @@ do ifconfig $i up fi done < /tmp/iflist -ip route add default via [GATEWAY] dev eth2 && \ -service cloud-passwd-srvr restart && \ -service dnsmasq restart +ip route add default via [GATEWAY] dev eth2 diff --git a/patches/systemvm/debian/config/root/redundant_router/master.sh.templ b/patches/systemvm/debian/config/root/redundant_router/master.sh.templ index 418fd5d83b8..11ca6284f65 100644 --- a/patches/systemvm/debian/config/root/redundant_router/master.sh.templ +++ b/patches/systemvm/debian/config/root/redundant_router/master.sh.templ @@ -28,12 +28,18 @@ fi echo To master called >> [RROUTER_LOG] [RROUTER_BIN_PATH]/enable_pubip.sh >> [RROUTER_LOG] 2>&1 ret=$? +if [ $ret -eq 0 ] +then + [RROUTER_BIN_PATH]/services.sh restart >> [RROUTER_LOG] 2>&1 + ret=$? +fi last_msg=`tail -n 1 [RROUTER_LOG]` echo Enable public ip returned $ret >> [RROUTER_LOG] if [ $ret -ne 0 ] then echo Fail to enable public ip! >> [RROUTER_LOG] [RROUTER_BIN_PATH]/disable_pubip.sh >> [RROUTER_LOG] 2>&1 + [RROUTER_BIN_PATH]/services.sh stop >> [RROUTER_LOG] 2>&1 service keepalived stop >> [RROUTER_LOG] 2>&1 service conntrackd stop >> [RROUTER_LOG] 2>&1 echo Status: FAULT \($last_msg\) >> [RROUTER_LOG] diff --git a/patches/systemvm/debian/config/root/redundant_router/services.sh b/patches/systemvm/debian/config/root/redundant_router/services.sh new file mode 100644 index 00000000000..b7ebeed264c --- /dev/null +++ b/patches/systemvm/debian/config/root/redundant_router/services.sh @@ -0,0 +1,68 @@ +#!/bin/bash +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +vpn_service() { + ps aux|grep ipsec | grep -v grep > /dev/null + no_vpn=$? + if [ $no_vpn -eq 1 ] + then + return 0 + fi + r=0 + case "$1" in + stop) + service ipsec stop && \ + service xl2tpd stop + r=$? + ;; + restart) + service ipsec restart && \ + service xl2tpd restart + r=$? + ;; + esac + return $r +} + +ret=0 +case "$1" in + start) + vpn_service restart && \ + service cloud-passwd-srvr start && \ + service dnsmasq start + ret=$? + ;; + stop) + vpn_service stop && \ + service cloud-passwd-srvr stop && \ + service dnsmasq stop + ret=$? + ;; + restart) + vpn_service restart && \ + service cloud-passwd-srvr restart && \ + service dnsmasq restart + ret=$? + ;; + *) + echo "Usage: services {start|stop|restart}" + exit 1 + ;; +esac + +exit $ret diff --git a/patches/systemvm/debian/config/root/savepassword.sh b/patches/systemvm/debian/config/root/savepassword.sh index 80a6928df0e..a096b862fce 100755 --- a/patches/systemvm/debian/config/root/savepassword.sh +++ b/patches/systemvm/debian/config/root/savepassword.sh @@ -24,7 +24,7 @@ source /root/func.sh -lock="biglock" +lock="passwdlock" locked=$(getLockFile $lock) if [ "$locked" != "1" ] then diff --git a/plugins/deployment-planners/user-concentrated-pod/build.xml b/plugins/deployment-planners/user-concentrated-pod/build.xml deleted file mode 100755 index d63f33476b3..00000000000 --- a/plugins/deployment-planners/user-concentrated-pod/build.xml +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/deployment-planners/user-dispersing/build.xml b/plugins/deployment-planners/user-dispersing/build.xml deleted file mode 100755 index ba72332586a..00000000000 --- a/plugins/deployment-planners/user-dispersing/build.xml +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/file-systems/netapp/build.xml b/plugins/file-systems/netapp/build.xml deleted file mode 100755 index 6326e144f6a..00000000000 --- a/plugins/file-systems/netapp/build.xml +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/host-allocators/random/build.xml b/plugins/host-allocators/random/build.xml deleted file mode 100755 index 6cb8fd8980e..00000000000 --- a/plugins/host-allocators/random/build.xml +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/hypervisors/kvm/build.xml b/plugins/hypervisors/kvm/build.xml deleted file mode 100755 index 9a572496fc3..00000000000 --- a/plugins/hypervisors/kvm/build.xml +++ /dev/null @@ -1,137 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index 41ee1dd4139..b52e2d8a0b0 100755 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -1104,8 +1104,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements String secondaryStorageUrl = cmd.getSecondaryStorageURL(); KVMStoragePool secondaryStoragePool = null; try { - KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(pool - .getUuid()); + KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool( + pool.getType(), + pool.getUuid()); String volumeName = UUID.randomUUID().toString(); if (copyToSecondary) { @@ -1114,20 +1115,21 @@ public class LibvirtComputingResource extends ServerResourceBase implements .getVolumePath()); String volumeDestPath = "/volumes/" + cmd.getVolumeId() + File.separator; - secondaryStoragePool = _storagePoolMgr - .getStoragePoolByURI(secondaryStorageUrl); + secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI( + secondaryStorageUrl); secondaryStoragePool.createFolder(volumeDestPath); secondaryStoragePool.delete(); - secondaryStoragePool = _storagePoolMgr - .getStoragePoolByURI(secondaryStorageUrl - + volumeDestPath); - _storagePoolMgr.copyPhysicalDisk(volume, destVolumeName, - secondaryStoragePool); + secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI( + secondaryStorageUrl + + volumeDestPath); + _storagePoolMgr.copyPhysicalDisk(volume, + destVolumeName,secondaryStoragePool); return new CopyVolumeAnswer(cmd, true, null, null, volumeName); } else { volumePath = "/volumes/" + cmd.getVolumeId() + File.separator; - secondaryStoragePool = _storagePoolMgr - .getStoragePoolByURI(secondaryStorageUrl + volumePath); + secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI( + secondaryStorageUrl + + volumePath); KVMPhysicalDisk volume = secondaryStoragePool .getPhysicalDisk(cmd.getVolumePath() + ".qcow2"); _storagePoolMgr.copyPhysicalDisk(volume, volumeName, @@ -1145,7 +1147,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements protected Answer execute(DeleteStoragePoolCommand cmd) { try { - _storagePoolMgr.deleteStoragePool(cmd.getPool().getUuid()); + _storagePoolMgr.deleteStoragePool(cmd.getPool().getType(), + cmd.getPool().getUuid()); return new Answer(cmd); } catch (CloudRuntimeException e) { return new Answer(cmd, false, e.toString()); @@ -1186,7 +1189,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements KVMPhysicalDisk vol = null; long disksize; try { - primaryPool = _storagePoolMgr.getStoragePool(pool.getUuid()); + primaryPool = _storagePoolMgr.getStoragePool(pool.getType(), + pool.getUuid()); disksize = dskch.getSize(); if (cmd.getTemplateUrl() != null) { @@ -1268,9 +1272,29 @@ public class LibvirtComputingResource extends ServerResourceBase implements VolumeTO vol = cmd.getVolume(); try { - KVMStoragePool pool = _storagePoolMgr.getStoragePool(vol - .getPoolUuid()); + KVMStoragePool pool = _storagePoolMgr.getStoragePool( + vol.getPoolType(), + vol.getPoolUuid()); pool.deletePhysicalDisk(vol.getPath()); + String vmName = cmd.getVmName(); + String poolPath = pool.getLocalPath(); + + /* if vol is a root disk for a system vm, try to remove accompanying patch disk as well + this is a bit tricky since the patchdisk is only a LibvirtComputingResource construct + and not tracked anywhere in cloudstack */ + if (vol.getType() == Volume.Type.ROOT && vmName.matches("^[rsv]-\\d+-.+$")) { + File patchVbd = new File(poolPath + File.separator + vmName + "-patchdisk"); + if(patchVbd.exists()){ + try { + _storagePoolMgr.deleteVbdByPath(vol.getPoolType(),patchVbd.getAbsolutePath()); + } catch(CloudRuntimeException e) { + s_logger.warn("unable to destroy patch disk '" + patchVbd.getAbsolutePath() + + "' while removing root disk for " + vmName + " : " + e); + } + } else { + s_logger.debug("file '" +patchVbd.getAbsolutePath()+ "' not found"); + } + } return new Answer(cmd, true, "Success"); } catch (CloudRuntimeException e) { @@ -1624,8 +1648,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements } } - KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd - .getPool().getUuid()); + KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool( + cmd.getPool().getType(), + cmd.getPool().getUuid()); if (primaryPool.getType() == StoragePoolType.RBD) { s_logger.debug("Snapshots are not supported on RBD volumes"); @@ -1702,8 +1727,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements try { Connect conn = LibvirtConnection.getConnection(); - secondaryStoragePool = _storagePoolMgr - .getStoragePoolByURI(secondaryStoragePoolUrl); + secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI( + secondaryStoragePoolUrl); String ssPmountPath = secondaryStoragePool.getLocalPath(); snapshotRelPath = File.separator + "snapshots" + File.separator @@ -1713,8 +1738,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements snapshotDestPath = ssPmountPath + File.separator + "snapshots" + File.separator + dcId + File.separator + accountId + File.separator + volumeId; - KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd - .getPrimaryStoragePoolNameLabel()); + KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool( + cmd.getPool().getType(), + cmd.getPrimaryStoragePoolNameLabel()); KVMPhysicalDisk snapshotDisk = primaryPool.getPhysicalDisk(cmd .getVolumePath()); Script command = new Script(_manageSnapshotPath, _cmdsTimeout, @@ -1741,8 +1767,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements } } - KVMStoragePool primaryStorage = _storagePoolMgr.getStoragePool(cmd - .getPool().getUuid()); + KVMStoragePool primaryStorage = _storagePoolMgr.getStoragePool( + cmd.getPool().getType(), + cmd.getPool().getUuid()); if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING && !primaryStorage.isExternalSnapshot()) { String vmUuid = vm.getUUIDString(); @@ -1826,7 +1853,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements KVMStoragePool secondaryStoragePool = null; try { secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(cmd - .getSecondaryStorageUrl()); + .getSecondaryStorageUrl()); String ssPmountPath = secondaryStoragePool.getLocalPath(); String snapshotDestPath = ssPmountPath + File.separator @@ -1856,15 +1883,16 @@ public class LibvirtComputingResource extends ServerResourceBase implements String snapshotPath = cmd.getSnapshotUuid(); int index = snapshotPath.lastIndexOf("/"); snapshotPath = snapshotPath.substring(0, index); - KVMStoragePool secondaryPool = _storagePoolMgr - .getStoragePoolByURI(cmd.getSecondaryStorageUrl() - + snapshotPath); + KVMStoragePool secondaryPool = _storagePoolMgr.getStoragePoolByURI( + cmd.getSecondaryStorageUrl() + + snapshotPath); KVMPhysicalDisk snapshot = secondaryPool.getPhysicalDisk(cmd .getSnapshotName()); String primaryUuid = cmd.getPrimaryStoragePoolNameLabel(); KVMStoragePool primaryPool = _storagePoolMgr - .getStoragePool(primaryUuid); + .getStoragePool(cmd.getPool().getType(), + primaryUuid); String volUuid = UUID.randomUUID().toString(); KVMPhysicalDisk disk = _storagePoolMgr.copyPhysicalDisk(snapshot, volUuid, primaryPool); @@ -1899,8 +1927,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements KVMPhysicalDisk snapshot = snapshotPool.getPhysicalDisk(cmd .getSnapshotName()); - secondaryPool = _storagePoolMgr.getStoragePoolByURI(cmd - .getSecondaryStorageUrl()); + secondaryPool = _storagePoolMgr.getStoragePoolByURI( + cmd.getSecondaryStorageUrl()); String templatePath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder; @@ -1949,8 +1977,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements protected GetStorageStatsAnswer execute(final GetStorageStatsCommand cmd) { try { - KVMStoragePool sp = _storagePoolMgr.getStoragePool(cmd - .getStorageId()); + KVMStoragePool sp = _storagePoolMgr.getStoragePool( + cmd.getPooltype(), + cmd.getStorageId()); return new GetStorageStatsAnswer(cmd, sp.getCapacity(), sp.getUsed()); } catch (CloudRuntimeException e) { @@ -1969,11 +1998,12 @@ public class LibvirtComputingResource extends ServerResourceBase implements + cmd.getTemplateId() + File.separator; String templateInstallFolder = "/template/tmpl/" + templateFolder; - secondaryStorage = _storagePoolMgr - .getStoragePoolByURI(secondaryStorageURL); + secondaryStorage = _storagePoolMgr.getStoragePoolByURI( + secondaryStorageURL); - KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd - .getPrimaryStoragePoolNameLabel()); + KVMStoragePool primary = _storagePoolMgr.getStoragePool( + cmd.getPool().getType(), + cmd.getPrimaryStoragePoolNameLabel()); KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath()); String tmpltPath = secondaryStorage.getLocalPath() + File.separator + templateInstallFolder; @@ -2095,8 +2125,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements } /* Copy volume to primary storage */ - KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd - .getPoolUuid()); + KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool( + cmd.getPool().getType(), + cmd.getPoolUuid()); KVMPhysicalDisk primaryVol = _storagePoolMgr.copyPhysicalDisk( tmplVol, UUID.randomUUID().toString(), primaryPool); @@ -2117,9 +2148,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements } protected Answer execute(ModifyStoragePoolCommand cmd) { + String poolType = cmd.getPool().getType().toString(); KVMStoragePool storagepool = _storagePoolMgr.createStoragePool(cmd - .getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool().getPort(), - cmd.getPool().getPath(), cmd.getPool().getUserInfo(), cmd.getPool().getType()); + .getPool().getUuid(), cmd.getPool().getHost(), + cmd.getPool().getPort(), cmd.getPool().getPath(), + cmd.getPool().getUserInfo(), cmd.getPool().getType()); if (storagepool == null) { return new Answer(cmd, false, " Failed to create storage pool"); } @@ -2257,8 +2290,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements private AttachVolumeAnswer execute(AttachVolumeCommand cmd) { try { Connect conn = LibvirtConnection.getConnection(); - KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd - .getPoolUuid()); + KVMStoragePool primary = _storagePoolMgr.getStoragePool( + cmd.getPooltype(), + cmd.getPoolUuid()); KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath()); attachOrDetachDisk(conn, cmd.getAttach(), cmd.getVmName(), disk, cmd.getDeviceId().intValue()); @@ -2651,12 +2685,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements if (disk.getDeviceType() == DiskDef.deviceType.CDROM && disk.getDiskPath() != null) { cleanupDisk(conn, disk); - } else if (disk.getDiskPath() != null - && disk.getDiskPath().contains(vmName + "-patchdisk") - && vmName.matches("^[rsv]-\\d+-VM$")) { - if (!_storagePoolMgr.deleteVbdByPath(disk.getDiskPath())) { - s_logger.warn("failed to delete patch disk " + disk.getDiskPath()); - } } } for (InterfaceDef iface: ifaces) { @@ -2911,8 +2939,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements int index = isoPath.lastIndexOf("/"); String path = isoPath.substring(0, index); String name = isoPath.substring(index + 1); - KVMStoragePool secondaryPool = _storagePoolMgr - .getStoragePoolByURI(path); + KVMStoragePool secondaryPool = _storagePoolMgr.getStoragePoolByURI( + path); KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name); return isoVol.getPath(); } else { @@ -2939,11 +2967,13 @@ public class LibvirtComputingResource extends ServerResourceBase implements int index = volPath.lastIndexOf("/"); String volDir = volPath.substring(0, index); String volName = volPath.substring(index + 1); - KVMStoragePool secondaryStorage = _storagePoolMgr - .getStoragePoolByURI(volDir); + KVMStoragePool secondaryStorage = _storagePoolMgr. + getStoragePoolByURI(volDir); physicalDisk = secondaryStorage.getPhysicalDisk(volName); } else if (volume.getType() != Volume.Type.ISO) { - pool = _storagePoolMgr.getStoragePool(volume.getPoolUuid()); + pool = _storagePoolMgr.getStoragePool( + volume.getPoolType(), + volume.getPoolUuid()); physicalDisk = pool.getPhysicalDisk(volume.getPath()); } @@ -3021,7 +3051,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements DiskDef rootDisk = disks.get(0); VolumeTO rootVol = getVolume(vmSpec, Volume.Type.ROOT); String patchName = vmName + "-patchdisk"; - KVMStoragePool pool = _storagePoolMgr.getStoragePool(rootVol.getPoolUuid()); + KVMStoragePool pool = _storagePoolMgr.getStoragePool( + rootVol.getPoolType(), + rootVol.getPoolUuid()); String patchDiskPath = pool.getLocalPath() + "/" + patchName; List phyDisks = pool.listPhysicalDisks(); @@ -3117,7 +3149,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements } try { - KVMStoragePool pool = _storagePoolMgr.getStoragePool(poolUuid); + //we use libvirt since we passed a libvirt connection to cleanupDisk + KVMStoragePool pool = _storagePoolMgr.getStoragePool(null, poolUuid); if (pool != null) { pool.delete(); } @@ -3135,8 +3168,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements int index = isoPath.lastIndexOf("/"); String path = isoPath.substring(0, index); String name = isoPath.substring(index + 1); - KVMStoragePool secondaryPool = _storagePoolMgr - .getStoragePoolByURI(path); + KVMStoragePool secondaryPool = _storagePoolMgr.getStoragePoolByURI( + path); KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name); isoPath = isoVol.getPath(); @@ -4403,4 +4436,5 @@ public class LibvirtComputingResource extends ServerResourceBase implements return new Answer(cmd, success, ""); } + } diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java index 2c0e0ac9b6f..ac611275e5a 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java @@ -16,8 +16,12 @@ // under the License. package com.cloud.hypervisor.kvm.storage; +import java.net.URI; +import java.net.URISyntaxException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.HashMap; +import java.util.UUID; import com.cloud.hypervisor.kvm.resource.KVMHABase; import com.cloud.hypervisor.kvm.resource.KVMHABase.PoolType; @@ -25,11 +29,22 @@ import com.cloud.hypervisor.kvm.resource.KVMHAMonitor; import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk.PhysicalDiskFormat; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StorageLayer; +import com.cloud.utils.exception.CloudRuntimeException; public class KVMStoragePoolManager { private StorageAdaptor _storageAdaptor; private KVMHAMonitor _haMonitor; private final Map _storagePools = new ConcurrentHashMap(); + private final Map _storageMapper = new HashMap(); + + private StorageAdaptor getStorageAdaptor(StoragePoolType type) { + StorageAdaptor adaptor = _storageMapper.get(type.toString()); + if (adaptor == null) { + // LibvirtStorageAdaptor is selected by default + adaptor = _storageMapper.get("libvirt"); + } + return adaptor; + } private void addStoragePool(String uuid) { synchronized (_storagePools) { @@ -42,20 +57,49 @@ public class KVMStoragePoolManager { public KVMStoragePoolManager(StorageLayer storagelayer, KVMHAMonitor monitor) { this._storageAdaptor = new LibvirtStorageAdaptor(storagelayer); this._haMonitor = monitor; + this._storageMapper.put("libvirt", new LibvirtStorageAdaptor(storagelayer)); + // add other storage adaptors here + // this._storageMapper.put("newadaptor", new NewStorageAdaptor(storagelayer)); } - public KVMStoragePool getStoragePool(String uuid) { - return this._storageAdaptor.getStoragePool(uuid); + public KVMStoragePool getStoragePool(StoragePoolType type, String uuid) { + StorageAdaptor adaptor = getStorageAdaptor(type); + return adaptor.getStoragePool(uuid); } public KVMStoragePool getStoragePoolByURI(String uri) { - return this._storageAdaptor.getStoragePoolByURI(uri); + URI storageUri = null; + + try { + storageUri = new URI(uri); + } catch (URISyntaxException e) { + throw new CloudRuntimeException(e.toString()); + } + + String sourcePath = null; + String uuid = null; + String sourceHost = ""; + StoragePoolType protocol = null; + if (storageUri.getScheme().equalsIgnoreCase("nfs")) { + sourcePath = storageUri.getPath(); + sourcePath = sourcePath.replace("//", "/"); + sourceHost = storageUri.getHost(); + uuid = UUID.nameUUIDFromBytes( + new String(sourceHost + sourcePath).getBytes()).toString(); + protocol = StoragePoolType.NetworkFilesystem; + } + + return createStoragePool(uuid, sourceHost, 0, sourcePath, "", protocol); } - public KVMStoragePool createStoragePool(String name, String host, int port, String path, - String userInfo, StoragePoolType type) { - KVMStoragePool pool = this._storageAdaptor.createStoragePool(name, + public KVMStoragePool createStoragePool( String name, String host, int port, + String path, String userInfo, + StoragePoolType type) { + StorageAdaptor adaptor = getStorageAdaptor(type); + KVMStoragePool pool = adaptor.createStoragePool(name, host, port, path, userInfo, type); + + // LibvirtStorageAdaptor-specific statement if (type == StoragePoolType.NetworkFilesystem) { KVMHABase.NfsStoragePool nfspool = new KVMHABase.NfsStoragePool( pool.getUuid(), host, path, pool.getLocalPath(), @@ -66,28 +110,33 @@ public class KVMStoragePoolManager { return pool; } - public boolean deleteStoragePool(String uuid) { + public boolean deleteStoragePool(StoragePoolType type, String uuid) { + StorageAdaptor adaptor = getStorageAdaptor(type); _haMonitor.removeStoragePool(uuid); - this._storageAdaptor.deleteStoragePool(uuid); + adaptor.deleteStoragePool(uuid); _storagePools.remove(uuid); return true; } - public boolean deleteVbdByPath(String diskPath) { - return this._storageAdaptor.deleteVbdByPath(diskPath); + public boolean deleteVbdByPath(StoragePoolType type, String diskPath) { + StorageAdaptor adaptor = getStorageAdaptor(type); + return adaptor.deleteVbdByPath(diskPath); } public KVMPhysicalDisk createDiskFromTemplate(KVMPhysicalDisk template, String name, KVMStoragePool destPool) { + StorageAdaptor adaptor = getStorageAdaptor(destPool.getType()); + + // LibvirtStorageAdaptor-specific statement if (destPool.getType() == StoragePoolType.RBD) { - return this._storageAdaptor.createDiskFromTemplate(template, name, + return adaptor.createDiskFromTemplate(template, name, KVMPhysicalDisk.PhysicalDiskFormat.RAW, template.getSize(), destPool); } else if (destPool.getType() == StoragePoolType.CLVM) { - return this._storageAdaptor.createDiskFromTemplate(template, name, + return adaptor.createDiskFromTemplate(template, name, KVMPhysicalDisk.PhysicalDiskFormat.RAW, template.getSize(), destPool); } else { - return this._storageAdaptor.createDiskFromTemplate(template, name, + return adaptor.createDiskFromTemplate(template, name, KVMPhysicalDisk.PhysicalDiskFormat.QCOW2, template.getSize(), destPool); } @@ -96,22 +145,22 @@ public class KVMStoragePoolManager { public KVMPhysicalDisk createTemplateFromDisk(KVMPhysicalDisk disk, String name, PhysicalDiskFormat format, long size, KVMStoragePool destPool) { - return this._storageAdaptor.createTemplateFromDisk(disk, name, format, + StorageAdaptor adaptor = getStorageAdaptor(destPool.getType()); + return adaptor.createTemplateFromDisk(disk, name, format, size, destPool); } public KVMPhysicalDisk copyPhysicalDisk(KVMPhysicalDisk disk, String name, KVMStoragePool destPool) { - return this._storageAdaptor.copyPhysicalDisk(disk, name, destPool); + StorageAdaptor adaptor = getStorageAdaptor(destPool.getType()); + return adaptor.copyPhysicalDisk(disk, name, destPool); } public KVMPhysicalDisk createDiskFromSnapshot(KVMPhysicalDisk snapshot, String snapshotName, String name, KVMStoragePool destPool) { - return this._storageAdaptor.createDiskFromSnapshot(snapshot, + StorageAdaptor adaptor = getStorageAdaptor(destPool.getType()); + return adaptor.createDiskFromSnapshot(snapshot, snapshotName, name, destPool); } - public KVMPhysicalDisk getPhysicalDiskFromUrl(String url) { - return this._storageAdaptor.getPhysicalDiskFromURI(url); - } } diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java index 6c55743696d..d350ef994fb 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java @@ -688,10 +688,16 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { PhysicalDiskFormat destFormat = newDisk.getFormat(); if ((srcPool.getType() != StoragePoolType.RBD) && (destPool.getType() != StoragePoolType.RBD)) { - Script.runSimpleBashScript("qemu-img convert -f " + sourceFormat - + " -O " + destFormat - + " " + sourcePath - + " " + destPath); + if (sourceFormat.equals(destFormat) && + Script.runSimpleBashScript("qemu-img info " + sourcePath + "|grep backing") == null) { + Script.runSimpleBashScript("cp -f " + sourcePath + " " + destPath); + + } else { + Script.runSimpleBashScript("qemu-img convert -f " + sourceFormat + + " -O " + destFormat + + " " + sourcePath + + " " + destPath); + } } else if ((srcPool.getType() != StoragePoolType.RBD) && (destPool.getType() == StoragePoolType.RBD)) { Script.runSimpleBashScript("qemu-img convert -f " + sourceFormat + " -O " + destFormat @@ -719,38 +725,6 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { return newDisk; } - @Override - public KVMStoragePool getStoragePoolByURI(String uri) { - URI storageUri = null; - - try { - storageUri = new URI(uri); - } catch (URISyntaxException e) { - throw new CloudRuntimeException(e.toString()); - } - - String sourcePath = null; - String uuid = null; - String sourceHost = ""; - StoragePoolType protocal = null; - if (storageUri.getScheme().equalsIgnoreCase("nfs")) { - sourcePath = storageUri.getPath(); - sourcePath = sourcePath.replace("//", "/"); - sourceHost = storageUri.getHost(); - uuid = UUID.nameUUIDFromBytes( - new String(sourceHost + sourcePath).getBytes()).toString(); - protocal = StoragePoolType.NetworkFilesystem; - } - - return createStoragePool(uuid, sourceHost, 0, sourcePath, "", protocal); - } - - @Override - public KVMPhysicalDisk getPhysicalDiskFromURI(String uri) { - // TODO Auto-generated method stub - return null; - } - @Override public KVMPhysicalDisk createDiskFromSnapshot(KVMPhysicalDisk snapshot, String snapshotName, String name, KVMStoragePool destPool) { diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/StorageAdaptor.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/StorageAdaptor.java index ef1e7c9302a..79c3b926b33 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/StorageAdaptor.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/storage/StorageAdaptor.java @@ -55,10 +55,6 @@ public interface StorageAdaptor { public KVMPhysicalDisk createDiskFromSnapshot(KVMPhysicalDisk snapshot, String snapshotName, String name, KVMStoragePool destPool); - public KVMStoragePool getStoragePoolByURI(String uri); - - public KVMPhysicalDisk getPhysicalDiskFromURI(String uri); - public boolean refresh(KVMStoragePool pool); public boolean deleteStoragePool(KVMStoragePool pool); diff --git a/plugins/hypervisors/ovm/build.xml b/plugins/hypervisors/ovm/build.xml deleted file mode 100755 index 8113d725daa..00000000000 --- a/plugins/hypervisors/ovm/build.xml +++ /dev/null @@ -1,136 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/hypervisors/simulator/pom.xml b/plugins/hypervisors/simulator/pom.xml new file mode 100644 index 00000000000..15b37900590 --- /dev/null +++ b/plugins/hypervisors/simulator/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + org.apache.cloudstack + cloudstack-plugins + 4.1.0-SNAPSHOT + ../../pom.xml + + org.apache.cloudstack + cloud-plugin-hypervisor-simulator + 4.1.0-SNAPSHOT + Apache CloudStack Plugin - Hypervisor Simulator + Simulator Hypervisor for Cloudstack + + install + src + test + + + + org.apache.cloudstack + cloud-utils + ${project.version} + + + \ No newline at end of file diff --git a/plugins/hypervisors/simulator/resources/components-simulator.xml b/plugins/hypervisors/simulator/resources/components-simulator.xml new file mode 100644 index 00000000000..4629acc866a --- /dev/null +++ b/plugins/hypervisors/simulator/resources/components-simulator.xml @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/agent-simulator/src/com/cloud/agent/MetricsCollector.java b/plugins/hypervisors/simulator/src/com/cloud/agent/MetricsCollector.java similarity index 89% rename from agent-simulator/src/com/cloud/agent/MetricsCollector.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/MetricsCollector.java index 7d86a0c8e3e..fd611f83b9f 100644 --- a/agent-simulator/src/com/cloud/agent/MetricsCollector.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/MetricsCollector.java @@ -30,43 +30,43 @@ import com.cloud.utils.concurrency.NamedThreadFactory; public class MetricsCollector { private static final Logger s_logger = Logger.getLogger(MetricsCollector.class); - + private final Set vmNames = new HashSet(); private final Set newVMnames = new HashSet(); private final Map metricsMap = new HashMap(); - + private final transient ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("Metrics")); private Set _currentVms; - + public MetricsCollector(Set currentVms) { _currentVms = currentVms; getAllVMNames(); } - + public MetricsCollector() { - + } - + public synchronized void getAllVMNames() { Set currentVMs = _currentVms; - + newVMnames.clear(); newVMnames.addAll(currentVMs); newVMnames.removeAll(vmNames); //leave only new vms - + vmNames.removeAll(currentVMs); //old vms - current vms --> leave non-running vms; for (String vm: vmNames) { - removeVM(vm); + removeVM(vm); } - + vmNames.clear(); vmNames.addAll(currentVMs); } - + public synchronized void submitMetricsJobs() { s_logger.debug("Submit Metric Jobs called"); - + for (String vm : newVMnames) { MockVmMetrics task = new MockVmMetrics(vm); if (!metricsMap.containsKey(vm)) { @@ -77,30 +77,30 @@ public class MetricsCollector { } newVMnames.clear(); } - + public synchronized void addVM(String vmName) { newVMnames.add(vmName); s_logger.debug("Added vm name= " + vmName); } - + public synchronized void removeVM(String vmName) { newVMnames.remove(vmName); vmNames.remove(vmName); MockVmMetrics task = metricsMap.get(vmName); - if (task != null) { - task.stop(); - boolean r1= task.getFuture().cancel(false); - metricsMap.remove(vmName); - s_logger.debug("removeVM: cancel returned " + r1 + " for VM " + vmName); - } else { - s_logger.warn("removeVM called for nonexistent VM " + vmName); - } + if (task != null) { + task.stop(); + boolean r1= task.getFuture().cancel(false); + metricsMap.remove(vmName); + s_logger.debug("removeVM: cancel returned " + r1 + " for VM " + vmName); + } else { + s_logger.warn("removeVM called for nonexistent VM " + vmName); } - + } + public synchronized Set getVMNames() { return vmNames; } - + public synchronized Map getMetricsMap() { return metricsMap; } diff --git a/agent-simulator/src/com/cloud/agent/MockVmMetrics.java b/plugins/hypervisors/simulator/src/com/cloud/agent/MockVmMetrics.java similarity index 96% rename from agent-simulator/src/com/cloud/agent/MockVmMetrics.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/MockVmMetrics.java index f106f367a9c..30b99e753a1 100644 --- a/agent-simulator/src/com/cloud/agent/MockVmMetrics.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/MockVmMetrics.java @@ -25,52 +25,52 @@ import org.apache.log4j.Logger; public class MockVmMetrics implements Runnable { private static final Logger s_logger = Logger.getLogger(MockVmMetrics.class); - + private String vmName; - + public final int MAX_INTERFACES=1; - + public final int MAX_DISKS=8; - + //the last calculated traffic speed (transmit) per interface private Map netTxKBps = new HashMap(); - + //the last calculated traffic speed (receive) per interface private Map netRxKBps = new HashMap(); - + //the last calculated disk write speed per disk (Bytes Per Second) private Map diskWriteKBytesPerSec = new HashMap(); - + //the last calculated disk read speed per disk (Bytes Per Second) private Map diskReadKBytesPerSec = new HashMap(); - + //Total Bytes Transmitted on network interfaces private Map netTxTotalBytes = new HashMap(); - + //Total Bytes Received on network interfaces private Map netRxTotalBytes = new HashMap(); - + //Total Bytes read per disk private Map diskReadTotalBytes = new HashMap(); //Total Bytes written per disk private Map diskWriteTotalBytes = new HashMap(); - + //CPU time in seconds private Double cpuSeconds = new Double(0.0); - + //CPU percentage private Float cpuPercent = new Float(0.0); - + private Map diskMap = new HashMap(); private Map vifMap = new HashMap(); - + private Map diskStatTimestamp = new HashMap(); private Map netStatTimestamp = new HashMap(); - + private long cpuStatTimestamp = 0L; - + private ScheduledFuture future; private boolean stopped = false; private Random randSeed = new Random(); @@ -80,44 +80,44 @@ public class MockVmMetrics implements Runnable { vifMap.put("eth0", "eth0"); vifMap.put("eth1", "eth1"); vifMap.put("eth2", "eth2"); - + Long networkStart = 0L; netTxTotalBytes.put("eth0", networkStart); netRxTotalBytes.put("eth0", networkStart); - + netTxTotalBytes.put("eth1", networkStart); netRxTotalBytes.put("eth1", networkStart); - + netTxTotalBytes.put("eth2", networkStart); - netRxTotalBytes.put("eth2", networkStart); + netRxTotalBytes.put("eth2", networkStart); } - + private int getIncrementor() { return randSeed.nextInt(100); } - + @Override public void run() { if(s_logger.isDebugEnabled()) { s_logger.debug("Generating MockVM metrics"); } for (Map.Entry entry : netRxTotalBytes.entrySet()) { - entry.setValue(entry.getValue() + getIncrementor()); + entry.setValue(entry.getValue() + getIncrementor()); } - + for (Map.Entry entry : netTxTotalBytes.entrySet()) { entry.setValue(entry.getValue() + getIncrementor()); } } - + public String getVmName() { return vmName; } - + public Map getNetTxKBps() { return netTxKBps; } - + public Map getNetRxKBps() { return netRxKBps; } @@ -125,11 +125,11 @@ public class MockVmMetrics implements Runnable { public Map getDiskWriteBytesPerSec() { return diskWriteKBytesPerSec; } - + public Map getDiskReadBytesPerSec() { return diskReadKBytesPerSec; } - + public Map getNetTxTotalBytes() { return netTxTotalBytes; } @@ -137,7 +137,7 @@ public class MockVmMetrics implements Runnable { public Map getNetRxTotalBytes() { return netRxTotalBytes; } - + public Map getDiskReadTotalBytes() { return diskReadTotalBytes; } @@ -145,7 +145,7 @@ public class MockVmMetrics implements Runnable { public Map getDiskWriteTotalBytes() { return diskWriteTotalBytes; } - + public Double getNetTxKBps(String intf) { return netTxKBps.get(intf); } @@ -153,7 +153,7 @@ public class MockVmMetrics implements Runnable { public Double getNetRxKBps(String intf) { return netRxKBps.get(intf); } - + public Double getDiskWriteKBytesPerSec(String disk) { return diskWriteKBytesPerSec.get(disk); } @@ -161,7 +161,7 @@ public class MockVmMetrics implements Runnable { public Double getDiskReadKBytesPerSec(String disk) { return diskReadKBytesPerSec.get(disk); } - + public Long getNetTxTotalBytes(String intf) { return netTxTotalBytes.get(intf); } @@ -169,7 +169,7 @@ public class MockVmMetrics implements Runnable { public Long getNetRxTotalBytes(String intf) { return netRxTotalBytes.get(intf); } - + public Long getDiskReadTotalBytes(String disk) { return diskReadTotalBytes.get(disk); } @@ -177,7 +177,7 @@ public class MockVmMetrics implements Runnable { public Long getDiskWriteTotalBytes(String disk) { return diskWriteTotalBytes.get(disk); } - + public Double getCpuSeconds() { return cpuSeconds; } @@ -189,7 +189,7 @@ public class MockVmMetrics implements Runnable { public Float getCpuPercent() { return cpuPercent; } - + public void setFuture(ScheduledFuture sf) { this.future = sf; } @@ -197,9 +197,8 @@ public class MockVmMetrics implements Runnable { public ScheduledFuture getFuture() { return future; } - + public void stop() { this.stopped = true; } } - diff --git a/agent-simulator/src/com/cloud/agent/MultiCaster.java b/plugins/hypervisors/simulator/src/com/cloud/agent/MultiCaster.java similarity index 94% rename from agent-simulator/src/com/cloud/agent/MultiCaster.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/MultiCaster.java index 9c98ef651be..7d38baf0e68 100644 --- a/agent-simulator/src/com/cloud/agent/MultiCaster.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/MultiCaster.java @@ -30,49 +30,49 @@ import org.apache.log4j.Logger; public class MultiCaster implements Runnable { private static final Logger s_logger = Logger.getLogger(MultiCaster.class); - + public final int MAX_PACKET_SIZE = 8096; - + private List listeners; private DatagramSocket socket; private byte[] recvBuffer; - + private Thread driver; private volatile boolean stopRequested = false; - + public MultiCaster() { listeners = new ArrayList(); recvBuffer = new byte[MAX_PACKET_SIZE]; } - + public void addListener(MultiCasterListener listener) { synchronized(listeners) { listeners.add(listener); } } - + public void removeListener(MultiCasterListener listener) { synchronized(listeners) { listeners.remove(listener); } } - - public void cast(byte[] buf, int off, int len, + + public void cast(byte[] buf, int off, int len, InetAddress toAddress, int nToPort) throws IOException { - + if(socket == null) throw new IOException("multi caster is not started"); - + if(len >= MAX_PACKET_SIZE) throw new IOException("packet size exceeds limit of " + MAX_PACKET_SIZE); - - DatagramPacket packet = new DatagramPacket(buf, off, + + DatagramPacket packet = new DatagramPacket(buf, off, len, toAddress, nToPort); socket.send(packet); } - - public void start(String strOutboundAddress, + + public void start(String strOutboundAddress, String strClusterAddress, int nPort) throws SocketException { assert(socket == null); @@ -82,22 +82,22 @@ public class MultiCaster implements Runnable { } catch(IOException e) { s_logger.error("Unexpected exception " , e); } - + if(addr != null && addr.isMulticastAddress()) { try { socket = new MulticastSocket(nPort); socket.setReuseAddress(true); - + if(s_logger.isInfoEnabled()) s_logger.info("Join multicast group : " + addr); - + ((MulticastSocket)socket).joinGroup(addr); ((MulticastSocket)socket).setTimeToLive(1); - + if(strOutboundAddress != null) { if(s_logger.isInfoEnabled()) s_logger.info("set outgoing interface to : " + strOutboundAddress); - + InetAddress ia = InetAddress.getByName(strOutboundAddress); NetworkInterface ni = NetworkInterface.getByInetAddress(ia); ((MulticastSocket)socket).setNetworkInterface(ni); @@ -109,16 +109,16 @@ public class MultiCaster implements Runnable { socket = new DatagramSocket(nPort); socket.setReuseAddress(true); } - + driver = new Thread(this, "Multi-caster"); driver.setDaemon(true); driver.start(); } - + public void stop() { if(socket != null) { stopRequested = true; - + socket.close(); if(driver != null) { try { @@ -128,17 +128,17 @@ public class MultiCaster implements Runnable { driver = null; } } - + socket = null; stopRequested = false; } - + public void run() { while(!stopRequested) { try { DatagramPacket packet = new DatagramPacket(recvBuffer, recvBuffer.length); socket.receive(packet); - + for(Object listener : listeners.toArray()) { ((MultiCasterListener)listener).onMultiCasting(packet.getData(), packet.getOffset(), packet.getLength(), packet.getAddress()); diff --git a/agent-simulator/src/com/cloud/agent/MultiCasterListener.java b/plugins/hypervisors/simulator/src/com/cloud/agent/MultiCasterListener.java similarity index 100% rename from agent-simulator/src/com/cloud/agent/MultiCasterListener.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/MultiCasterListener.java diff --git a/agent-simulator/src/com/cloud/agent/SimulatorCmd.java b/plugins/hypervisors/simulator/src/com/cloud/agent/SimulatorCmd.java similarity index 96% rename from agent-simulator/src/com/cloud/agent/SimulatorCmd.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/SimulatorCmd.java index 342bfd2491e..caed518dd78 100644 --- a/agent-simulator/src/com/cloud/agent/SimulatorCmd.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/SimulatorCmd.java @@ -20,17 +20,17 @@ import java.io.Serializable; public class SimulatorCmd implements Serializable { private static final long serialVersionUID = 1L; - + private String testCase = "DEFAULT"; - + public SimulatorCmd(String testCase) { - this.testCase = testCase; + this.testCase = testCase; } - + public String getTestCase() { return testCase; } - + public void setTestCase(String testCase) { this.testCase = testCase; } diff --git a/agent-simulator/src/com/cloud/agent/SimulatorMigrateVmCmd.java b/plugins/hypervisors/simulator/src/com/cloud/agent/SimulatorMigrateVmCmd.java similarity index 99% rename from agent-simulator/src/com/cloud/agent/SimulatorMigrateVmCmd.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/SimulatorMigrateVmCmd.java index f86b16ee7d4..6a2190d696a 100644 --- a/agent-simulator/src/com/cloud/agent/SimulatorMigrateVmCmd.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/SimulatorMigrateVmCmd.java @@ -21,12 +21,12 @@ public class SimulatorMigrateVmCmd extends SimulatorCmd { private static final long serialVersionUID = 1L; private String destIp; - + private String vmName; private long ramSize; private int cpuCount; private int utilization; - + public SimulatorMigrateVmCmd(String testCase) { super(testCase); } @@ -38,7 +38,7 @@ public class SimulatorMigrateVmCmd extends SimulatorCmd { public void setDestIp(String destIp) { this.destIp = destIp; } - + public String getVmName() { return vmName; } @@ -70,14 +70,14 @@ public class SimulatorMigrateVmCmd extends SimulatorCmd { public void setUtilization(int utilization) { this.utilization = utilization; } - + public String toString() { StringBuffer sb = new StringBuffer(); sb.append("SimulatorMigrateVmCmd {").append("vm: ").append(getVmName()); sb.append(", destIp: ").append(getDestIp()).append(", ramSize: ").append(getRamSize()); sb.append(", cpuCount: ").append(getCpuCount()).append(", utilization: ").append(getUtilization()); sb.append("}"); - + return sb.toString(); } } diff --git a/agent-simulator/src/com/cloud/agent/manager/MockAgentManager.java b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockAgentManager.java similarity index 97% rename from agent-simulator/src/com/cloud/agent/manager/MockAgentManager.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockAgentManager.java index 7db5b20f55c..2bb1205b115 100644 --- a/agent-simulator/src/com/cloud/agent/manager/MockAgentManager.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockAgentManager.java @@ -56,8 +56,6 @@ public interface MockAgentManager extends Manager { Answer pingTest(PingTestCommand cmd); - Answer prepareForMigrate(PrepareForMigrationCommand cmd); - MockHost getHost(String guid); Answer maintain(MaintainCommand cmd); diff --git a/agent-simulator/src/com/cloud/agent/manager/MockAgentManagerImpl.java b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockAgentManagerImpl.java similarity index 98% rename from agent-simulator/src/com/cloud/agent/manager/MockAgentManagerImpl.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockAgentManagerImpl.java index cb992979e07..f6bc8fc7fee 100755 --- a/agent-simulator/src/com/cloud/agent/manager/MockAgentManagerImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockAgentManagerImpl.java @@ -429,15 +429,6 @@ public class MockAgentManagerImpl implements MockAgentManager { return new Answer(cmd); } - @Override - public PrepareForMigrationAnswer prepareForMigrate(PrepareForMigrationCommand cmd) { - VirtualMachineTO vm = cmd.getVirtualMachine(); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Preparing host for migrating " + vm); - } - return new PrepareForMigrationAnswer(cmd); - } - @Override public boolean start() { return true; diff --git a/agent-simulator/src/com/cloud/agent/manager/MockStorageManager.java b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockStorageManager.java similarity index 99% rename from agent-simulator/src/com/cloud/agent/manager/MockStorageManager.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockStorageManager.java index 3b7a286c5e1..fc8aacc6ec3 100644 --- a/agent-simulator/src/com/cloud/agent/manager/MockStorageManager.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockStorageManager.java @@ -51,17 +51,17 @@ import com.cloud.utils.component.Manager; public interface MockStorageManager extends Manager { public static final long DEFAULT_HOST_STORAGE_SIZE = 1 * 1024 * 1024 * 1024 * 1024L; //1T public static final long DEFAULT_TEMPLATE_SIZE = 1 * 1000 * 1000 * 1000L; //1G - + public PrimaryStorageDownloadAnswer primaryStorageDownload(PrimaryStorageDownloadCommand cmd); - + public CreateAnswer createVolume(CreateCommand cmd); public AttachVolumeAnswer AttachVolume(AttachVolumeCommand cmd); public Answer AttachIso(AttachIsoCommand cmd); - + public Answer DeleteStoragePool(DeleteStoragePoolCommand cmd); public Answer ModifyStoragePool(ModifyStoragePoolCommand cmd); public Answer CreateStoragePool(CreateStoragePoolCommand cmd); - + public Answer SecStorageSetup(SecStorageSetupCommand cmd); public Answer ListTemplates(ListTemplateCommand cmd); public Answer Destroy(DestroyCommand cmd); @@ -74,7 +74,7 @@ public interface MockStorageManager extends Manager { public Answer CreateVolumeFromSnapshot(CreateVolumeFromSnapshotCommand cmd); public Answer DeleteTemplate(DeleteTemplateCommand cmd); public Answer SecStorageVMSetup(SecStorageVMSetupCommand cmd); - + public void preinstallTemplates(String url, long zoneId); StoragePoolInfo getLocalStorage(String hostGuid); diff --git a/agent-simulator/src/com/cloud/agent/manager/MockStorageManagerImpl.java b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockStorageManagerImpl.java similarity index 99% rename from agent-simulator/src/com/cloud/agent/manager/MockStorageManagerImpl.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockStorageManagerImpl.java index cc15b206738..9bf4192c4bd 100644 --- a/agent-simulator/src/com/cloud/agent/manager/MockStorageManagerImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockStorageManagerImpl.java @@ -703,7 +703,7 @@ public class MockStorageManagerImpl implements MockStorageManager { txn = Transaction.open(Transaction.CLOUD_DB); txn.close(); } - + MockVolumeVO newsnapshot = new MockVolumeVO(); String name = UUID.randomUUID().toString(); newsnapshot.setName(name); @@ -953,7 +953,7 @@ public class MockStorageManagerImpl implements MockStorageManager { @Override public StoragePoolInfo getLocalStorage(String hostGuid) { Transaction txn = Transaction.open(Transaction.SIMULATOR_DB); - MockHost host = null; + MockHost host = null; MockStoragePoolVO storagePool = null; try { txn.start(); @@ -968,7 +968,7 @@ public class MockStorageManagerImpl implements MockStorageManager { txn = Transaction.open(Transaction.CLOUD_DB); txn.close(); } - + if (storagePool == null) { String uuid = UUID.randomUUID().toString(); storagePool = new MockStoragePoolVO(); @@ -998,7 +998,7 @@ public class MockStorageManagerImpl implements MockStorageManager { @Override public StoragePoolInfo getLocalStorage(String hostGuid, Long storageSize) { Transaction txn = Transaction.open(Transaction.SIMULATOR_DB); - MockHost host = null; + MockHost host = null; try { txn.start(); host = _mockHostDao.findByGuid(hostGuid); diff --git a/agent-simulator/src/com/cloud/agent/manager/MockVmManager.java b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockVmManager.java similarity index 97% rename from agent-simulator/src/com/cloud/agent/manager/MockVmManager.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockVmManager.java index 07cf584883e..117e2f6374f 100644 --- a/agent-simulator/src/com/cloud/agent/manager/MockVmManager.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockVmManager.java @@ -40,7 +40,7 @@ import com.cloud.vm.VirtualMachine.State; public interface MockVmManager extends Manager { public Answer stopVM(StopCommand cmd); public Answer rebootVM(RebootCommand cmd); - + public Answer checkVmState(CheckVirtualMachineCommand cmd); public Map getVmStates(String hostGuid); public Answer getVncPort(GetVncPortCommand cmd); @@ -49,31 +49,32 @@ public interface MockVmManager extends Manager { Answer getVmStats(GetVmStatsCommand cmd); public CheckSshAnswer checkSshCommand(CheckSshCommand cmd); - + Answer SetStaticNatRules(SetStaticNatRulesCommand cmd); - + Answer SetPortForwardingRules(SetPortForwardingRulesCommand cmd); Answer SetFirewallRules(SetFirewallRulesCommand cmd); - + Answer getNetworkUsage(NetworkUsageCommand cmd); - + Answer IpAssoc(IpAssocCommand cmd); Answer LoadBalancerConfig(LoadBalancerConfigCommand cmd); - + Answer AddDhcpEntry(DhcpEntryCommand cmd); - + Answer setVmData(VmDataCommand cmd); Answer CleanupNetworkRules(CleanupNetworkRulesCmd cmd, SimulatorInfo info); - + Answer CheckConsoleProxyLoad(CheckConsoleProxyLoadCommand cmd); Answer WatchConsoleProxyLoad(WatchConsoleProxyLoadCommand cmd); - + Answer SavePassword(SavePasswordCommand cmd); HashMap> syncNetworkGroups(SimulatorInfo info); SecurityGroupRuleAnswer AddSecurityGroupRules(SecurityGroupRulesCmd cmd, SimulatorInfo info); MigrateAnswer Migrate(MigrateCommand cmd, SimulatorInfo info); + PrepareForMigrationAnswer prepareForMigrate(PrepareForMigrationCommand cmd); GetDomRVersionAnswer getDomRVersion(GetDomRVersionCmd cmd); Map getVms(String hostGuid); diff --git a/agent-simulator/src/com/cloud/agent/manager/MockVmManagerImpl.java b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockVmManagerImpl.java similarity index 88% rename from agent-simulator/src/com/cloud/agent/manager/MockVmManagerImpl.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockVmManagerImpl.java index 78881f2fc3a..40cd80acf8e 100644 --- a/agent-simulator/src/com/cloud/agent/manager/MockVmManagerImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockVmManagerImpl.java @@ -60,20 +60,20 @@ public class MockVmManagerImpl implements MockVmManager { @Inject MockHostDao _mockHostDao = null; @Inject MockSecurityRulesDao _mockSecurityDao = null; private Map>> _securityRules = new ConcurrentHashMap>>(); - + public MockVmManagerImpl() { } - + @Override public boolean configure(String name, Map params) throws ConfigurationException { - + return true; } - + public String startVM(String vmName, NicTO[] nics, - int cpuHz, long ramSize, - String bootArgs, String hostGuid) { + int cpuHz, long ramSize, + String bootArgs, String hostGuid) { Transaction txn = Transaction.open(Transaction.SIMULATOR_DB); MockHost host = null; @@ -95,7 +95,7 @@ public class MockVmManagerImpl implements MockVmManager { txn = Transaction.open(Transaction.CLOUD_DB); txn.close(); } - + if(vm == null) { int vncPort = 0; if(vncPort < 0) @@ -107,14 +107,15 @@ public class MockVmManagerImpl implements MockVmManager { vm.setName(vmName); vm.setVncPort(vncPort); vm.setHostId(host.getId()); + vm.setBootargs(bootArgs); if(vmName.startsWith("s-")) { - vm.setType("SecondaryStorageVm"); + vm.setType("SecondaryStorageVm"); } else if (vmName.startsWith("v-")) { - vm.setType("ConsoleProxy"); + vm.setType("ConsoleProxy"); } else if (vmName.startsWith("r-")) { - vm.setType("DomainRouter"); + vm.setType("DomainRouter"); } else if (vmName.startsWith("i-")) { - vm.setType("User"); + vm.setType("User"); } txn = Transaction.open(Transaction.SIMULATOR_DB); try { @@ -133,18 +134,18 @@ public class MockVmManagerImpl implements MockVmManager { if(vm.getState() == State.Stopped) { vm.setState(State.Running); txn = Transaction.open(Transaction.SIMULATOR_DB); - try { - txn.start(); - _mockVmDao.update(vm.getId(), (MockVMVO)vm); - txn.commit(); - } catch (Exception ex) { - txn.rollback(); - throw new CloudRuntimeException("unable to update vm " + vm.getName(), ex); - } finally { - txn.close(); + try { + txn.start(); + _mockVmDao.update(vm.getId(), (MockVMVO)vm); + txn.commit(); + } catch (Exception ex) { + txn.rollback(); + throw new CloudRuntimeException("unable to update vm " + vm.getName(), ex); + } finally { + txn.close(); txn = Transaction.open(Transaction.CLOUD_DB); txn.close(); - } + } } } @@ -212,7 +213,7 @@ public class MockVmManagerImpl implements MockVmManager { } return true; } - + @Override public Map getVms(String hostGuid) { Transaction txn = Transaction.open(Transaction.SIMULATOR_DB); @@ -238,15 +239,16 @@ public class MockVmManagerImpl implements MockVmManager { @Override public CheckRouterAnswer checkRouter(CheckRouterCommand cmd) { String router_name = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - int router_id = Integer.parseInt(router_name.split("-")[1]); - if (router_id % 2 == 0) { - s_logger.debug("Found even routerId, making it MASTER in RvR"); + MockVm vm = _mockVmDao.findByVmName(router_name); + String args = vm.getBootargs(); + if (args.indexOf("router_pr=100") > 0) { + s_logger.debug("Router priority is for MASTER"); CheckRouterAnswer ans = new CheckRouterAnswer(cmd, "Status: MASTER & Bumped: NO", true); ans.setState(VirtualRouter.RedundantState.MASTER); return ans; } else { - s_logger.debug("Found odd routerId, making it BACKUP in RvR"); - CheckRouterAnswer ans = new CheckRouterAnswer(cmd, "Status: MASTER & Bumped: NO", true); + s_logger.debug("Router priority is for BACKUP"); + CheckRouterAnswer ans = new CheckRouterAnswer(cmd, "Status: BACKUP & Bumped: NO", true); ans.setState(VirtualRouter.RedundantState.BACKUP); return ans; } @@ -255,13 +257,13 @@ public class MockVmManagerImpl implements MockVmManager { @Override public Answer bumpPriority(BumpUpPriorityCommand cmd) { String router_name = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - int router_id = Integer.parseInt(router_name.split("-")[1]); - if (router_id % 2 == 0) { - return new Answer(cmd, true, "Status: MASTER & Bumped: YES"); - } else { + MockVm vm = _mockVmDao.findByVmName(router_name); + String args = vm.getBootargs(); + if (args.indexOf("router_pr=100") > 0) { return new Answer(cmd, true, "Status: BACKUP & Bumped: YES"); + } else { + return new Answer(cmd, true, "Status: MASTER & Bumped: YES"); } - } @Override @@ -303,8 +305,8 @@ public class MockVmManagerImpl implements MockVmManager { @Override public String getName() { return this.getClass().getSimpleName(); - } - + } + @Override public Answer getVmStats(GetVmStatsCommand cmd) { HashMap vmStatsNameMap = new HashMap(); @@ -370,9 +372,9 @@ public class MockVmManagerImpl implements MockVmManager { @Override public Answer SetFirewallRules(SetFirewallRulesCommand cmd) { - return new Answer(cmd); + return new Answer(cmd); } - + @Override public NetworkUsageAnswer getNetworkUsage(NetworkUsageCommand cmd) { @@ -388,8 +390,12 @@ public class MockVmManagerImpl implements MockVmManager { String destGuid = cmd.getHostGuid(); MockVMVO vm = _mockVmDao.findByVmNameAndHost(vmName, info.getHostUuid()); if (vm == null) { - return new MigrateAnswer(cmd, false, "can;t find vm:" + vmName + " on host:" + info.getHostUuid(), null); - } + return new MigrateAnswer(cmd, false, "can't find vm:" + vmName + " on host:" + info.getHostUuid(), null); + } else { + if (vm.getState() == State.Migrating) { + vm.setState(State.Running); + } + } MockHost destHost = _mockHostDao.findByGuid(destGuid); if (destHost == null) { @@ -409,6 +415,27 @@ public class MockVmManagerImpl implements MockVmManager { } } + @Override + public PrepareForMigrationAnswer prepareForMigrate(PrepareForMigrationCommand cmd) { + Transaction txn = Transaction.open(Transaction.SIMULATOR_DB); + VirtualMachineTO vmTo = cmd.getVirtualMachine(); + try { + txn.start(); + MockVMVO vm = _mockVmDao.findById(vmTo.getId()); + vm.setState(State.Migrating); + _mockVmDao.update(vm.getId(), vm); + txn.commit(); + } catch (Exception ex) { + txn.rollback(); + throw new CloudRuntimeException("unable to find vm " + vmTo.getName(), ex); + } finally { + txn.close(); + txn = Transaction.open(Transaction.CLOUD_DB); + txn.close(); + return new PrepareForMigrationAnswer(cmd); + } + } + @Override public Answer IpAssoc(IpAssocCommand cmd) { return new Answer(cmd); @@ -516,20 +543,20 @@ public class MockVmManagerImpl implements MockVmManager { public Answer WatchConsoleProxyLoad(WatchConsoleProxyLoadCommand cmd) { return Answer.createUnsupportedCommandAnswer(cmd); } - + @Override public GetDomRVersionAnswer getDomRVersion(GetDomRVersionCmd cmd) { - return new GetDomRVersionAnswer(cmd, null, null, null); + return new GetDomRVersionAnswer(cmd, null, null, null); } @Override public SecurityGroupRuleAnswer AddSecurityGroupRules(SecurityGroupRulesCmd cmd, SimulatorInfo info) { if (!info.isEnabled()) { - return new SecurityGroupRuleAnswer(cmd, false, "Disabled", SecurityGroupRuleAnswer.FailureReason.CANNOT_BRIDGE_FIREWALL); + return new SecurityGroupRuleAnswer(cmd, false, "Disabled", SecurityGroupRuleAnswer.FailureReason.CANNOT_BRIDGE_FIREWALL); } - + Map> rules = _securityRules.get(info.getHostUuid()); - + if (rules == null) { logSecurityGroupAction(cmd, null); rules = new ConcurrentHashMap>(); @@ -539,10 +566,10 @@ public class MockVmManagerImpl implements MockVmManager { logSecurityGroupAction(cmd, rules.get(cmd.getVmName())); rules.put(cmd.getVmName(), new Ternary(cmd.getSignature(), cmd.getVmId(), cmd.getSeqNum())); } - + return new SecurityGroupRuleAnswer(cmd); } - + private boolean logSecurityGroupAction(SecurityGroupRulesCmd cmd, Ternary rule) { String action = ", do nothing"; String reason = ", reason="; @@ -554,13 +581,13 @@ public class MockVmManagerImpl implements MockVmManager { s_logger.info("New seqno received: " + cmd.getSeqNum() + " curr=" + currSeqnum); updateSeqnoAndSig = true; if (!cmd.getSignature().equals(currSig)) { - s_logger.info("New seqno received: " + cmd.getSeqNum() + " curr=" + currSeqnum + s_logger.info("New seqno received: " + cmd.getSeqNum() + " curr=" + currSeqnum + " new signature received:" + cmd.getSignature() + " curr=" + currSig + ", updated iptables"); action = ", updated iptables"; reason = reason + "seqno_increased_sig_changed"; } else { - s_logger.info("New seqno received: " + cmd.getSeqNum() + " curr=" + currSeqnum - + " no change in signature:" + cmd.getSignature() + ", do nothing"); + s_logger.info("New seqno received: " + cmd.getSeqNum() + " curr=" + currSeqnum + + " no change in signature:" + cmd.getSignature() + ", do nothing"); reason = reason + "seqno_increased_sig_same"; } } else if (cmd.getSeqNum() < currSeqnum) { @@ -568,14 +595,14 @@ public class MockVmManagerImpl implements MockVmManager { reason = reason + "seqno_decreased"; } else { if (!cmd.getSignature().equals(currSig)) { - s_logger.info("Identical seqno received: " + cmd.getSeqNum() + s_logger.info("Identical seqno received: " + cmd.getSeqNum() + " new signature received:" + cmd.getSignature() + " curr=" + currSig + ", updated iptables"); action = ", updated iptables"; reason = reason + "seqno_same_sig_changed"; updateSeqnoAndSig = true; } else { - s_logger.info("Identical seqno received: " + cmd.getSeqNum() + " curr=" + currSeqnum - + " no change in signature:" + cmd.getSignature() + ", do nothing"); + s_logger.info("Identical seqno received: " + cmd.getSeqNum() + " curr=" + currSeqnum + + " no change in signature:" + cmd.getSignature() + ", do nothing"); reason = reason + "seqno_same_sig_same"; } } @@ -585,8 +612,8 @@ public class MockVmManagerImpl implements MockVmManager { action = ", updated iptables"; reason = ", seqno_new"; } - s_logger.info("Programmed network rules for vm " + cmd.getVmName() + " seqno=" + cmd.getSeqNum() - + " signature=" + cmd.getSignature() + s_logger.info("Programmed network rules for vm " + cmd.getVmName() + " seqno=" + cmd.getSeqNum() + + " signature=" + cmd.getSignature() + " guestIp=" + cmd.getGuestIp() + ", numIngressRules=" + cmd.getIngressRuleSet().length + ", numEgressRules=" + cmd.getEgressRuleSet().length + " total cidrs=" + cmd.getTotalNumCidrs() + action + reason); @@ -595,13 +622,13 @@ public class MockVmManagerImpl implements MockVmManager { @Override public Answer SavePassword(SavePasswordCommand cmd) { - return new Answer(cmd); + return new Answer(cmd); } - + @Override public HashMap> syncNetworkGroups(SimulatorInfo info) { HashMap> maps = new HashMap>(); - + Map> rules = _securityRules.get(info.getHostUuid()); if (rules == null) { return maps; diff --git a/agent-simulator/src/com/cloud/agent/manager/SimulatorInfo.java b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/SimulatorInfo.java similarity index 98% rename from agent-simulator/src/com/cloud/agent/manager/SimulatorInfo.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/manager/SimulatorInfo.java index dafd33abb51..c084730c6bb 100644 --- a/agent-simulator/src/com/cloud/agent/manager/SimulatorInfo.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/SimulatorInfo.java @@ -20,39 +20,39 @@ public class SimulatorInfo { private boolean enabled; private int timeout; private String hostUuid; - + public SimulatorInfo(boolean enabled, int timeout, String hostUuid) { this.enabled = enabled; this.timeout = timeout; this.hostUuid = hostUuid; } - + public SimulatorInfo() { this.enabled = true; this.timeout = -1; this.hostUuid = null; } - + public boolean isEnabled() { return this.enabled; } - + public int getTimeout() { return this.timeout; } - + public String getHostUuid() { return this.hostUuid; } - + public void setEnabled(boolean enabled) { this.enabled = enabled; } - + public void setTimeout(int timeout) { this.timeout = timeout; } - + public void setHostUuid(String hostUuid) { this.hostUuid = hostUuid; } diff --git a/agent-simulator/src/com/cloud/agent/manager/SimulatorManager.java b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/SimulatorManager.java similarity index 97% rename from agent-simulator/src/com/cloud/agent/manager/SimulatorManager.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/manager/SimulatorManager.java index 2b31b14d32f..ff8c32ce185 100755 --- a/agent-simulator/src/com/cloud/agent/manager/SimulatorManager.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/SimulatorManager.java @@ -23,7 +23,6 @@ import java.util.Map; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; import com.cloud.agent.api.StoragePoolInfo; -import com.cloud.agent.mockvm.MockVm; import com.cloud.simulator.MockVMVO; import com.cloud.utils.Pair; import com.cloud.utils.component.Manager; @@ -31,10 +30,10 @@ import com.cloud.vm.VirtualMachine.State; public interface SimulatorManager extends Manager { public static final String Name = "simulator manager"; - + public enum AgentType { Computing(0), // not used anymore - Routing(1), + Routing(1), Storage(2); int value; @@ -56,7 +55,7 @@ public interface SimulatorManager extends Manager { Answer simulate(Command cmd, String hostGuid); StoragePoolInfo getLocalStorage(String hostGuid); - + boolean configureSimulator(Long zoneId, Long podId, Long clusterId, Long hostId, String command, String values); public HashMap> syncNetworkGroups(String hostGuid); diff --git a/agent-simulator/src/com/cloud/agent/manager/SimulatorManagerImpl.java b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/SimulatorManagerImpl.java similarity index 87% rename from agent-simulator/src/com/cloud/agent/manager/SimulatorManagerImpl.java rename to plugins/hypervisors/simulator/src/com/cloud/agent/manager/SimulatorManagerImpl.java index 9a81ea6edaa..3d572ff83a3 100644 --- a/agent-simulator/src/com/cloud/agent/manager/SimulatorManagerImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/SimulatorManagerImpl.java @@ -16,8 +16,6 @@ // under the License. package com.cloud.agent.manager; -import java.sql.Connection; -import java.sql.SQLException; import java.util.HashMap; import java.util.Map; @@ -58,6 +56,7 @@ import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.VirtualMachine.State; + @Local(value = { SimulatorManager.class }) public class SimulatorManagerImpl implements SimulatorManager { private static final Logger s_logger = Logger.getLogger(SimulatorManagerImpl.class); @@ -121,43 +120,43 @@ public class SimulatorManagerImpl implements SimulatorManager { public Answer simulate(Command cmd, String hostGuid) { Transaction txn = Transaction.open(Transaction.SIMULATOR_DB); // txn.transitToUserManagedConnection(_concierge.conn()); - + try { MockHost host = _mockHost.findByGuid(hostGuid); String cmdName = cmd.toString(); int index = cmdName.lastIndexOf("."); if (index != -1) { - cmdName = cmdName.substring(index + 1); + cmdName = cmdName.substring(index + 1); } MockConfigurationVO config = _mockConfigDao.findByNameBottomUP(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), cmdName); - + SimulatorInfo info = new SimulatorInfo(); info.setHostUuid(hostGuid); - + if (config != null) { Map configParameters = config.getParameters(); for (Map.Entry entry : configParameters.entrySet()) { - if (entry.getKey().equalsIgnoreCase("enabled")) { - info.setEnabled(Boolean.parseBoolean(entry.getValue())); - } else if (entry.getKey().equalsIgnoreCase("timeout")) { - try { - info.setTimeout(Integer.valueOf(entry.getValue())); - } catch (NumberFormatException e) { - s_logger.debug("invalid timeout parameter: " + e.toString()); - } - } else if (entry.getKey().equalsIgnoreCase("wait")) { - try { - int wait = Integer.valueOf(entry.getValue()); - Thread.sleep(wait * 1000); - } catch (NumberFormatException e) { - s_logger.debug("invalid timeout parameter: " + e.toString()); - } catch (InterruptedException e) { - s_logger.debug("thread is interrupted: " + e.toString()); - } - } + if (entry.getKey().equalsIgnoreCase("enabled")) { + info.setEnabled(Boolean.parseBoolean(entry.getValue())); + } else if (entry.getKey().equalsIgnoreCase("timeout")) { + try { + info.setTimeout(Integer.valueOf(entry.getValue())); + } catch (NumberFormatException e) { + s_logger.debug("invalid timeout parameter: " + e.toString()); + } + } else if (entry.getKey().equalsIgnoreCase("wait")) { + try { + int wait = Integer.valueOf(entry.getValue()); + Thread.sleep(wait * 1000); + } catch (NumberFormatException e) { + s_logger.debug("invalid timeout parameter: " + e.toString()); + } catch (InterruptedException e) { + s_logger.debug("thread is interrupted: " + e.toString()); + } + } } } - + if (cmd instanceof GetHostStatsCommand) { return _mockAgentMgr.getHostStatistic((GetHostStatsCommand)cmd); } else if (cmd instanceof CheckHealthCommand) { @@ -165,7 +164,7 @@ public class SimulatorManagerImpl implements SimulatorManager { } else if (cmd instanceof PingTestCommand) { return _mockAgentMgr.pingTest((PingTestCommand)cmd); } else if (cmd instanceof PrepareForMigrationCommand) { - return _mockAgentMgr.prepareForMigrate((PrepareForMigrationCommand)cmd); + return _mockVmMgr.prepareForMigrate((PrepareForMigrationCommand)cmd); } else if (cmd instanceof MigrateCommand) { return _mockVmMgr.Migrate((MigrateCommand)cmd, info); } else if (cmd instanceof StartCommand) { @@ -173,11 +172,11 @@ public class SimulatorManagerImpl implements SimulatorManager { } else if (cmd instanceof CheckSshCommand) { return _mockVmMgr.checkSshCommand((CheckSshCommand)cmd); } else if (cmd instanceof CheckVirtualMachineCommand) { - return _mockVmMgr.checkVmState((CheckVirtualMachineCommand)cmd); + return _mockVmMgr.checkVmState((CheckVirtualMachineCommand)cmd); } else if (cmd instanceof SetStaticNatRulesCommand) { return _mockVmMgr.SetStaticNatRules((SetStaticNatRulesCommand)cmd); } else if (cmd instanceof SetFirewallRulesCommand) { - return _mockVmMgr.SetFirewallRules((SetFirewallRulesCommand)cmd); + return _mockVmMgr.SetFirewallRules((SetFirewallRulesCommand)cmd); } else if (cmd instanceof SetPortForwardingRulesCommand) { return _mockVmMgr.SetPortForwardingRules((SetPortForwardingRulesCommand)cmd); } else if (cmd instanceof NetworkUsageCommand) { @@ -193,7 +192,7 @@ public class SimulatorManagerImpl implements SimulatorManager { } else if (cmd instanceof CleanupNetworkRulesCmd) { return _mockVmMgr.CleanupNetworkRules((CleanupNetworkRulesCmd)cmd, info); } else if (cmd instanceof CheckNetworkCommand) { - return _mockAgentMgr.checkNetworkCommand((CheckNetworkCommand) cmd); + return _mockAgentMgr.checkNetworkCommand((CheckNetworkCommand) cmd); }else if (cmd instanceof StopCommand) { return _mockVmMgr.stopVM((StopCommand)cmd); } else if (cmd instanceof RebootCommand) { @@ -261,12 +260,11 @@ public class SimulatorManagerImpl implements SimulatorManager { } else if (cmd instanceof BumpUpPriorityCommand) { return _mockVmMgr.bumpPriority((BumpUpPriorityCommand) cmd); } else if (cmd instanceof GetDomRVersionCmd) { - return _mockVmMgr.getDomRVersion((GetDomRVersionCmd) cmd); + return _mockVmMgr.getDomRVersion((GetDomRVersionCmd) cmd); } else if (cmd instanceof ClusterSyncCommand) { - return new Answer(cmd); - //return new ClusterSyncAnswer(((ClusterSyncCommand) cmd).getClusterId(), this.getVmStates(hostGuid)); + return new Answer(cmd); } else if (cmd instanceof CopyVolumeCommand) { - return _mockStorageMgr.CopyVolume((CopyVolumeCommand) cmd); + return _mockStorageMgr.CopyVolume((CopyVolumeCommand) cmd); } else { return Answer.createUnsupportedCommandAnswer(cmd); } @@ -288,19 +286,19 @@ public class SimulatorManagerImpl implements SimulatorManager { @Override public Map getVmStates(String hostGuid) { - return _mockVmMgr.getVmStates(hostGuid); + return _mockVmMgr.getVmStates(hostGuid); } - + @Override public Map getVms(String hostGuid) { - return _mockVmMgr.getVms(hostGuid); + return _mockVmMgr.getVms(hostGuid); } - + @Override public HashMap> syncNetworkGroups(String hostGuid) { - SimulatorInfo info = new SimulatorInfo(); - info.setHostUuid(hostGuid); - return _mockVmMgr.syncNetworkGroups(info); + SimulatorInfo info = new SimulatorInfo(); + info.setHostUuid(hostGuid); + return _mockVmMgr.syncNetworkGroups(info); } @Override diff --git a/agent-simulator/src/com/cloud/api/commands/ConfigureSimulator.java b/plugins/hypervisors/simulator/src/com/cloud/api/commands/ConfigureSimulator.java similarity index 91% rename from agent-simulator/src/com/cloud/api/commands/ConfigureSimulator.java rename to plugins/hypervisors/simulator/src/com/cloud/api/commands/ConfigureSimulator.java index 4147e3aae1f..92f89488221 100755 --- a/agent-simulator/src/com/cloud/api/commands/ConfigureSimulator.java +++ b/plugins/hypervisors/simulator/src/com/cloud/api/commands/ConfigureSimulator.java @@ -19,12 +19,12 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import com.cloud.agent.manager.SimulatorManager; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Implementation; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; @@ -37,25 +37,25 @@ import com.cloud.utils.component.ComponentLocator; public class ConfigureSimulator extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ConfigureSimulator.class.getName()); private static final String s_name = "configuresimulatorresponse"; - + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="configure range: in a zone") private Long zoneId; - + @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="configure range: in a pod") private Long podId; - + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, description="configure range: in a cluster") private Long clusterId; - + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="configure range: in a host") private Long hostId; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="which command needs to be configured") private String command; - + @Parameter(name=ApiConstants.VALUE, type=CommandType.STRING, required=true, description="configuration options for this command, which is seperated by ;") private String values; - + @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); @@ -64,7 +64,7 @@ public class ConfigureSimulator extends BaseCmd { if (!result) { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to configure simulator"); } - + SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } diff --git a/agent-simulator/src/com/cloud/configuration/SimulatorComponentLibrary.java b/plugins/hypervisors/simulator/src/com/cloud/configuration/SimulatorComponentLibrary.java similarity index 100% rename from agent-simulator/src/com/cloud/configuration/SimulatorComponentLibrary.java rename to plugins/hypervisors/simulator/src/com/cloud/configuration/SimulatorComponentLibrary.java diff --git a/agent-simulator/src/com/cloud/resource/AgentResourceBase.java b/plugins/hypervisors/simulator/src/com/cloud/resource/AgentResourceBase.java similarity index 98% rename from agent-simulator/src/com/cloud/resource/AgentResourceBase.java rename to plugins/hypervisors/simulator/src/com/cloud/resource/AgentResourceBase.java index 6261158ee11..808ca070d4d 100644 --- a/agent-simulator/src/com/cloud/resource/AgentResourceBase.java +++ b/plugins/hypervisors/simulator/src/com/cloud/resource/AgentResourceBase.java @@ -52,7 +52,7 @@ public class AgentResourceBase implements ServerResource { protected String _name; private List _warnings = new LinkedList(); private List _errors = new LinkedList(); - + private transient IAgentControl _agentControl; protected long _instanceId; @@ -64,36 +64,36 @@ public class AgentResourceBase implements ServerResource { protected MockHost agentHost = null; protected boolean stopped = false; protected String hostGuid = null; - + public AgentResourceBase(long instanceId, AgentType agentType, SimulatorManager simMgr, String hostGuid) { - _instanceId = instanceId; - + _instanceId = instanceId; + if(s_logger.isDebugEnabled()) { s_logger.info("New Routing host instantiated with guid:" + hostGuid); } - + if (agentType == AgentType.Routing) { _type = Host.Type.Routing; } else { _type = Host.Type.Storage; } - + this.hostGuid = hostGuid; } - + protected MockVmManager getVmMgr() { return _simMgr.getVmMgr(); } - + protected MockStorageManager getStorageMgr() { return _simMgr.getStorageMgr(); } - + protected MockAgentManager getAgentMgr() { return _simMgr.getAgentMgr(); } - + protected long getInstanceId() { return _instanceId; } @@ -102,7 +102,7 @@ public class AgentResourceBase implements ServerResource { if(s_logger.isDebugEnabled()) { s_logger.debug("Deserializing simulated agent on reconnect"); } - + } @Override @@ -113,18 +113,18 @@ public class AgentResourceBase implements ServerResource { public void setName(String name) { _name = name; } - + @Override public boolean configure(String name, Map params) throws ConfigurationException { hostGuid = (String)params.get("guid"); _locator = ComponentLocator.getLocator("management-server"); _simMgr = _locator.getManager(SimulatorManager.class); - + agentHost = getAgentMgr().getHost(hostGuid); return true; } - + private void reconnect(MockHost host) { if(s_logger.isDebugEnabled()) { @@ -244,7 +244,7 @@ public class AgentResourceBase implements ServerResource { } return file.getAbsolutePath(); } - + @Override public Answer executeRequest(Command cmd) { @@ -264,20 +264,20 @@ public class AgentResourceBase implements ServerResource { public void setType(Host.Type _type) { this._type = _type; } - + @Override public StartupCommand[] initialize() { return null; } - + public SimulatorManager getSimulatorManager() { return _simMgr; - } - - public void setSimulatorManager(SimulatorManager simMgr) { - _simMgr = simMgr; } - + + public void setSimulatorManager(SimulatorManager simMgr) { + _simMgr = simMgr; + } + public boolean isStopped() { return this.stopped; } diff --git a/agent-simulator/src/com/cloud/resource/AgentRoutingResource.java b/plugins/hypervisors/simulator/src/com/cloud/resource/AgentRoutingResource.java similarity index 96% rename from agent-simulator/src/com/cloud/resource/AgentRoutingResource.java rename to plugins/hypervisors/simulator/src/com/cloud/resource/AgentRoutingResource.java index f10713d126c..f35e4325b38 100644 --- a/agent-simulator/src/com/cloud/resource/AgentRoutingResource.java +++ b/plugins/hypervisors/simulator/src/com/cloud/resource/AgentRoutingResource.java @@ -91,7 +91,7 @@ public class AgentRoutingResource extends AgentStorageResource { } else if (cmd instanceof ReadyCommand) { return new ReadyAnswer((ReadyCommand)cmd); } else if (cmd instanceof ShutdownCommand) { - return execute((ShutdownCommand)cmd); + return execute((ShutdownCommand)cmd); } else { return _simMgr.simulate(cmd, hostGuid); } @@ -99,7 +99,7 @@ public class AgentRoutingResource extends AgentStorageResource { return new Answer(cmd, false, e.getMessage()); } } - + @Override public Type getType() { return Host.Type.Routing; @@ -111,10 +111,10 @@ public class AgentRoutingResource extends AgentStorageResource { return null; } synchronized (_vms) { - if (_vms.size() == 0) { - //load vms state from database - _vms.putAll(_simMgr.getVmStates(hostGuid)); - } + if (_vms.size() == 0) { + //load vms state from database + _vms.putAll(_simMgr.getVmStates(hostGuid)); + } } final HashMap newStates = sync(); HashMap> nwGrpStates = _simMgr.syncNetworkGroups(hostGuid); @@ -131,18 +131,18 @@ public class AgentRoutingResource extends AgentStorageResource { totalCpu = agentHost.getCpuCount() * agentHost.getCpuSpeed(); totalMem = agentHost.getMemorySize(); for (Map.Entry entry : vmsMaps.entrySet()) { - MockVMVO vm = entry.getValue(); - usedCpu += vm.getCpu(); - usedMem += vm.getMemory(); - _runningVms.put(entry.getKey(), new Pair(Long.valueOf(vm.getCpu()), vm.getMemory())); + MockVMVO vm = entry.getValue(); + usedCpu += vm.getCpu(); + usedMem += vm.getMemory(); + _runningVms.put(entry.getKey(), new Pair(Long.valueOf(vm.getCpu()), vm.getMemory())); } - + List info = getHostInfo(); StartupRoutingCommand cmd = new StartupRoutingCommand((Integer) info.get(0), (Long) info.get(1), (Long) info.get(2), (Long) info.get(4), (String) info.get(3), HypervisorType.Simulator, RouterPrivateIpStrategy.HostLocal); cmd.setStateChanges(changes); - + Map hostDetails = new HashMap(); hostDetails.put(RouterPrivateIpStrategy.class.getCanonicalName(), RouterPrivateIpStrategy.DcGlobal.toString()); @@ -167,13 +167,13 @@ public class AgentRoutingResource extends AgentStorageResource { cmd.setCluster(String.valueOf(agentHost.getClusterId())); StartupStorageCommand ssCmd = initializeLocalSR(); - + return new StartupCommand[] { cmd, ssCmd }; } private StartupStorageCommand initializeLocalSR() { Map tInfo = new HashMap(); - + StoragePoolInfo poolInfo = _simMgr.getLocalStorage(hostGuid); StartupStorageCommand cmd = new StartupStorageCommand(poolInfo.getHostPath(), poolInfo.getPoolType(), poolInfo.getCapacityBytes(), tInfo); @@ -183,14 +183,14 @@ public class AgentRoutingResource extends AgentStorageResource { cmd.setResourceType(StorageResourceType.STORAGE_POOL); return cmd; } - + protected synchronized Answer execute(StartCommand cmd) throws IllegalArgumentException { VirtualMachineTO vmSpec = cmd.getVirtualMachine(); String vmName = vmSpec.getName(); if (this.totalCpu < (vmSpec.getCpus() * vmSpec.getSpeed() + this.usedCpu) || this.totalMem < (vmSpec.getMaxRam() + this.usedMem)) { - return new StartAnswer(cmd, "Not enough resource to start the vm"); + return new StartAnswer(cmd, "Not enough resource to start the vm"); } State state = State.Stopped; synchronized (_vms) { @@ -202,7 +202,7 @@ public class AgentRoutingResource extends AgentStorageResource { if (!result.getResult()) { return new StartAnswer(cmd, result.getDetails()); } - + this.usedCpu += vmSpec.getCpus() * vmSpec.getSpeed(); this.usedMem += vmSpec.getMaxRam(); _runningVms.put(vmName, new Pair(Long.valueOf(vmSpec.getCpus() * vmSpec.getSpeed()), vmSpec.getMaxRam())); @@ -217,7 +217,7 @@ public class AgentRoutingResource extends AgentStorageResource { return new StartAnswer(cmd); } - + protected synchronized StopAnswer execute(StopCommand cmd) { StopAnswer answer = null; @@ -230,11 +230,11 @@ public class AgentRoutingResource extends AgentStorageResource { } try { Answer result = _simMgr.simulate(cmd, hostGuid); - + if (!result.getResult()) { return new StopAnswer(cmd, result.getDetails(), false); } - + answer = new StopAnswer(cmd, null, 0, true); Pair data = _runningVms.get(vmName); if (data != null) { @@ -242,16 +242,16 @@ public class AgentRoutingResource extends AgentStorageResource { this.usedMem -= data.second(); } state = State.Stopped; - + } finally { synchronized (_vms) { _vms.put(vmName, state); } } - + return answer; } - + protected CheckVirtualMachineAnswer execute(final CheckVirtualMachineCommand cmd) { final String vmName = cmd.getVmName(); CheckVirtualMachineAnswer result = (CheckVirtualMachineAnswer)_simMgr.simulate(cmd, hostGuid); @@ -346,7 +346,7 @@ public class AgentRoutingResource extends AgentStorageResource { return changes; } - + private Answer execute(ShutdownCommand cmd) { this.stopped = true; return new Answer(cmd); diff --git a/agent-simulator/src/com/cloud/resource/AgentStorageResource.java b/plugins/hypervisors/simulator/src/com/cloud/resource/AgentStorageResource.java similarity index 93% rename from agent-simulator/src/com/cloud/resource/AgentStorageResource.java rename to plugins/hypervisors/simulator/src/com/cloud/resource/AgentStorageResource.java index 2751b875eb6..1125eeb7847 100644 --- a/agent-simulator/src/com/cloud/resource/AgentStorageResource.java +++ b/plugins/hypervisors/simulator/src/com/cloud/resource/AgentStorageResource.java @@ -62,7 +62,7 @@ public class AgentStorageResource extends AgentResourceBase implements Secondary return _simMgr.simulate(cmd, hostGuid); } } - + @Override public PingCommand getCurrentStatus(long id) { if (isStopped()) { @@ -73,14 +73,14 @@ public class AgentStorageResource extends AgentResourceBase implements Secondary @Override public Type getType() { - if(SecondaryStorageVm.Role.templateProcessor.toString().equals(_role)) - return Host.Type.SecondaryStorage; - return Host.Type.SecondaryStorageCmdExecutor; + if(SecondaryStorageVm.Role.templateProcessor.toString().equals(_role)) + return Host.Type.SecondaryStorage; + return Host.Type.SecondaryStorageCmdExecutor; } @Override public StartupCommand[] initialize() { - StartupSecondaryStorageCommand cmd = new StartupSecondaryStorageCommand(); + StartupSecondaryStorageCommand cmd = new StartupSecondaryStorageCommand(); cmd.setPrivateIpAddress(agentHost.getPrivateIpAddress()); cmd.setPrivateNetmask(agentHost.getPrivateNetMask()); @@ -97,15 +97,15 @@ public class AgentStorageResource extends AgentResourceBase implements Secondary cmd.setPod(String.valueOf(agentHost.getPodId())); cmd.setGuid(agentHost.getGuid()); return new StartupCommand[] { cmd }; - } - + } + @Override public boolean configure(String name, Map params) throws ConfigurationException { if (!super.configure(name, params)) { s_logger.warn("Base class was unable to configure"); return false; } - + return true; } diff --git a/agent-simulator/src/com/cloud/resource/SimulatorDiscoverer.java b/plugins/hypervisors/simulator/src/com/cloud/resource/SimulatorDiscoverer.java similarity index 94% rename from agent-simulator/src/com/cloud/resource/SimulatorDiscoverer.java rename to plugins/hypervisors/simulator/src/com/cloud/resource/SimulatorDiscoverer.java index 729d4b0fd23..b6d40d49589 100755 --- a/agent-simulator/src/com/cloud/resource/SimulatorDiscoverer.java +++ b/plugins/hypervisors/simulator/src/com/cloud/resource/SimulatorDiscoverer.java @@ -60,7 +60,7 @@ import com.cloud.utils.component.Inject; public class SimulatorDiscoverer extends DiscovererBase implements Discoverer, Listener, ResourceStateAdapter { private static final Logger s_logger = Logger .getLogger(SimulatorDiscoverer.class); - + @Inject HostDao _hostDao; @Inject VMTemplateDao _vmTemplateDao; @Inject VMTemplateHostDao _vmTemplateHostDao; @@ -70,10 +70,10 @@ public class SimulatorDiscoverer extends DiscovererBase implements Discoverer, L @Inject MockAgentManager _mockAgentMgr = null; @Inject MockStorageManager _mockStorageMgr = null; @Inject ResourceManager _resourceMgr; - + /** * Finds ServerResources of an in-process simulator - * + * * @see com.cloud.resource.Discoverer#find(long, java.lang.Long, * java.lang.Long, java.net.URI, java.lang.String, java.lang.String) */ @@ -88,7 +88,7 @@ public class SimulatorDiscoverer extends DiscovererBase implements Discoverer, L String scheme = uri.getScheme(); String host = uri.getAuthority(); String commands = URLDecoder.decode(uri.getPath()); - + long cpuSpeed = _mockAgentMgr.DEFAULT_HOST_SPEED_MHZ; long cpuCores = _mockAgentMgr.DEFAULT_HOST_CPU_CORES; long memory = _mockAgentMgr.DEFAULT_HOST_MEM_SIZE; @@ -145,7 +145,7 @@ public class SimulatorDiscoverer extends DiscovererBase implements Discoverer, L if (s_logger.isInfoEnabled()) s_logger.info("invalid cluster id or cluster is not for Simulator hypervisors"); return null; - } + } cluster = Long.toString(clusterId); if(clu.getGuid() == null) { clu.setGuid(UUID.randomUUID().toString()); @@ -205,23 +205,23 @@ public class SimulatorDiscoverer extends DiscovererBase implements Discoverer, L for (HostVO h : hosts) { associateTemplatesToZone(h.getId(), h.getDataCenterId()); } - } + } private void associateTemplatesToZone(long hostId, long dcId){ - VMTemplateZoneVO tmpltZone; + VMTemplateZoneVO tmpltZone; - List allTemplates = _vmTemplateDao.listAll(); - for (VMTemplateVO vt: allTemplates){ - if (vt.isCrossZones()) { - tmpltZone = _vmTemplateZoneDao.findByZoneTemplate(dcId, vt.getId()); - if (tmpltZone == null) { - VMTemplateZoneVO vmTemplateZone = new VMTemplateZoneVO(dcId, vt.getId(), new Date()); - _vmTemplateZoneDao.persist(vmTemplateZone); - } - } - } + List allTemplates = _vmTemplateDao.listAll(); + for (VMTemplateVO vt: allTemplates){ + if (vt.isCrossZones()) { + tmpltZone = _vmTemplateZoneDao.findByZoneTemplate(dcId, vt.getId()); + if (tmpltZone == null) { + VMTemplateZoneVO vmTemplateZone = new VMTemplateZoneVO(dcId, vt.getId(), new Date()); + _vmTemplateZoneDao.persist(vmTemplateZone); + } + } + } } - + @Override public HypervisorType getHypervisorType() { return HypervisorType.Simulator; @@ -231,7 +231,7 @@ public class SimulatorDiscoverer extends DiscovererBase implements Discoverer, L public boolean matchHypervisor(String hypervisor) { return hypervisor.equalsIgnoreCase(HypervisorType.Simulator.toString()); } - + @Override public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); @@ -257,9 +257,9 @@ public class SimulatorDiscoverer extends DiscovererBase implements Discoverer, L @Override public void processConnect(HostVO host, StartupCommand cmd, boolean forRebalance) throws ConnectionException { - + /*if(forRebalance) - return; + return; if ( Host.Type.SecondaryStorage == host.getType() ) { List tmplts = _vmTemplateDao.listAll(); for( VMTemplateVO tmplt : tmplts ) { @@ -275,7 +275,7 @@ public class SimulatorDiscoverer extends DiscovererBase implements Discoverer, L } } }*/ - + } @Override @@ -312,12 +312,12 @@ public class SimulatorDiscoverer extends DiscovererBase implements Discoverer, L if (!(firstCmd instanceof StartupRoutingCommand)) { return null; } - + StartupRoutingCommand ssCmd = ((StartupRoutingCommand) firstCmd); if (ssCmd.getHypervisorType() != HypervisorType.Simulator) { return null; } - + return _resourceMgr.fillRoutingHostVO(host, ssCmd, HypervisorType.Simulator, details, hostTags); } @@ -326,11 +326,11 @@ public class SimulatorDiscoverer extends DiscovererBase implements Discoverer, L boolean isForceDeleteStorage) throws UnableDeleteHostException { return null; } - + @Override public boolean stop() { - _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); + _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); return super.stop(); } - + } diff --git a/agent-simulator/src/com/cloud/resource/SimulatorSecondaryDiscoverer.java b/plugins/hypervisors/simulator/src/com/cloud/resource/SimulatorSecondaryDiscoverer.java similarity index 96% rename from agent-simulator/src/com/cloud/resource/SimulatorSecondaryDiscoverer.java rename to plugins/hypervisors/simulator/src/com/cloud/resource/SimulatorSecondaryDiscoverer.java index f828bc822ca..5d4d5b97c40 100644 --- a/agent-simulator/src/com/cloud/resource/SimulatorSecondaryDiscoverer.java +++ b/plugins/hypervisors/simulator/src/com/cloud/resource/SimulatorSecondaryDiscoverer.java @@ -45,14 +45,14 @@ public class SimulatorSecondaryDiscoverer extends SecondaryStorageDiscoverer imp @Inject AgentManager _agentMgr; @Inject ResourceManager _resourceMgr; @Inject SnapshotDao _snapshotDao; - + @Override public boolean configure(String name, Map params) throws ConfigurationException { - _agentMgr.registerForHostEvents(this, true, false, false); + _agentMgr.registerForHostEvents(this, true, false, false); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return super.configure(name, params); } - + @Override public void postDiscovery(List hosts, long msId) { super.postDiscovery(hosts, msId); @@ -74,9 +74,9 @@ public class SimulatorSecondaryDiscoverer extends SecondaryStorageDiscoverer imp //for detecting SSVM dispatch StartupCommand firstCmd = startup[0]; if (!(firstCmd instanceof StartupSecondaryStorageCommand)) { - return null; + return null; } - + host.setType(com.cloud.host.Host.Type.SecondaryStorageVM); return host; } @@ -103,7 +103,7 @@ public class SimulatorSecondaryDiscoverer extends SecondaryStorageDiscoverer imp @Override public boolean stop() { - _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); + _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); return true; } @@ -130,7 +130,7 @@ public class SimulatorSecondaryDiscoverer extends SecondaryStorageDiscoverer imp @Override public void processConnect(HostVO host, StartupCommand cmd, boolean forRebalance) throws ConnectionException { - + } @Override diff --git a/agent-simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java b/plugins/hypervisors/simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java similarity index 99% rename from agent-simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java rename to plugins/hypervisors/simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java index 1c69b543aa8..35aa3010005 100644 --- a/agent-simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java @@ -25,7 +25,7 @@ public class ManagementServerSimulatorImpl extends ManagementServerExtImpl { for (int i = 0; i < apis.length; i++) { newapis[i] = apis[i]; } - + newapis[apis.length] = "commands-simulator.properties"; return newapis; } diff --git a/agent-simulator/src/com/cloud/simulator/MockConfigurationVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockConfigurationVO.java similarity index 96% rename from agent-simulator/src/com/cloud/simulator/MockConfigurationVO.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockConfigurationVO.java index dfea2279e9e..3ed862bb69f 100644 --- a/agent-simulator/src/com/cloud/simulator/MockConfigurationVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockConfigurationVO.java @@ -33,79 +33,79 @@ public class MockConfigurationVO { @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - + @Column(name="data_center_id", nullable=false) private Long dataCenterId; - + @Column(name="pod_id") private Long podId; - + @Column(name="cluster_id") private Long clusterId; - + @Column(name="host_id") private Long hostId; - + @Column(name="name") private String name; - + @Column(name="values") private String values; - + public long getId() { return this.id; } - + public Long getDataCenterId() { return this.dataCenterId; } - + public void setDataCenterId(Long dcId) { this.dataCenterId = dcId; } - + public Long getPodId() { return this.podId; } - + public void setPodId(Long podId) { this.podId = podId; } - + public Long getClusterId() { return this.clusterId; } - + public void setClusterId(Long clusterId) { this.clusterId = clusterId; } - + public Long getHostId() { return this.hostId; } - + public void setHostId(Long hostId) { this.hostId = hostId; } - + public String getName() { return this.name; } - + public void setName(String name) { this.name = name; } - + public String getValues() { return this.values; } - + public Map getParameters() { Map maps = new HashMap(); if (this.values == null) { return maps; } - + String[] vals = this.values.split("\\|"); for (String val : vals) { String[] paras = val.split(":"); @@ -113,9 +113,8 @@ public class MockConfigurationVO { } return maps; } - + public void setValues(String values) { this.values = values; } } - diff --git a/agent-simulator/src/com/cloud/simulator/MockHost.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockHost.java similarity index 93% rename from agent-simulator/src/com/cloud/simulator/MockHost.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockHost.java index d20e8259267..5ca90177189 100644 --- a/agent-simulator/src/com/cloud/simulator/MockHost.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockHost.java @@ -19,44 +19,44 @@ package com.cloud.simulator; public interface MockHost { public long getCpuSpeed(); public long getCpuCount(); - - + + public long getMemorySize(); - + public String getCapabilities(); - + public long getId(); - + public String getName(); - + public String getGuid(); - - + + public String getVersion(); - + public Long getDataCenterId(); - + public Long getPodId(); - + public Long getClusterId(); - + public String getPrivateIpAddress(); - + public String getPrivateNetMask(); - + public String getPrivateMacAddress(); - - + + public String getPublicIpAddress(); - + public String getPublicNetMask(); - + public String getPublicMacAddress(); - + public String getStorageIpAddress(); - + public String getStorageNetMask(); - + public String getStorageMacAddress(); - + } diff --git a/agent-simulator/src/com/cloud/simulator/MockHostVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockHostVO.java similarity index 94% rename from agent-simulator/src/com/cloud/simulator/MockHostVO.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockHostVO.java index 59b7e8d0788..c86dfa6a2bf 100644 --- a/agent-simulator/src/com/cloud/simulator/MockHostVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockHostVO.java @@ -31,245 +31,245 @@ public class MockHostVO implements MockHost { @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - + @Column(name="name", nullable=false) private String name = null; - + @Column(name="private_ip_address", nullable=false) private String privateIpAddress; - + @Column(name="private_mac_address", nullable=false) private String privateMacAddress; - + @Column(name="private_netmask", nullable=false) private String privateNetmask; - + @Column(name="public_netmask") private String publicNetmask; - + @Column(name="public_ip_address") private String publicIpAddress; - + @Column(name="public_mac_address") private String publicMacAddress; - + @Column(name="storage_ip_address") private String storageIpAddress; - + @Column(name="storage_mac_address") private String storageMacAddress; - + @Column(name="storage_netmask") private String storageNetMask; - + @Column(name="guid") private String guid; - + @Column(name="version") private String version; - + @Column(name="data_center_id", nullable=false) private long dataCenterId; - + @Column(name="pod_id") private Long podId; - + @Column(name="cluster_id") private Long clusterId; - + @Column(name="speed") private long cpuSpeed; - + @Column(name="cpus") private long cpuCount; - + @Column(name="ram") private long memorySize; - + @Column(name="capabilities") private String capabilities; - + @Column(name="vm_id") private long vmId; - + @Column(name="resource") private String resource; - - - + + + public MockHostVO() { - + } - - + + public long getVmId() { return vmId; } - + public void setVmId(long vmId) { this.vmId = vmId; } - + public String getResource() { return this.resource; } - + public void setResource(String resource) { this.resource = resource; } - + public long getCpuSpeed() { return this.cpuSpeed; } - + public void setCpuSpeed(long cpuSpeed) { this.cpuSpeed = cpuSpeed; } - + public long getCpuCount() { return this.cpuCount; } - + public void setCpuCount(long cpuCount) { this.cpuCount = cpuCount; } - + public long getMemorySize() { return this.memorySize; } - + public void setMemorySize(long memorySize) { this.memorySize = memorySize; } - + public String getCapabilities() { return this.capabilities; } - + public void setCapabilities(String capabilities) { this.capabilities = capabilities; } - + public long getId() { return id; } - + public String getName() { return name; } - + public void setName(String name) { this.name = name; } - + public String getGuid() { return this.guid; } - + public void setGuid(String guid) { this.guid = guid; } - + public String getVersion() { return this.version; } - + public void setVersion(String version) { this.version = version; } - + public Long getDataCenterId() { return this.dataCenterId; } - + public void setDataCenterId(Long dataCenterId) { this.dataCenterId = dataCenterId; } - + public Long getPodId() { return this.podId; } - + public void setPodId(long podId) { this.podId = podId; } - + public Long getClusterId() { return this.clusterId; } - + public void setClusterId(Long clusterId) { this.clusterId = clusterId; } - + public String getPrivateIpAddress() { return privateIpAddress; } - + public void setPrivateIpAddress(String privateIpAddress) { this.privateIpAddress = privateIpAddress; } - + public String getPrivateNetMask() { return this.privateNetmask; } - + public void setPrivateNetMask(String privateNetmask) { this.privateNetmask = privateNetmask; } - + public String getPrivateMacAddress() { return this.privateMacAddress; } - + public void setPrivateMacAddress(String privateMacAddress) { this.privateMacAddress = privateMacAddress; } - + public String getPublicIpAddress() { return this.publicIpAddress; } - + public void setPublicIpAddress(String publicIpAddress) { this.publicIpAddress = publicIpAddress; } - + public String getPublicNetMask() { return this.publicNetmask; } - + public void setPublicNetMask(String publicNetMask) { this.publicNetmask = publicNetMask; } - + public String getPublicMacAddress() { return this.publicMacAddress; } - + public void setPublicMacAddress(String publicMacAddress) { this.publicMacAddress = publicMacAddress; } - + public String getStorageIpAddress() { return this.storageIpAddress; } - + public void setStorageIpAddress(String storageIpAddress) { this.storageIpAddress = storageIpAddress; } - + public String getStorageNetMask() { return this.storageNetMask; } - + public void setStorageNetMask(String storageNetMask) { this.storageNetMask = storageNetMask; } - + public String getStorageMacAddress() { return this.storageMacAddress; } - + public void setStorageMacAddress(String storageMacAddress) { this.storageMacAddress = storageMacAddress; } diff --git a/agent-simulator/src/com/cloud/simulator/MockSecStorageVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecStorageVO.java similarity index 96% rename from agent-simulator/src/com/cloud/simulator/MockSecStorageVO.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecStorageVO.java index c503cc260be..59a81c79abe 100644 --- a/agent-simulator/src/com/cloud/simulator/MockSecStorageVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecStorageVO.java @@ -31,45 +31,45 @@ public class MockSecStorageVO { @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - + @Column(name="url") private String url; - + @Column(name="capacity") private long capacity; - + @Column(name="mount_point") private String mountPoint; - - + + public MockSecStorageVO() { - + } - + public long getId() { return this.id; } - + public String getMountPoint() { return this.mountPoint; } - + public void setMountPoint(String mountPoint) { this.mountPoint = mountPoint; } - + public String getUrl() { return url; } - + public void setUrl(String url) { this.url = url; } - + public long getCapacity() { return this.capacity; } - + public void setCapacity(long capacity) { this.capacity = capacity; } diff --git a/agent-simulator/src/com/cloud/simulator/MockSecurityRulesVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecurityRulesVO.java similarity index 96% rename from agent-simulator/src/com/cloud/simulator/MockSecurityRulesVO.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecurityRulesVO.java index 3036ea98db2..df31fbf277b 100644 --- a/agent-simulator/src/com/cloud/simulator/MockSecurityRulesVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecurityRulesVO.java @@ -31,73 +31,73 @@ public class MockSecurityRulesVO { @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - + @Column(name="vmid") private Long vmId; - + @Column(name="signature") private String signature; - + @Column(name="seqnum") private Long seqNum; - + @Column(name="ruleset") private String ruleSet; - + @Column(name="hostid") private String hostId; - + @Column(name="vmname") public String vmName; - + public String getVmName() { return this.vmName; } - + public void setVmName(String vmName) { this.vmName = vmName; } - + public String getHostId() { return this.hostId; } - + public void setHostId(String hostId) { this.hostId = hostId; } - + public long getId() { return this.id; } - + public Long getVmId() { return this.vmId; } - + public void setVmId(Long vmId) { this.vmId = vmId; } - + public String getSignature() { return this.signature; } - + public void setSignature(String sig) { this.signature = sig; } - + public Long getSeqNum() { return this.seqNum; } - + public void setSeqNum(Long seqNum) { this.seqNum = seqNum; } - + public String getRuleSet() { return this.ruleSet; } - + public void setRuleSet(String ruleset) { this.ruleSet = ruleset; } diff --git a/agent-simulator/src/com/cloud/simulator/MockStoragePoolVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockStoragePoolVO.java similarity index 96% rename from agent-simulator/src/com/cloud/simulator/MockStoragePoolVO.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockStoragePoolVO.java index 81f0432247d..9c6e84d2714 100644 --- a/agent-simulator/src/com/cloud/simulator/MockStoragePoolVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockStoragePoolVO.java @@ -35,67 +35,67 @@ public class MockStoragePoolVO { @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - + @Column(name="guid") private String uuid; - + @Column(name="mount_point") private String mountPoint; - + @Column(name="capacity") private long capacity; - + @Column(name="hostguid") private String hostGuid; - + @Column(name="pool_type") @Enumerated(value=EnumType.STRING) private StoragePoolType poolType; - + public MockStoragePoolVO() { - + } - + public String getHostGuid() { return this.hostGuid; } - + public void setHostGuid(String hostGuid) { this.hostGuid = hostGuid; } - + public long getId() { return this.id; } - + public StoragePoolType getPoolType() { return this.poolType; } - + public void setStorageType(StoragePoolType poolType) { this.poolType = poolType; } - + public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } - + public String getMountPoint() { return this.mountPoint; } - + public void setMountPoint(String mountPoint) { this.mountPoint = mountPoint; } - + public long getCapacity() { return this.capacity; } - + public void setCapacity(long capacity) { this.capacity = capacity; } diff --git a/agent-simulator/src/com/cloud/simulator/MockVMVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVMVO.java similarity index 90% rename from agent-simulator/src/com/cloud/simulator/MockVMVO.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockVMVO.java index c1b391e37f6..3a5aa3d4c10 100644 --- a/agent-simulator/src/com/cloud/simulator/MockVMVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVMVO.java @@ -33,98 +33,108 @@ public class MockVMVO implements MockVm{ @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - + @Column(name="name") private String name; - + @Column(name="host_id") private long hostId; - + @Column(name="type") private String vmType; - + @Column(name="state") private State state; - + @Column(name="vnc_port") private int vncPort; - + @Column(name="memory") private long memory; - + @Column(name="cpu") private int cpu; - + + @Column(name="bootargs") + private String bootargs; + public MockVMVO() { - + } - + public long getId() { return this.id; } - + public String getName() { return this.name; } - + public void setName(String name) { this.name = name; } - + public long getHostId() { return this.hostId; } - + public void setHostId(long hostId) { this.hostId = hostId; } - + public String getVmType() { return this.vmType; } - + public void setVmType(String vmType) { this.vmType = vmType; } - + public State getState() { return this.state; } - + public String getType() { - return this.vmType; + return this.vmType; } - + public void setState(State state) { this.state = state; } - + public int getVncPort() { return this.vncPort; } - + public void setVncPort(int vncPort) { this.vncPort = vncPort; } - + public long getMemory() { return this.memory; } - + public void setMemory(long memory) { this.memory = memory; } - + public int getCpu() { return this.cpu; } - + public void setCpu(int cpu) { this.cpu = cpu; } - + public void setType(String type) { - this.vmType = type; + this.vmType = type; } + public String getBootargs() { + return bootargs; + } + + public void setBootargs(String bootargs) { + this.bootargs = bootargs; + } } diff --git a/agent-simulator/src/com/cloud/simulator/MockVm.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVm.java similarity index 94% rename from agent-simulator/src/com/cloud/simulator/MockVm.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockVm.java index 250ca7bedf4..e46b6a0cf99 100644 --- a/agent-simulator/src/com/cloud/simulator/MockVm.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVm.java @@ -20,26 +20,28 @@ import com.cloud.vm.VirtualMachine.State; // As storage is mapped from storage device, can virtually treat that VM here does public interface MockVm { - - + + public String getName(); - + public State getState(); - + public void setState(State state); - + public void setHostId(long hostId); public long getMemory(); - + public int getCpu(); public String getType(); public int getVncPort(); - + public void setName(String name); public void setMemory(long memory); public void setCpu(int cpu); public void setType(String type); public void setVncPort(int vncPort); public long getId(); -} + public String getBootargs(); + public void setBootargs(String bootargs); +} diff --git a/agent-simulator/src/com/cloud/simulator/MockVolumeVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVolumeVO.java similarity index 96% rename from agent-simulator/src/com/cloud/simulator/MockVolumeVO.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockVolumeVO.java index 94908d7efd4..48a12f8ee93 100644 --- a/agent-simulator/src/com/cloud/simulator/MockVolumeVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVolumeVO.java @@ -43,76 +43,76 @@ public class MockVolumeVO { @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - + @Column(name="name") private String name; - + @Column(name="size") private long size; - + @Column(name="path") private String path; - + @Column(name="pool_id") private long poolId; - + @Column(name="type") @Enumerated(value=EnumType.STRING) private MockVolumeType type; - + @Column(name="status") @Enumerated(value=EnumType.STRING) private VMTemplateStorageResourceAssoc.Status status; - + public long getId() { return id; } public String getName() { return this.name; } - + public void setName(String name) { this.name = name; } - + public long getSize() { return this.size; } - + public void setSize(long size) { this.size = size; } - + public String getPath() { return this.path; } - + public void setPath(String path) { this.path = path; } - + public long getPoolId() { return this.poolId; } - + public void setPoolId(long poolId) { this.poolId = poolId; } - + public MockVolumeType getType() { return this.type; } - + public void setType(MockVolumeType type) { this.type = type; } - + public Status getStatus() { return this.status; } - + public void setStatus(Status status) { this.status = status; } - + } diff --git a/agent-simulator/src/com/cloud/simulator/SimulatorGuru.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/SimulatorGuru.java similarity index 98% rename from agent-simulator/src/com/cloud/simulator/SimulatorGuru.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/SimulatorGuru.java index 20457e4db56..b9c404b66a1 100644 --- a/agent-simulator/src/com/cloud/simulator/SimulatorGuru.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/SimulatorGuru.java @@ -35,7 +35,7 @@ public class SimulatorGuru extends HypervisorGuruBase implements HypervisorGuru protected SimulatorGuru() { super(); } - + @Override public HypervisorType getHypervisorType() { return HypervisorType.Simulator; @@ -44,11 +44,11 @@ public class SimulatorGuru extends HypervisorGuruBase implements HypervisorGuru @Override public VirtualMachineTO implement(VirtualMachineProfile vm) { VirtualMachineTO to = toVirtualMachineTO(vm); - + // Determine the VM's OS description GuestOSVO guestOS = _guestOsDao.findById(vm.getVirtualMachine().getGuestOSId()); to.setOs(guestOS.getDisplayName()); - + return to; } diff --git a/agent-simulator/src/com/cloud/simulator/SimulatorRuntimeException.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/SimulatorRuntimeException.java similarity index 98% rename from agent-simulator/src/com/cloud/simulator/SimulatorRuntimeException.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/SimulatorRuntimeException.java index ce962a2d296..9891bc82556 100644 --- a/agent-simulator/src/com/cloud/simulator/SimulatorRuntimeException.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/SimulatorRuntimeException.java @@ -26,15 +26,15 @@ import com.cloud.utils.exception.RuntimeCloudException; public class SimulatorRuntimeException extends RuntimeCloudException { private static final long serialVersionUID = SerialVersionUID.CloudRuntimeException; - + public SimulatorRuntimeException(String message) { super(message); } - + public SimulatorRuntimeException(String message, Throwable th) { super(message, th); } - + protected SimulatorRuntimeException() { super(); } diff --git a/agent-simulator/src/com/cloud/simulator/dao/MockConfigurationDao.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockConfigurationDao.java similarity index 100% rename from agent-simulator/src/com/cloud/simulator/dao/MockConfigurationDao.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockConfigurationDao.java diff --git a/agent-simulator/src/com/cloud/simulator/dao/MockConfigurationDaoImpl.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockConfigurationDaoImpl.java similarity index 88% rename from agent-simulator/src/com/cloud/simulator/dao/MockConfigurationDaoImpl.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockConfigurationDaoImpl.java index a65a4a77c55..bd1b48dfde8 100644 --- a/agent-simulator/src/com/cloud/simulator/dao/MockConfigurationDaoImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockConfigurationDaoImpl.java @@ -35,8 +35,8 @@ public class MockConfigurationDaoImpl extends GenericDaoBase _searchByDcIDPodIdClusterIdName; private SearchBuilder _searchByDcIDPodIdClusterIdHostIdName; private SearchBuilder _searchByGlobalName; - - + + public MockConfigurationDaoImpl() { _searchByGlobalName = createSearchBuilder(); _searchByGlobalName.and("dcId", _searchByGlobalName.entity().getDataCenterId(), SearchCriteria.Op.NULL); @@ -45,7 +45,7 @@ public class MockConfigurationDaoImpl extends GenericDaoBase sc = _searchByGlobalName.create(); sc.setParameters("name", name); @@ -113,19 +113,19 @@ public class MockConfigurationDaoImpl extends GenericDaoBase implements MockHostDao { - protected final SearchBuilder GuidSearch; + protected final SearchBuilder GuidSearch; public MockHostDaoImpl() { GuidSearch = createSearchBuilder(); GuidSearch.and("guid", GuidSearch.entity().getGuid(), SearchCriteria.Op.EQ); diff --git a/agent-simulator/src/com/cloud/simulator/dao/MockSecStorageDao.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockSecStorageDao.java similarity index 100% rename from agent-simulator/src/com/cloud/simulator/dao/MockSecStorageDao.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockSecStorageDao.java diff --git a/agent-simulator/src/com/cloud/simulator/dao/MockSecStorageDaoImpl.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockSecStorageDaoImpl.java similarity index 95% rename from agent-simulator/src/com/cloud/simulator/dao/MockSecStorageDaoImpl.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockSecStorageDaoImpl.java index fd8d1d3a90b..65a375f5843 100644 --- a/agent-simulator/src/com/cloud/simulator/dao/MockSecStorageDaoImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockSecStorageDaoImpl.java @@ -25,14 +25,14 @@ import com.cloud.utils.db.SearchCriteria; @Local(value={MockSecStorageDao.class}) public class MockSecStorageDaoImpl extends GenericDaoBase implements MockSecStorageDao { - protected final SearchBuilder urlSearch; + protected final SearchBuilder urlSearch; @Override public MockSecStorageVO findByUrl(String url) { SearchCriteria sc = urlSearch.create(); sc.setParameters("url", url); return findOneBy(sc); } - + public MockSecStorageDaoImpl() { urlSearch = createSearchBuilder(); urlSearch.and("url", urlSearch.entity().getUrl(), SearchCriteria.Op.EQ); diff --git a/agent-simulator/src/com/cloud/simulator/dao/MockSecurityRulesDao.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockSecurityRulesDao.java similarity index 100% rename from agent-simulator/src/com/cloud/simulator/dao/MockSecurityRulesDao.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockSecurityRulesDao.java diff --git a/agent-simulator/src/com/cloud/simulator/dao/MockSecurityRulesDaoImpl.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockSecurityRulesDaoImpl.java similarity index 96% rename from agent-simulator/src/com/cloud/simulator/dao/MockSecurityRulesDaoImpl.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockSecurityRulesDaoImpl.java index 43a1da6c8fb..8831efef2ec 100644 --- a/agent-simulator/src/com/cloud/simulator/dao/MockSecurityRulesDaoImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockSecurityRulesDaoImpl.java @@ -29,7 +29,7 @@ import com.cloud.utils.db.SearchCriteria; @Local(value={MockSecurityRulesDao.class}) public class MockSecurityRulesDaoImpl extends GenericDaoBase implements MockSecurityRulesDao { protected SearchBuilder vmIdSearch; - protected SearchBuilder hostSearch; + protected SearchBuilder hostSearch; @Override public MockSecurityRulesVO findByVmId(Long vmId) { SearchCriteria sc = vmIdSearch.create(); @@ -43,18 +43,18 @@ public class MockSecurityRulesDaoImpl extends GenericDaoBase params) throws ConfigurationException { vmIdSearch = createSearchBuilder(); vmIdSearch.and("vmId", vmIdSearch.entity().getVmId(), SearchCriteria.Op.EQ); vmIdSearch.done(); - + hostSearch = createSearchBuilder(); hostSearch.and("host", hostSearch.entity().getHostId(), SearchCriteria.Op.EQ); hostSearch.done(); - + return true; } - + } diff --git a/agent-simulator/src/com/cloud/simulator/dao/MockStoragePoolDao.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockStoragePoolDao.java similarity index 100% rename from agent-simulator/src/com/cloud/simulator/dao/MockStoragePoolDao.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockStoragePoolDao.java diff --git a/agent-simulator/src/com/cloud/simulator/dao/MockStoragePoolDaoImpl.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockStoragePoolDaoImpl.java similarity index 99% rename from agent-simulator/src/com/cloud/simulator/dao/MockStoragePoolDaoImpl.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockStoragePoolDaoImpl.java index e35b5372946..3a64d27e30d 100644 --- a/agent-simulator/src/com/cloud/simulator/dao/MockStoragePoolDaoImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockStoragePoolDaoImpl.java @@ -34,12 +34,12 @@ public class MockStoragePoolDaoImpl extends GenericDaoBase implements MockVMDao { - protected SearchBuilder GuidSearch; + protected SearchBuilder GuidSearch; protected SearchBuilder vmNameSearch; protected SearchBuilder vmhostSearch; @Inject MockHostDao _mockHostDao; @@ -57,7 +57,7 @@ public class MockVMDaoImpl extends GenericDaoBase implements Moc sc.setParameters("state", VirtualMachine.State.Running); return listBy(sc); } - + @Override public MockVMVO findByVmNameAndHost(String vmName, String hostGuid) { SearchCriteria sc = vmhostSearch.create(); @@ -65,28 +65,28 @@ public class MockVMDaoImpl extends GenericDaoBase implements Moc sc.setParameters("name", vmName); return findOneBy(sc); } - + @Override public boolean configure(String name, Map params) throws ConfigurationException { SearchBuilder host = _mockHostDao.createSearchBuilder(); host.and("guid", host.entity().getGuid(), SearchCriteria.Op.EQ); - + GuidSearch = createSearchBuilder(); GuidSearch.join("host", host, host.entity().getId(), GuidSearch.entity().getHostId(), JoinBuilder.JoinType.INNER); GuidSearch.and("state", GuidSearch.entity().getState(), SearchCriteria.Op.EQ); GuidSearch.done(); - + vmNameSearch = createSearchBuilder(); vmNameSearch.and("name", vmNameSearch.entity().getName(), SearchCriteria.Op.EQ); vmNameSearch.done(); - + SearchBuilder newhost = _mockHostDao.createSearchBuilder(); newhost.and("guid", newhost.entity().getGuid(), SearchCriteria.Op.EQ); vmhostSearch = createSearchBuilder(); vmhostSearch.and("name", vmhostSearch.entity().getName(), SearchCriteria.Op.EQ); vmhostSearch.join("host", newhost, newhost.entity().getId(), vmhostSearch.entity().getHostId(), JoinBuilder.JoinType.INNER); vmhostSearch.done(); - + return true; } } diff --git a/agent-simulator/src/com/cloud/simulator/dao/MockVolumeDao.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockVolumeDao.java similarity index 100% rename from agent-simulator/src/com/cloud/simulator/dao/MockVolumeDao.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockVolumeDao.java diff --git a/agent-simulator/src/com/cloud/simulator/dao/MockVolumeDaoImpl.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockVolumeDaoImpl.java similarity index 96% rename from agent-simulator/src/com/cloud/simulator/dao/MockVolumeDaoImpl.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockVolumeDaoImpl.java index 87b54f196c1..a3a35179337 100644 --- a/agent-simulator/src/com/cloud/simulator/dao/MockVolumeDaoImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/dao/MockVolumeDaoImpl.java @@ -42,11 +42,11 @@ public class MockVolumeDaoImpl extends GenericDaoBase implem sc.setParameters("type", type); return listBy(sc); } - + @Override public Long findTotalStorageId(long id) { SearchCriteria sc = totalSearch.create(); - + sc.setParameters("poolId", id); return customSearch(sc, null).get(0); } @@ -57,20 +57,20 @@ public class MockVolumeDaoImpl extends GenericDaoBase implem sc.setParameters("path", "%" + path + "%"); return findOneBy(sc); } - + @Override public MockVolumeVO findByNameAndPool(String volumeName, String poolUUID) { SearchCriteria sc = namePoolSearch.create(); sc.setParameters("name", volumeName); sc.setParameters("poolUuid", poolUUID); - return findOneBy(sc); + return findOneBy(sc); } @Override public MockVolumeVO findByName(String volumeName) { SearchCriteria sc = nameSearch.create(); sc.setParameters("name", volumeName); - return findOneBy(sc); + return findOneBy(sc); } public MockVolumeDaoImpl() { @@ -78,24 +78,24 @@ public class MockVolumeDaoImpl extends GenericDaoBase implem idTypeSearch.and("storageId", idTypeSearch.entity().getPoolId(), SearchCriteria.Op.EQ); idTypeSearch.and("type", idTypeSearch.entity().getType(), SearchCriteria.Op.EQ); idTypeSearch.done(); - + pathTypeSearch = createSearchBuilder(); pathTypeSearch.and("path", pathTypeSearch.entity().getPath(), SearchCriteria.Op.LIKE); pathTypeSearch.done(); - + namePoolSearch = createSearchBuilder(); namePoolSearch.and("name", namePoolSearch.entity().getName(), SearchCriteria.Op.EQ); namePoolSearch.and("poolUuid", namePoolSearch.entity().getPoolId(), SearchCriteria.Op.EQ); namePoolSearch.done(); - + nameSearch = createSearchBuilder(); nameSearch.and("name", nameSearch.entity().getName(), SearchCriteria.Op.EQ); nameSearch.done(); - + totalSearch = createSearchBuilder(Long.class); totalSearch.select(null, Func.SUM, totalSearch.entity().getSize()); totalSearch.and("poolId", totalSearch.entity().getPoolId(), SearchCriteria.Op.EQ); totalSearch.done(); - - } + + } } diff --git a/plugins/hypervisors/vmware/build.xml b/plugins/hypervisors/vmware/build.xml deleted file mode 100755 index f6bcd435ae4..00000000000 --- a/plugins/hypervisors/vmware/build.xml +++ /dev/null @@ -1,135 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/hypervisors/xen/build.xml b/plugins/hypervisors/xen/build.xml deleted file mode 100755 index 9d3406f0ae2..00000000000 --- a/plugins/hypervisors/xen/build.xml +++ /dev/null @@ -1,135 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java index 9faceaae3bd..48f9681d48c 100755 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java @@ -70,6 +70,7 @@ import com.cloud.hypervisor.xen.resource.XenServer56Resource; import com.cloud.hypervisor.xen.resource.XenServer56SP2Resource; import com.cloud.hypervisor.xen.resource.XenServer600Resource; import com.cloud.hypervisor.xen.resource.XenServer602Resource; +import com.cloud.hypervisor.xen.resource.XenServer610Resource; import com.cloud.hypervisor.xen.resource.XenServerConnectionPool; import com.cloud.resource.Discoverer; import com.cloud.resource.DiscovererBase; @@ -436,9 +437,9 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L if (prodBrand.equals("XenServer") && prodVersion.equals("6.0.2")) return new XenServer602Resource(); - - if (prodBrand.equals("XenServer") && prodVersion.startsWith("6.0.9")) - return new XenServer602Resource(); + + if (prodBrand.equals("XenServer") && prodVersion.equals("6.1.0")) + return new XenServer610Resource(); if(prodBrand.equals("XenServer") && prodVersion.equals("5.6.100")) { String prodVersionTextShort = record.softwareVersion.get("product_version_text_short").trim(); @@ -448,18 +449,18 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L return new XenServer56FP1Resource(); } } - + if (prodBrand.equals("XCP_Kronos")) { return new XcpOssResource(); } - - String msg = "Only support XCP 1.0.0, 1.1.0, 1.5 beta; XenServer 5.6, XenServer 5.6 FP1, XenServer 5.6 SP2, Xenserver 6.0, 6.0.2, 6.0.9 but this one is " + prodBrand + " " + prodVersion; - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId, msg, msg); - s_logger.debug(msg); - throw new RuntimeException(msg); + + String msg = "Only support XCP 1.0.0, 1.1.0, 1.5 beta; XenServer 5.6, XenServer 5.6 FP1, XenServer 5.6 SP2, Xenserver 6.0, 6.0.2, 6.1.0 but this one is " + prodBrand + " " + prodVersion; + _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, dcId, podId, msg, msg); + s_logger.debug(msg); + throw new RuntimeException(msg); } - + protected void serverConfig() { String value = _params.get(Config.XenSetupMultipath.key()); _setupMultipath = Boolean.parseBoolean(value); @@ -589,8 +590,8 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L resource = XenServer600Resource.class.getName(); } else if (prodBrand.equals("XenServer") && prodVersion.equals("6.0.2")) { resource = XenServer602Resource.class.getName(); - } else if (prodBrand.equals("XenServer") && prodVersion.startsWith("6.0.9")) { - resource = XenServer602Resource.class.getName(); + } else if (prodBrand.equals("XenServer") && prodVersion.equals("6.1.0")) { + resource = XenServer610Resource.class.getName(); } else if(prodBrand.equals("XenServer") && prodVersion.equals("5.6.100")) { String prodVersionTextShort = details.get("product_version_text_short").trim(); if("5.6 SP2".equals(prodVersionTextShort)) { @@ -603,7 +604,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L } if( resource == null ){ - String msg = "Only support XCP 1.0.0, 1.1.0, 1.5 beta; XenServer 5.6, 5.6 FP1, 5.6 SP2 and Xenserver 6.0 , 6.0.2, 6.0.9 but this one is " + prodBrand + " " + prodVersion; + String msg = "Only support XCP 1.0.0, 1.1.0, 1.5 beta; XenServer 5.6, 5.6 FP1, 5.6 SP2 and Xenserver 6.0 , 6.0.2, 6.1.0 but this one is " + prodBrand + " " + prodVersion; s_logger.debug(msg); throw new RuntimeException(msg); } diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixHelper.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixHelper.java index bbb1ecfdb95..1b8496ff287 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixHelper.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixHelper.java @@ -33,6 +33,7 @@ public class CitrixHelper { private static final HashMap _xenServer56FP2GuestOsMap = new HashMap(70); private static final HashMap _xenServer600GuestOsMap = new HashMap(70); private static final HashMap _xenServer602GuestOsMap = new HashMap(70); + private static final HashMap _xenServer610GuestOsMap = new HashMap(70); private static final ArrayList _guestOsList = new ArrayList(70); @@ -554,6 +555,134 @@ public class CitrixHelper { _xenServer602GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); } + static { + _xenServer610GuestOsMap.put("CentOS 4.5 (32-bit)", "CentOS 4.5 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 4.6 (32-bit)", "CentOS 4.6 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 4.7 (32-bit)", "CentOS 4.7 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 4.8 (32-bit)", "CentOS 4.8 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.0 (32-bit)", "CentOS 5 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.0 (64-bit)", "CentOS 5 (64-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.1 (32-bit)", "CentOS 5 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.1 (64-bit)", "CentOS 5 (64-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.2 (32-bit)", "CentOS 5 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.2 (64-bit)", "CentOS 5 (64-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.3 (32-bit)", "CentOS 5 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.3 (64-bit)", "CentOS 5 (64-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.4 (32-bit)", "CentOS 5 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.4 (64-bit)", "CentOS 5 (64-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.5 (32-bit)", "CentOS 5 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.5 (64-bit)", "CentOS 5 (64-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.6 (32-bit)", "CentOS 5 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.6 (64-bit)", "CentOS 5 (64-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.7 (32-bit)", "CentOS 5 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 5.7 (64-bit)", "CentOS 5 (64-bit)"); + _xenServer610GuestOsMap.put("CentOS 6.0 (32-bit)", "CentOS 6.0 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 6.0 (64-bit)", "CentOS 6.0 (64-bit)"); + _xenServer610GuestOsMap.put("CentOS 6.1 (32-bit)", "CentOS 6.1 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 6.1 (64-bit)", "CentOS 6.1 (64-bit)"); + _xenServer610GuestOsMap.put("CentOS 6.2 (32-bit)", "CentOS 6.2 (32-bit)"); + _xenServer610GuestOsMap.put("CentOS 6.2 (64-bit)", "CentOS 6.2 (64-bit)"); + _xenServer610GuestOsMap.put("Debian GNU/Linux 5.0 (32-bit)", "Debian Lenny 5.0 (32-bit)"); + _xenServer610GuestOsMap.put("Debian GNU/Linux 6(32-bit)", "Debian Squeeze 6.0 (32-bit)"); + _xenServer610GuestOsMap.put("Debian GNU/Linux 6(64-bit)", "Debian Squeeze 6.0 (64-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.0 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.0 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.1 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.1 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.2 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.2 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.3 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.3 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.4 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.4 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.5 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.5 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.6 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.6 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.7 (32-bit)", "Oracle Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 5.7 (64-bit)", "Oracle Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 6.0 (32-bit)", "Oracle Enterprise Linux 6.0 (32-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 6.0 (64-bit)", "Oracle Enterprise Linux 6.0 (64-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 6.1 (32-bit)", "Oracle Enterprise Linux 6.1 (32-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 6.1 (64-bit)", "Oracle Enterprise Linux 6.1 (64-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 6.2 (32-bit)", "Oracle Enterprise Linux 6.2 (32-bit)"); + _xenServer610GuestOsMap.put("Oracle Enterprise Linux 6.2 (64-bit)", "Oracle Enterprise Linux 6.2 (64-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 4.5 (32-bit)", "Red Hat Enterprise Linux 4.5 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 4.6 (32-bit)", "Red Hat Enterprise Linux 4.6 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 4.7 (32-bit)", "Red Hat Enterprise Linux 4.7 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 4.8 (32-bit)", "Red Hat Enterprise Linux 4.8 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.0 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.0 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.1 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.1 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.2 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.2 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.3 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.3 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.4 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.4 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.5 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.5 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.6 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.6 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.7 (32-bit)", "Red Hat Enterprise Linux 5 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 5.7 (64-bit)", "Red Hat Enterprise Linux 5 (64-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.0 (32-bit)", "Red Hat Enterprise Linux 6.0 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.0 (64-bit)", "Red Hat Enterprise Linux 6.0 (64-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.1 (32-bit)", "Red Hat Enterprise Linux 6.1 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.1 (64-bit)", "Red Hat Enterprise Linux 6.1 (64-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.2 (32-bit)", "Red Hat Enterprise Linux 6.2 (32-bit)"); + _xenServer610GuestOsMap.put("Red Hat Enterprise Linux 6.2 (64-bit)", "Red Hat Enterprise Linux 6.2 (64-bit)"); + _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 9 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); + _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (32-bit)", "SUSE Linux Enterprise Server 10 SP1 (32-bit)"); + _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP1 (64-bit)", "SUSE Linux Enterprise Server 10 SP1 (64-bit)"); + _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (32-bit)", "SUSE Linux Enterprise Server 10 SP2 (32-bit)"); + _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP2 (64-bit)", "SUSE Linux Enterprise Server 10 SP2 (64-bit)"); + _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (32-bit)", "SUSE Linux Enterprise Server 10 SP3 (32-bit)"); + _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP3 (64-bit)", "SUSE Linux Enterprise Server 10 SP3 (64-bit)"); + _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (32-bit)", "SUSE Linux Enterprise Server 10 SP4 (32-bit)"); + _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 10 SP4 (64-bit)", "SUSE Linux Enterprise Server 10 SP4 (64-bit)"); + _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 11 (32-bit)", "SUSE Linux Enterprise Server 11 (32-bit)"); + _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 11 (64-bit)", "SUSE Linux Enterprise Server 11 (64-bit)"); + _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (32-bit)", "SUSE Linux Enterprise Server 11 SP1 (32-bit)"); + _xenServer610GuestOsMap.put("SUSE Linux Enterprise Server 11 SP1 (64-bit)", "SUSE Linux Enterprise Server 11 SP1 (64-bit)"); + _xenServer610GuestOsMap.put("Windows 7 (32-bit)", "Windows 7 (32-bit)"); + _xenServer610GuestOsMap.put("Windows 7 (64-bit)", "Windows 7 (64-bit)"); + _xenServer610GuestOsMap.put("Windows 8 (32-bit)", "Windows 8 (32-bit) (experimental)"); + _xenServer610GuestOsMap.put("Windows 8 (64-bit)", "Windows 7 (64-bit) (experimental)"); + _xenServer610GuestOsMap.put("Windows Server 2003 (32-bit)", "Windows Server 2003 (32-bit)"); + _xenServer610GuestOsMap.put("Windows Server 2003 (64-bit)", "Windows Server 2003 (64-bit)"); + _xenServer610GuestOsMap.put("Windows Server 2003 PAE (32-bit)", "Windows Server 2003 PAE (32-bit)"); + _xenServer610GuestOsMap.put("Windows Server 2003 Enterprise Edition(32-bit)", "Windows Server 2003 (32-bit)"); + _xenServer610GuestOsMap.put("Windows Server 2003 Enterprise Edition(64-bit)", "Windows Server 2003 (64-bit)"); + _xenServer610GuestOsMap.put("Windows Server 2003 DataCenter Edition(32-bit)", "Windows Server 2003 (32-bit)"); + _xenServer610GuestOsMap.put("Windows Server 2003 DataCenter Edition(64-bit)", "Windows Server 2003 (64-bit)"); + _xenServer610GuestOsMap.put("Windows Server 2003 Standard Edition(32-bit)", "Windows Server 2003 (32-bit)"); + _xenServer610GuestOsMap.put("Windows Server 2003 Standard Edition(64-bit)", "Windows Server 2003 (64-bit)"); + _xenServer610GuestOsMap.put("Windows Server 2008 (32-bit)", "Windows Server 2008 (32-bit)"); + _xenServer610GuestOsMap.put("Windows Server 2008 (64-bit)", "Windows Server 2008 (64-bit)"); + _xenServer610GuestOsMap.put("Windows Server 2008 R2 (64-bit)", "Windows Server 2008 R2 (64-bit)"); + _xenServer610GuestOsMap.put("Windows Server 8 (64-bit)", "Windows Server 8 (64-bit) (experimental)"); + _xenServer610GuestOsMap.put("Windows Vista (32-bit)", "Windows Vista (32-bit)"); + _xenServer610GuestOsMap.put("Windows XP SP3 (32-bit)", "Windows XP SP3 (32-bit)"); + _xenServer610GuestOsMap.put("Ubuntu 10.04 (32-bit)", "Ubuntu Lucid Lynx 10.04 (32-bit)"); + _xenServer610GuestOsMap.put("Ubuntu 10.04 (64-bit)", "Ubuntu Lucid Lynx 10.04 (64-bit)"); + _xenServer610GuestOsMap.put("Ubuntu 10.10 (32-bit)", "Ubuntu Maverick Meerkat 10.10 (32-bit) (experimental)"); + _xenServer610GuestOsMap.put("Ubuntu 10.10 (64-bit)", "Ubuntu Maverick Meerkat 10.10 (64-bit) (experimental)"); + _xenServer610GuestOsMap.put("Other Linux (32-bit)", "Other install media"); + _xenServer610GuestOsMap.put("Other Linux (64-bit)", "Other install media"); + _xenServer610GuestOsMap.put("Other (32-bit)", "Other install media"); + _xenServer610GuestOsMap.put("Other (64-bit)", "Other install media"); + _xenServer610GuestOsMap.put("Other CentOS (32-bit)", "Other install media"); + _xenServer610GuestOsMap.put("Other CentOS (64-bit)", "Other install media"); + _xenServer610GuestOsMap.put("Other Ubuntu (32-bit)", "Other install media"); + _xenServer610GuestOsMap.put("Other Ubuntu (64-bit)", "Other install media"); + _xenServer610GuestOsMap.put("Other SUSE Linux(32-bit)", "Other install media"); + _xenServer610GuestOsMap.put("Other SUSE Linux(64-bit)", "Other install media"); + _xenServer610GuestOsMap.put("Other PV (32-bit)", "CentOS 5 (32-bit)"); + _xenServer610GuestOsMap.put("Other PV (64-bit)", "CentOS 5 (64-bit)"); + } + public static String getXcpGuestOsType(String stdType) { String guestOS = _xcp100GuestOsMap.get(stdType); if (guestOS == null) { @@ -636,4 +765,18 @@ public class CitrixHelper { } return guestOS; } + + public static String getXenServer610GuestOsType(String stdType, boolean bootFromCD) { + String guestOS = _xenServer610GuestOsMap.get(stdType); + if (guestOS == null) { + if (!bootFromCD) { + s_logger.debug("Can't find the guest os: " + stdType + " mapping into XenServer 6.1.0 guestOS type, start it as HVM guest"); + guestOS = "Other install media"; + } else { + String msg = "XenServer 6.1.0 DOES NOT support Guest OS type " + stdType; + s_logger.warn(msg); + } + } + return guestOS; + } } diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java index d2db85c8597..313703c0a82 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java @@ -17,6 +17,10 @@ package com.cloud.hypervisor.xen.resource; +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -24,11 +28,13 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; +import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; @@ -179,6 +185,7 @@ import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.PortForwardingRuleTO; +import com.cloud.agent.api.to.S3TO; import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.agent.api.to.SwiftTO; @@ -217,6 +224,8 @@ import com.cloud.storage.template.TemplateInfo; import com.cloud.template.VirtualMachineTemplate.BootloaderType; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; +import com.cloud.utils.S3Utils; +import com.cloud.utils.StringUtils; import com.cloud.utils.Ternary; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; @@ -3113,11 +3122,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } protected void setMemory(Connection conn, VM vm, long memsize) throws XmlRpcException, XenAPIException { - vm.setMemoryStaticMin(conn, memsize); - vm.setMemoryDynamicMin(conn, memsize); - - vm.setMemoryDynamicMax(conn, memsize); - vm.setMemoryStaticMax(conn, memsize); + vm.setMemoryLimits(conn, memsize, memsize, memsize, memsize); } private void waitForTask(Connection c, Task task, long pollInterval, long timeout) throws XenAPIException, XmlRpcException { @@ -6511,7 +6516,14 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } finally { deleteSnapshotBackup(conn, dcId, accountId, volumeId, secondaryStorageMountPath, snapshotBackupUuid); } - } + } else if (cmd.getS3() != null) { + try { + backupSnapshotToS3(conn, cmd.getS3(), snapshotSr.getUuid(conn), snapshotBackupUuid, isISCSI, wait); + snapshotBackupUuid = snapshotBackupUuid + ".vhd"; + } finally { + deleteSnapshotBackup(conn, dcId, accountId, volumeId, secondaryStorageMountPath, snapshotBackupUuid); + } + } success = true; } finally { if( snapshotSr != null) { @@ -6528,6 +6540,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe snapshotBackupUuid = snapshotPaUuid + ".vhd"; } success = true; + } else if (cmd.getS3() != null) { + backupSnapshotToS3(conn, cmd.getS3(), primaryStorageSRUuid, snapshotPaUuid, isISCSI, wait); } else { snapshotBackupUuid = backupSnapshot(conn, primaryStorageSRUuid, dcId, accountId, volumeId, secondaryStorageMountPath, snapshotUuid, prevBackupUuid, isISCSI, wait); success = (snapshotBackupUuid != null); @@ -6550,6 +6564,88 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return new BackupSnapshotAnswer(cmd, success, details, snapshotBackupUuid, fullbackup); } + private static List serializeProperties(final Object object, + final Class propertySet) { + + assert object != null; + assert propertySet != null; + assert propertySet.isAssignableFrom(object.getClass()); + + try { + + final BeanInfo beanInfo = Introspector.getBeanInfo(propertySet); + final PropertyDescriptor[] descriptors = beanInfo + .getPropertyDescriptors(); + + final List serializedProperties = new ArrayList(); + for (final PropertyDescriptor descriptor : descriptors) { + + serializedProperties.add(descriptor.getName()); + final Object value = descriptor.getReadMethod().invoke(object); + serializedProperties.add(value != null ? value.toString() + : "null"); + + } + + return Collections.unmodifiableList(serializedProperties); + + } catch (IntrospectionException e) { + s_logger.warn( + "Ignored IntrospectionException when serializing class " + + object.getClass().getCanonicalName(), e); + } catch (IllegalArgumentException e) { + s_logger.warn( + "Ignored IllegalArgumentException when serializing class " + + object.getClass().getCanonicalName(), e); + } catch (IllegalAccessException e) { + s_logger.warn( + "Ignored IllegalAccessException when serializing class " + + object.getClass().getCanonicalName(), e); + } catch (InvocationTargetException e) { + s_logger.warn( + "Ignored InvocationTargetException when serializing class " + + object.getClass().getCanonicalName(), e); + } + + return Collections.emptyList(); + + } + + private boolean backupSnapshotToS3(final Connection connection, + final S3TO s3, final String srUuid, final String snapshotUuid, + final Boolean iSCSIFlag, final int wait) { + + final String filename = iSCSIFlag ? "VHD-" + snapshotUuid + : snapshotUuid + ".vhd"; + final String dir = (iSCSIFlag ? "/dev/VG_XenStorage-" + : "/var/run/sr-mount/") + srUuid; + final String key = StringUtils.join("/", "snapshots", snapshotUuid); + + try { + + final List parameters = new ArrayList( + serializeProperties(s3, S3Utils.ClientOptions.class)); + parameters.addAll(Arrays.asList("operation", "put", "directory", + dir, "filename", filename, "iSCSIFlag", + iSCSIFlag.toString(), "key", key)); + final String result = callHostPluginAsync(connection, "s3xen", + "s3", wait, + parameters.toArray(new String[parameters.size()])); + + if (result != null && result.equals("true")) { + return true; + } + + } catch (Exception e) { + s_logger.error(String.format( + "S3 upload failed of snapshot %1$s due to %2$s.", + snapshotUuid, e.toString()), e); + } + + return false; + + } + protected CreateVolumeFromSnapshotAnswer execute(final CreateVolumeFromSnapshotCommand cmd) { Connection conn = getConnection(); String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56Resource.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56Resource.java index 270240b69c8..716bb7cc9cc 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56Resource.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56Resource.java @@ -74,11 +74,6 @@ public class XenServer56Resource extends CitrixResourceBase { } } - @Override - protected void setMemory(Connection conn, VM vm, long memsize) throws XmlRpcException, XenAPIException { - vm.setMemoryLimits(conn, memsize, memsize, memsize, memsize); - } - @Override protected String getGuestOsType(String stdType, boolean bootFromCD) { diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer610Resource.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer610Resource.java new file mode 100644 index 00000000000..17ad3e62383 --- /dev/null +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer610Resource.java @@ -0,0 +1,58 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.hypervisor.xen.resource; + + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.resource.ServerResource; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.script.Script; + + +@Local(value=ServerResource.class) +public class XenServer610Resource extends XenServer56FP1Resource { + private static final Logger s_logger = Logger.getLogger(XenServer610Resource.class); + + public XenServer610Resource() { + super(); + } + + @Override + protected String getGuestOsType(String stdType, boolean bootFromCD) { + return CitrixHelper.getXenServer602GuestOsType(stdType, bootFromCD); + } + + @Override + protected List getPatchFiles() { + List files = new ArrayList(); + String patch = "scripts/vm/hypervisor/xenserver/xenserver60/patch"; + String patchfilePath = Script.findScript("" , patch); + if (patchfilePath == null) { + throw new CloudRuntimeException("Unable to find patch file " + patch); + } + File file = new File(patchfilePath); + files.add(file); + return files; + } +} diff --git a/plugins/network-elements/dns-notifier/pom.xml b/plugins/network-elements/dns-notifier/pom.xml new file mode 100644 index 00000000000..0b4c981af98 --- /dev/null +++ b/plugins/network-elements/dns-notifier/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + org.apache.cloudstack + cloudstack-plugins + 4.1.0-SNAPSHOT + ../../pom.xml + + org.apache.cloudstack + cloud-plugin-example-dns-notifier + 4.1.0-SNAPSHOT + CloudStack Dns Notifier Example + This is sample source code on how to write a plugin for CloudStack + + install + src + test + + + + org.apache.cloudstack + cloud-api + ${project.version} + + + org.apache.cloudstack + cloud-utils + ${project.version} + + + diff --git a/plugins/network-elements/dns-notifier/resources/components-example.xml b/plugins/network-elements/dns-notifier/resources/components-example.xml new file mode 100755 index 00000000000..592b01c3d2a --- /dev/null +++ b/plugins/network-elements/dns-notifier/resources/components-example.xml @@ -0,0 +1,220 @@ + + + + + + + + + + + + + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/network-elements/dns-notifier/src/org/apache/cloudstack/network/element/DnsNotifier.java b/plugins/network-elements/dns-notifier/src/org/apache/cloudstack/network/element/DnsNotifier.java new file mode 100644 index 00000000000..f9aa063973b --- /dev/null +++ b/plugins/network-elements/dns-notifier/src/org/apache/cloudstack/network/element/DnsNotifier.java @@ -0,0 +1,143 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.cloudstack.network.element; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import com.cloud.deploy.DeployDestination; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.Network; +import com.cloud.network.Network.Capability; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.network.element.NetworkElement; +import com.cloud.offering.NetworkOffering; +import com.cloud.vm.NicProfile; +import com.cloud.vm.ReservationContext; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; + +/** + * @author ahuang + * + */ +@Local(NetworkElement.class) +public class DnsNotifier implements NetworkElement { + String _name = null; + + public DnsNotifier() { + + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + @Override + public Map> getCapabilities() { + Map> caps = new HashMap>(); + caps.put(Service.Dns, new HashMap()); + return caps; + } + + @Override + public Provider getProvider() { + return null; + } + + @Override + public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { + return true; + } + + @Override + public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, + ResourceUnavailableException, InsufficientCapacityException { + // signal to the dns server that this vm is up and running and set the ip address to hostname mapping. + vm.getHostName(); + nic.getIp4Address(); + nic.getIp6Address(); + return true; + } + + @Override + public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { + vm.getHostName(); + nic.getIp4Address(); + nic.getIp6Address(); + // signal to the dns server that the vm is being shutdown and remove the mapping. + return true; + } + + @Override + public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { + return true; + } + + @Override + public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { + return true; + } + + @Override + public boolean isReady(PhysicalNetworkServiceProvider provider) { + return true; + } + + @Override + public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { + return true; + } + + @Override + public boolean canEnableIndividualServices() { + return true; + } + + @Override + public boolean verifyServicesCombination(Set services) { + return true; + } + +} diff --git a/plugins/network-elements/elastic-loadbalancer/build.xml b/plugins/network-elements/elastic-loadbalancer/build.xml deleted file mode 100755 index 66e42cedbd2..00000000000 --- a/plugins/network-elements/elastic-loadbalancer/build.xml +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/f5/build.xml b/plugins/network-elements/f5/build.xml deleted file mode 100755 index 47fcb1c6181..00000000000 --- a/plugins/network-elements/f5/build.xml +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index dfa2c9890d6..0cbb6a77d75 100644 --- a/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -119,7 +119,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan ConfigurationDao _configDao; private boolean canHandle(Network config) { - if (config.getGuestType() != Network.GuestType.Isolated || config.getTrafficType() != TrafficType.Guest) { + if ((config.getGuestType() != Network.GuestType.Isolated && config.getGuestType() != Network.GuestType.Shared) || config.getTrafficType() != TrafficType.Guest) { s_logger.trace("Not handling network with Type " + config.getGuestType() + " and traffic type " + config.getTrafficType()); return false; } diff --git a/plugins/network-elements/juniper-srx/build.xml b/plugins/network-elements/juniper-srx/build.xml deleted file mode 100755 index 7b8138a2ee2..00000000000 --- a/plugins/network-elements/juniper-srx/build.xml +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java index d9f6ce559bd..24bc2fc8db1 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java @@ -127,7 +127,8 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan private boolean canHandle(Network network, Service service) { DataCenter zone = _configMgr.getZone(network.getDataCenterId()); - if ((zone.getNetworkType() == NetworkType.Advanced && network.getGuestType() != Network.GuestType.Isolated) || (zone.getNetworkType() == NetworkType.Basic && network.getGuestType() != Network.GuestType.Shared)) { + if ((zone.getNetworkType() == NetworkType.Advanced && !(network.getGuestType() == Network.GuestType.Isolated || network.getGuestType() == Network.GuestType.Shared )) + || (zone.getNetworkType() == NetworkType.Basic && network.getGuestType() != Network.GuestType.Shared)) { s_logger.trace("Element " + getProvider().getName() + "is not handling network type = " + network.getGuestType()); return false; } diff --git a/plugins/network-elements/midokura-midonet/build.xml b/plugins/network-elements/midokura-midonet/build.xml deleted file mode 100644 index 6b826e700eb..00000000000 --- a/plugins/network-elements/midokura-midonet/build.xml +++ /dev/null @@ -1,17 +0,0 @@ - - diff --git a/plugins/network-elements/netscaler/build.xml b/plugins/network-elements/netscaler/build.xml deleted file mode 100755 index dcf8663de4b..00000000000 --- a/plugins/network-elements/netscaler/build.xml +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java index 4da097e3963..7cfe53ba6d6 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java +++ b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java @@ -152,7 +152,8 @@ StaticNatServiceProvider { private boolean canHandle(Network config, Service service) { DataCenter zone = _dcDao.findById(config.getDataCenterId()); - boolean handleInAdvanceZone = (zone.getNetworkType() == NetworkType.Advanced && config.getGuestType() == Network.GuestType.Isolated && config.getTrafficType() == TrafficType.Guest); + boolean handleInAdvanceZone = (zone.getNetworkType() == NetworkType.Advanced && + (config.getGuestType() == Network.GuestType.Isolated || config.getGuestType() == Network.GuestType.Shared) && config.getTrafficType() == TrafficType.Guest); boolean handleInBasicZone = (zone.getNetworkType() == NetworkType.Basic && config.getGuestType() == Network.GuestType.Shared && config.getTrafficType() == TrafficType.Guest); if (!(handleInAdvanceZone || handleInBasicZone)) { diff --git a/plugins/network-elements/nicira-nvp/build.xml b/plugins/network-elements/nicira-nvp/build.xml deleted file mode 100644 index 2d84c5c455f..00000000000 --- a/plugins/network-elements/nicira-nvp/build.xml +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java index a386ae53b47..1046a5a96b7 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java @@ -39,6 +39,7 @@ import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDetailsDao; import com.cloud.network.Network; +import com.cloud.network.Network.Service; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkProfile; import com.cloud.network.NetworkVO; @@ -50,9 +51,11 @@ import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetwork.IsolationMethod; import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkServiceMapDao; import com.cloud.network.dao.NiciraNvpDao; import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.offering.NetworkOffering; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; import com.cloud.resource.ResourceManager; import com.cloud.user.Account; import com.cloud.user.dao.AccountDao; @@ -88,6 +91,8 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { AgentManager _agentMgr; @Inject HostDetailsDao _hostDetailsDao; + @Inject + NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; public NiciraNvpGuestNetworkGuru() { super(); @@ -100,7 +105,8 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { if (networkType == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == Network.GuestType.Isolated - && isMyIsolationMethod(physicalNetwork)) { + && isMyIsolationMethod(physicalNetwork) + && _ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(offering.getId(), Service.Connectivity)) { return true; } else { s_logger.trace("We only take care of Guest networks of type " + GuestType.Isolated + " in zone of type " + NetworkType.Advanced); diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java index ce5205ba47f..0c4e677536c 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java @@ -41,7 +41,7 @@ public class Match { this.protocol = protocol; } - public Integer getSource_port_min() { + public Integer getSourcePortMin() { return source_port_min; } @@ -128,6 +128,126 @@ public class Match { public void setDestinationIpAddressesNot(Boolean destination_ip_addresses_not) { this.destination_ip_addresses_not = destination_ip_addresses_not; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime + * result + + ((destination_ip_addresses == null) ? 0 + : destination_ip_addresses.hashCode()); + result = prime + * result + + ((destination_ip_addresses_not == null) ? 0 + : destination_ip_addresses_not.hashCode()); + result = prime + * result + + ((destination_port_max == null) ? 0 : destination_port_max + .hashCode()); + result = prime + * result + + ((destination_port_min == null) ? 0 : destination_port_min + .hashCode()); + result = prime + * result + + ((destination_port_not == null) ? 0 : destination_port_not + .hashCode()); + result = prime * result + + ((ethertype == null) ? 0 : ethertype.hashCode()); + result = prime * result + + ((protocol == null) ? 0 : protocol.hashCode()); + result = prime + * result + + ((source_ip_addresses == null) ? 0 : source_ip_addresses + .hashCode()); + result = prime + * result + + ((source_ip_addresses_not == null) ? 0 + : source_ip_addresses_not.hashCode()); + result = prime * result + + ((source_port_max == null) ? 0 : source_port_max.hashCode()); + result = prime * result + + ((source_port_min == null) ? 0 : source_port_min.hashCode()); + result = prime * result + + ((source_port_not == null) ? 0 : source_port_not.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Match other = (Match) obj; + if (destination_ip_addresses == null) { + if (other.destination_ip_addresses != null) + return false; + } else if (!destination_ip_addresses + .equals(other.destination_ip_addresses)) + return false; + if (destination_ip_addresses_not == null) { + if (other.destination_ip_addresses_not != null) + return false; + } else if (!destination_ip_addresses_not + .equals(other.destination_ip_addresses_not)) + return false; + if (destination_port_max == null) { + if (other.destination_port_max != null) + return false; + } else if (!destination_port_max.equals(other.destination_port_max)) + return false; + if (destination_port_min == null) { + if (other.destination_port_min != null) + return false; + } else if (!destination_port_min.equals(other.destination_port_min)) + return false; + if (destination_port_not == null) { + if (other.destination_port_not != null) + return false; + } else if (!destination_port_not.equals(other.destination_port_not)) + return false; + if (ethertype == null) { + if (other.ethertype != null) + return false; + } else if (!ethertype.equals(other.ethertype)) + return false; + if (protocol == null) { + if (other.protocol != null) + return false; + } else if (!protocol.equals(other.protocol)) + return false; + if (source_ip_addresses == null) { + if (other.source_ip_addresses != null) + return false; + } else if (!source_ip_addresses.equals(other.source_ip_addresses)) + return false; + if (source_ip_addresses_not == null) { + if (other.source_ip_addresses_not != null) + return false; + } else if (!source_ip_addresses_not + .equals(other.source_ip_addresses_not)) + return false; + if (source_port_max == null) { + if (other.source_port_max != null) + return false; + } else if (!source_port_max.equals(other.source_port_max)) + return false; + if (source_port_min == null) { + if (other.source_port_min != null) + return false; + } else if (!source_port_min.equals(other.source_port_min)) + return false; + if (source_port_not == null) { + if (other.source_port_not != null) + return false; + } else if (!source_port_not.equals(other.source_port_not)) + return false; + return true; + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java index 7255ab67d39..b66ffa89b77 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java @@ -110,4 +110,173 @@ public class NatRule { public String getType() { return type; } + + public void setType(String type) { + this.type = type; + } + + @Override + public int hashCode() { + final int prime = 42; + int result = 1; + result = prime * result + ((match == null) ? 0 : match.hashCode()); + result = prime + * result + + ((to_destination_ip_address_max == null) ? 0 + : to_destination_ip_address_max.hashCode()); + result = prime + * result + + ((to_destination_ip_address_min == null) ? 0 + : to_destination_ip_address_min.hashCode()); + result = prime + * result + + ((to_destination_port == null) ? 0 : to_destination_port + .hashCode()); + result = prime + * result + + ((to_source_ip_address_max == null) ? 0 + : to_source_ip_address_max.hashCode()); + result = prime + * result + + ((to_source_ip_address_min == null) ? 0 + : to_source_ip_address_min.hashCode()); + result = prime + * result + + ((to_source_port_max == null) ? 0 : to_source_port_max + .hashCode()); + result = prime + * result + + ((to_source_port_min == null) ? 0 : to_source_port_min + .hashCode()); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + result = prime * result + ((uuid == null) ? 0 : uuid.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + NatRule other = (NatRule) obj; + if (match == null) { + if (other.match != null) + return false; + } else if (!match.equals(other.match)) + return false; + if (to_destination_ip_address_max == null) { + if (other.to_destination_ip_address_max != null) + return false; + } else if (!to_destination_ip_address_max + .equals(other.to_destination_ip_address_max)) + return false; + if (to_destination_ip_address_min == null) { + if (other.to_destination_ip_address_min != null) + return false; + } else if (!to_destination_ip_address_min + .equals(other.to_destination_ip_address_min)) + return false; + if (to_destination_port == null) { + if (other.to_destination_port != null) + return false; + } else if (!to_destination_port.equals(other.to_destination_port)) + return false; + if (to_source_ip_address_max == null) { + if (other.to_source_ip_address_max != null) + return false; + } else if (!to_source_ip_address_max + .equals(other.to_source_ip_address_max)) + return false; + if (to_source_ip_address_min == null) { + if (other.to_source_ip_address_min != null) + return false; + } else if (!to_source_ip_address_min + .equals(other.to_source_ip_address_min)) + return false; + if (to_source_port_max == null) { + if (other.to_source_port_max != null) + return false; + } else if (!to_source_port_max.equals(other.to_source_port_max)) + return false; + if (to_source_port_min == null) { + if (other.to_source_port_min != null) + return false; + } else if (!to_source_port_min.equals(other.to_source_port_min)) + return false; + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) + return false; + if (uuid == null) { + if (other.uuid != null) + return false; + } else if (!uuid.equals(other.uuid)) + return false; + return true; + } + + public boolean equalsIgnoreUuid(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + NatRule other = (NatRule) obj; + if (match == null) { + if (other.match != null) + return false; + } else if (!match.equals(other.match)) + return false; + if (to_destination_ip_address_max == null) { + if (other.to_destination_ip_address_max != null) + return false; + } else if (!to_destination_ip_address_max + .equals(other.to_destination_ip_address_max)) + return false; + if (to_destination_ip_address_min == null) { + if (other.to_destination_ip_address_min != null) + return false; + } else if (!to_destination_ip_address_min + .equals(other.to_destination_ip_address_min)) + return false; + if (to_destination_port == null) { + if (other.to_destination_port != null) + return false; + } else if (!to_destination_port.equals(other.to_destination_port)) + return false; + if (to_source_ip_address_max == null) { + if (other.to_source_ip_address_max != null) + return false; + } else if (!to_source_ip_address_max + .equals(other.to_source_ip_address_max)) + return false; + if (to_source_ip_address_min == null) { + if (other.to_source_ip_address_min != null) + return false; + } else if (!to_source_ip_address_min + .equals(other.to_source_ip_address_min)) + return false; + if (to_source_port_max == null) { + if (other.to_source_port_max != null) + return false; + } else if (!to_source_port_max.equals(other.to_source_port_max)) + return false; + if (to_source_port_min == null) { + if (other.to_source_port_min != null) + return false; + } else if (!to_source_port_min.equals(other.to_source_port_min)) + return false; + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) + return false; + return true; + } + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java index 26e7e0d663c..3e8e0285bfe 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpApi.java @@ -41,7 +41,9 @@ import javax.net.ssl.X509TrustManager; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpConnectionManager; import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; @@ -71,17 +73,42 @@ public class NiciraNvpApi { private String _adminpass; private HttpClient _client; - - public NiciraNvpApi(String host, String adminuser, String adminpass) throws NiciraNvpApiException { - this._host = host; - this._adminpass = adminpass; - this._adminuser = adminuser; - - if (_host == null || _adminpass == null || _adminuser == null) { - throw new NiciraNvpApiException("host, adminuser and adminpass may not be null"); + + /* This factory method is protected so we can extend this + * in the unittests. + */ + protected HttpClient createHttpClient() { + return new HttpClient(s_httpClientManager); + } + + protected HttpMethod createMethod(String type, String uri) throws NiciraNvpApiException { + String url; + try { + url = new URL(_protocol, _host, "/ws.v1/login").toString(); + } catch (MalformedURLException e) { + s_logger.error("Unable to build Nicira API URL", e); + throw new NiciraNvpApiException("Unable to build Nicira API URL", e); } + + if ("post".equalsIgnoreCase(type)) { + return new PostMethod(url); + } + else if ("get".equalsIgnoreCase(type)) { + return new GetMethod(url); + } + else if ("delete".equalsIgnoreCase(type)) { + return new DeleteMethod(url); + } + else if ("put".equalsIgnoreCase(type)) { + return new PutMethod(url); + } + else { + throw new NiciraNvpApiException("Requesting unknown method type"); + } + } - _client = new HttpClient(s_httpClientManager); + public NiciraNvpApi() { + _client = createHttpClient(); _client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); try { @@ -93,15 +120,30 @@ public class NiciraNvpApi { } + public void setControllerAddress(String address) { + this._host = address; + } + + public void setAdminCredentials(String username, String password) { + this._adminuser = username; + this._adminpass = password; + } + /** * Logs into the Nicira API. The cookie is stored in the _authcookie variable. *

* The method returns false if the login failed or the connection could not be made. * */ - private void login() throws NiciraNvpApiException { + protected void login() throws NiciraNvpApiException { String url; + if (_host == null || _host.isEmpty() || + _adminuser == null || _adminuser.isEmpty() || + _adminpass == null || _adminpass.isEmpty()) { + throw new NiciraNvpApiException("Hostname/credentials are null or empty"); + } + try { url = new URL(_protocol, _host, "/ws.v1/login").toString(); } catch (MalformedURLException e) { @@ -119,6 +161,8 @@ public class NiciraNvpApi { throw new NiciraNvpApiException("Nicira NVP API login failed ", e); } catch (IOException e) { throw new NiciraNvpApiException("Nicira NVP API login failed ", e); + } finally { + pm.releaseConnection(); } if (pm.getStatusCode() != HttpStatus.SC_OK) { @@ -237,14 +281,7 @@ public class NiciraNvpApi { public NatRule createLogicalRouterNatRule(String logicalRouterUuid, NatRule natRule) throws NiciraNvpApiException { String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/nat"; - if (natRule instanceof SourceNatRule) { - return executeCreateObject(natRule, new TypeToken(){}.getType(), uri, Collections.emptyMap()); - } - else if (natRule instanceof DestinationNatRule) { - return executeCreateObject(natRule, new TypeToken(){}.getType(), uri, Collections.emptyMap()); - } - - throw new NiciraNvpApiException("Unknown NatRule type"); + return executeCreateObject(natRule, new TypeToken(){}.getType(), uri, Collections.emptyMap()); } public void modifyLogicalRouterNatRule(String logicalRouterUuid, NatRule natRule) throws NiciraNvpApiException { @@ -298,18 +335,16 @@ public class NiciraNvpApi { return executeRetrieveObject(new TypeToken>(){}.getType(), uri, params); } - private void executeUpdateObject(T newObject, String uri, Map parameters) throws NiciraNvpApiException { - String url; - try { - url = new URL(_protocol, _host, uri).toString(); - } catch (MalformedURLException e) { - s_logger.error("Unable to build Nicira API URL", e); - throw new NiciraNvpApiException("Connection to NVP Failed"); + protected void executeUpdateObject(T newObject, String uri, Map parameters) throws NiciraNvpApiException { + if (_host == null || _host.isEmpty() || + _adminuser == null || _adminuser.isEmpty() || + _adminpass == null || _adminpass.isEmpty()) { + throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } Gson gson = new Gson(); - PutMethod pm = new PutMethod(url); + PutMethod pm = (PutMethod) createMethod("put", uri); pm.setRequestHeader("Content-Type", "application/json"); try { pm.setRequestEntity(new StringRequestEntity( @@ -322,24 +357,23 @@ public class NiciraNvpApi { if (pm.getStatusCode() != HttpStatus.SC_OK) { String errorMessage = responseToErrorMessage(pm); + pm.releaseConnection(); s_logger.error("Failed to update object : " + errorMessage); throw new NiciraNvpApiException("Failed to update object : " + errorMessage); } - + pm.releaseConnection(); } - private T executeCreateObject(T newObject, Type returnObjectType, String uri, Map parameters) throws NiciraNvpApiException { - String url; - try { - url = new URL(_protocol, _host, uri).toString(); - } catch (MalformedURLException e) { - s_logger.error("Unable to build Nicira API URL", e); - throw new NiciraNvpApiException("Unable to build Nicira API URL", e); + protected T executeCreateObject(T newObject, Type returnObjectType, String uri, Map parameters) throws NiciraNvpApiException { + if (_host == null || _host.isEmpty() || + _adminuser == null || _adminuser.isEmpty() || + _adminpass == null || _adminpass.isEmpty()) { + throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } Gson gson = new Gson(); - PostMethod pm = new PostMethod(url); + PostMethod pm = (PostMethod) createMethod("post", uri); pm.setRequestHeader("Content-Type", "application/json"); try { pm.setRequestEntity(new StringRequestEntity( @@ -352,6 +386,7 @@ public class NiciraNvpApi { if (pm.getStatusCode() != HttpStatus.SC_CREATED) { String errorMessage = responseToErrorMessage(pm); + pm.releaseConnection(); s_logger.error("Failed to create object : " + errorMessage); throw new NiciraNvpApiException("Failed to create object : " + errorMessage); } @@ -361,42 +396,42 @@ public class NiciraNvpApi { result = (T)gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType()); } catch (IOException e) { throw new NiciraNvpApiException("Failed to decode json response body", e); + } finally { + pm.releaseConnection(); } return result; } - private void executeDeleteObject(String uri) throws NiciraNvpApiException { - String url; - try { - url = new URL(_protocol, _host, uri).toString(); - } catch (MalformedURLException e) { - s_logger.error("Unable to build Nicira API URL", e); - throw new NiciraNvpApiException("Unable to build Nicira API URL", e); + protected void executeDeleteObject(String uri) throws NiciraNvpApiException { + if (_host == null || _host.isEmpty() || + _adminuser == null || _adminuser.isEmpty() || + _adminpass == null || _adminpass.isEmpty()) { + throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } - - DeleteMethod dm = new DeleteMethod(url); + + DeleteMethod dm = (DeleteMethod) createMethod("delete", uri); dm.setRequestHeader("Content-Type", "application/json"); executeMethod(dm); if (dm.getStatusCode() != HttpStatus.SC_NO_CONTENT) { String errorMessage = responseToErrorMessage(dm); + dm.releaseConnection(); s_logger.error("Failed to delete object : " + errorMessage); throw new NiciraNvpApiException("Failed to delete object : " + errorMessage); } + dm.releaseConnection(); } - private T executeRetrieveObject(Type returnObjectType, String uri, Map parameters) throws NiciraNvpApiException { - String url; - try { - url = new URL(_protocol, _host, uri).toString(); - } catch (MalformedURLException e) { - s_logger.error("Unable to build Nicira API URL", e); - throw new NiciraNvpApiException("Unable to build Nicira API URL", e); + protected T executeRetrieveObject(Type returnObjectType, String uri, Map parameters) throws NiciraNvpApiException { + if (_host == null || _host.isEmpty() || + _adminuser == null || _adminuser.isEmpty() || + _adminpass == null || _adminpass.isEmpty()) { + throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } - GetMethod gm = new GetMethod(url); + GetMethod gm = (GetMethod) createMethod("get", uri); gm.setRequestHeader("Content-Type", "application/json"); if (parameters != null && !parameters.isEmpty()) { List nameValuePairs = new ArrayList(parameters.size()); @@ -410,6 +445,7 @@ public class NiciraNvpApi { if (gm.getStatusCode() != HttpStatus.SC_OK) { String errorMessage = responseToErrorMessage(gm); + gm.releaseConnection(); s_logger.error("Failed to retrieve object : " + errorMessage); throw new NiciraNvpApiException("Failed to retrieve object : " + errorMessage); } @@ -421,24 +457,28 @@ public class NiciraNvpApi { } catch (IOException e) { s_logger.error("IOException while retrieving response body",e); throw new NiciraNvpApiException(e); + } finally { + gm.releaseConnection(); } - return returnValue; } - private void executeMethod(HttpMethodBase method) throws NiciraNvpApiException { + protected void executeMethod(HttpMethodBase method) throws NiciraNvpApiException { try { _client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { + method.releaseConnection(); // login and try again login(); _client.executeMethod(method); } } catch (HttpException e) { s_logger.error("HttpException caught while trying to connect to the Nicira NVP Controller", e); + method.releaseConnection(); throw new NiciraNvpApiException("API call to Nicira NVP Controller Failed", e); } catch (IOException e) { s_logger.error("IOException caught while trying to connect to the Nicira NVP Controller", e); + method.releaseConnection(); throw new NiciraNvpApiException("API call to Nicira NVP Controller Failed", e); } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java deleted file mode 100644 index acbf21e18af..00000000000 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SourceNatRule.java +++ /dev/null @@ -1,27 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network.nicira; - -/** - * - */ -public class SourceNatRule extends NatRule { - { - type = "SourceNatRule"; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java index c6359d37553..12ed72a1fd5 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java @@ -60,9 +60,7 @@ import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.host.Host; import com.cloud.host.Host.Type; -import com.cloud.network.nicira.Attachment; import com.cloud.network.nicira.ControlClusterStatus; -import com.cloud.network.nicira.DestinationNatRule; import com.cloud.network.nicira.L3GatewayAttachment; import com.cloud.network.nicira.LogicalRouterConfig; import com.cloud.network.nicira.LogicalRouterPort; @@ -77,50 +75,33 @@ import com.cloud.network.nicira.NiciraNvpTag; import com.cloud.network.nicira.PatchAttachment; import com.cloud.network.nicira.RouterNextHop; import com.cloud.network.nicira.SingleDefaultRouteImplictRoutingConfig; -import com.cloud.network.nicira.SourceNatRule; import com.cloud.network.nicira.TransportZoneBinding; import com.cloud.network.nicira.VifAttachment; import com.cloud.resource.ServerResource; -import edu.emory.mathcs.backport.java.util.Arrays; - public class NiciraNvpResource implements ServerResource { private static final Logger s_logger = Logger.getLogger(NiciraNvpResource.class); private String _name; - private String _ip; - private String _adminuser; - private String _adminpass; private String _guid; private String _zoneId; private int _numRetries; private NiciraNvpApi _niciraNvpApi; + protected NiciraNvpApi createNiciraNvpApi() { + return new NiciraNvpApi(); + } + @Override public boolean configure(String name, Map params) throws ConfigurationException { - + _name = (String) params.get("name"); if (_name == null) { throw new ConfigurationException("Unable to find name"); } - _ip = (String) params.get("ip"); - if (_ip == null) { - throw new ConfigurationException("Unable to find IP"); - } - - _adminuser = (String) params.get("adminuser"); - if (_adminuser == null) { - throw new ConfigurationException("Unable to find admin username"); - } - - _adminpass = (String) params.get("adminpass"); - if (_adminpass == null) { - throw new ConfigurationException("Unable to find admin password"); - } - _guid = (String)params.get("guid"); if (_guid == null) { throw new ConfigurationException("Unable to find the guid"); @@ -133,11 +114,24 @@ public class NiciraNvpResource implements ServerResource { _numRetries = 2; - try { - _niciraNvpApi = new NiciraNvpApi(_ip, _adminuser, _adminpass); - } catch (NiciraNvpApiException e) { - throw new ConfigurationException(e.getMessage()); + String ip = (String) params.get("ip"); + if (ip == null) { + throw new ConfigurationException("Unable to find IP"); } + + String adminuser = (String) params.get("adminuser"); + if (adminuser == null) { + throw new ConfigurationException("Unable to find admin username"); + } + + String adminpass = (String) params.get("adminpass"); + if (adminpass == null) { + throw new ConfigurationException("Unable to find admin password"); + } + + _niciraNvpApi = createNiciraNvpApi(); + _niciraNvpApi.setControllerAddress(ip); + _niciraNvpApi.setAdminCredentials(adminuser,adminpass); return true; } @@ -308,7 +302,13 @@ public class NiciraNvpResource implements ServerResource { LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true); LogicalSwitchPort newPort = _niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, logicalSwitchPort); - _niciraNvpApi.modifyLogicalSwitchPortAttachment(cmd.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid)); + try { + _niciraNvpApi.modifyLogicalSwitchPortAttachment(cmd.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid)); + } catch (NiciraNvpApiException ex) { + s_logger.warn("modifyLogicalSwitchPort failed after switchport was created, removing switchport"); + _niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), newPort.getUuid()); + throw (ex); // Rethrow the original exception + } return new CreateLogicalSwitchPortAnswer(cmd, true, "Logical switch port " + newPort.getUuid() + " created", newPort.getUuid()); } catch (NiciraNvpApiException e) { if (numRetries > 0) { @@ -405,6 +405,9 @@ public class NiciraNvpResource implements ServerResource { new RouterNextHop(publicNetworkNextHopIp))); lrc = _niciraNvpApi.createLogicalRouter(lrc); + // store the switchport for rollback + LogicalSwitchPort lsp = null; + try { // Create the outside port for the router LogicalRouterPort lrpo = new LogicalRouterPort(); @@ -434,7 +437,7 @@ public class NiciraNvpResource implements ServerResource { lrpi = _niciraNvpApi.createLogicalRouterPort(lrc.getUuid(),lrpi); // Create the inside port on the lswitch - LogicalSwitchPort lsp = new LogicalSwitchPort(truncate(routerName + "-inside-port", 40), tags, true); + lsp = new LogicalSwitchPort(truncate(routerName + "-inside-port", 40), tags, true); lsp = _niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, lsp); // Attach the inside router port to the lswitch port with a PatchAttachment @@ -446,7 +449,8 @@ public class NiciraNvpResource implements ServerResource { new PatchAttachment(lrpi.getUuid())); // Setup the source nat rule - SourceNatRule snr = new SourceNatRule(); + NatRule snr = new NatRule(); + snr.setType("SourceNatRule"); snr.setToSourceIpAddressMin(publicNetworkIpAddress.split("/")[0]); snr.setToSourceIpAddressMax(publicNetworkIpAddress.split("/")[0]); Match match = new Match(); @@ -455,10 +459,12 @@ public class NiciraNvpResource implements ServerResource { _niciraNvpApi.createLogicalRouterNatRule(lrc.getUuid(), snr); } catch (NiciraNvpApiException e) { // We need to destroy the router if we already created it - // this will also take care of any router ports - // TODO Clean up the switchport + // this will also take care of any router ports and rules try { _niciraNvpApi.deleteLogicalRouter(lrc.getUuid()); + if (lsp != null) { + _niciraNvpApi.deleteLogicalSwitchPort(logicalSwitchUuid, lsp.getUuid()); + } } catch (NiciraNvpApiException ex) {} throw e; @@ -499,7 +505,8 @@ public class NiciraNvpResource implements ServerResource { lrp.setIpAddresses(cmd.getPublicCidrs()); _niciraNvpApi.modifyLogicalRouterPort(cmd.getLogicalRouterUuid(), lrp); - return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, true, "Logical Router deleted (uuid " + cmd.getLogicalRouterUuid() + ")"); + return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, true, "Configured " + cmd.getPublicCidrs().size() + + " ip addresses on logical router uuid " + cmd.getLogicalRouterUuid()); } catch (NiciraNvpApiException e) { if (numRetries > 0) { return retry(cmd, --numRetries); @@ -519,56 +526,37 @@ public class NiciraNvpResource implements ServerResource { // Any other SourceNat rule should have a corresponding DestinationNat rule for (StaticNatRuleTO rule : cmd.getRules()) { - // Find if a DestinationNat rule exists for this rule - String insideIp = rule.getDstIp(); - String insideCidr = rule.getDstIp() + "/32"; - String outsideIp = rule.getSrcIp(); - String outsideCidr = rule.getSrcIp() + "/32"; - + + NatRule[] rulepair = generateStaticNatRulePair(rule.getDstIp(), rule.getSrcIp()); + NatRule incoming = null; NatRule outgoing = null; for (NatRule storedRule : existingRules.getResults()) { - if ("SourceNatRule".equals(storedRule.getType())) { - if (outsideIp.equals(storedRule.getToSourceIpAddressMin()) && - outsideIp.equals(storedRule.getToSourceIpAddressMax()) && - storedRule.getToSourcePortMin() == null) { - // The outgoing rule exists - outgoing = storedRule; - } - } - if ("DestinationNatRule".equals(storedRule.getType()) && - storedRule.getToDestinationPort() != null) { - // Skip PortForwarding rules - continue; - } - // Compare against Ip as it should be a /32 cidr and the /32 is omitted - if (outsideIp.equals(storedRule.getMatch().getDestinationIpAddresses())) { + if (storedRule.equalsIgnoreUuid(rulepair[1])) { + // The outgoing rule exists + outgoing = storedRule; + s_logger.debug("Found matching outgoing rule " + outgoing.getUuid()); + if (incoming != null) { + break; + } + } + else if (storedRule.equalsIgnoreUuid(rulepair[0])) { // The incoming rule exists incoming = storedRule; + s_logger.debug("Found matching incoming rule " + incoming.getUuid()); + if (outgoing != null) { + break; + } } } if (incoming != null && outgoing != null) { - if (insideIp.equals(incoming.getToDestinationIpAddressMin())) { - if (rule.revoked()) { - s_logger.debug("Deleting incoming rule " + incoming.getUuid()); - _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), incoming.getUuid()); - - s_logger.debug("Deleting outgoing rule " + outgoing.getUuid()); - _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), outgoing.getUuid()); - } - } - else { - s_logger.debug("Updating outgoing rule " + outgoing.getUuid()); - outgoing.setToDestinationIpAddressMin(insideIp); - outgoing.setToDestinationIpAddressMax(insideIp); - _niciraNvpApi.modifyLogicalRouterNatRule(cmd.getLogicalRouterUuid(), outgoing); - - s_logger.debug("Updating incoming rule " + outgoing.getUuid()); - incoming.setToSourceIpAddressMin(insideIp); - incoming.setToSourceIpAddressMax(insideIp); - _niciraNvpApi.modifyLogicalRouterNatRule(cmd.getLogicalRouterUuid(), incoming); - break; + if (rule.revoked()) { + s_logger.debug("Deleting incoming rule " + incoming.getUuid()); + _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), incoming.getUuid()); + + s_logger.debug("Deleting outgoing rule " + outgoing.getUuid()); + _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), outgoing.getUuid()); } } else { @@ -578,26 +566,17 @@ public class NiciraNvpResource implements ServerResource { break; } - // api createLogicalRouterNatRule - // create the dnat rule - Match m = new Match(); - m.setDestinationIpAddresses(outsideCidr); - DestinationNatRule newDnatRule = new DestinationNatRule(); - newDnatRule.setMatch(m); - newDnatRule.setToDestinationIpAddressMin(insideIp); - newDnatRule.setToDestinationIpAddressMax(insideIp); - newDnatRule = (DestinationNatRule) _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), newDnatRule); - s_logger.debug("Created " + natRuleToString(newDnatRule)); - - // create matching snat rule - m = new Match(); - m.setSourceIpAddresses(insideIp + "/32"); - SourceNatRule newSnatRule = new SourceNatRule(); - newSnatRule.setMatch(m); - newSnatRule.setToSourceIpAddressMin(outsideIp); - newSnatRule.setToSourceIpAddressMax(outsideIp); - newSnatRule = (SourceNatRule) _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), newSnatRule); - s_logger.debug("Created " + natRuleToString(newSnatRule)); + rulepair[0] = _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0]); + s_logger.debug("Created " + natRuleToString(rulepair[0])); + + try { + rulepair[1] = _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[1]); + s_logger.debug("Created " + natRuleToString(rulepair[1])); + } catch (NiciraNvpApiException ex) { + s_logger.debug("Failed to create SourceNatRule, rolling back DestinationNatRule"); + _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0].getUuid()); + throw ex; // Rethrow original exception + } } } @@ -610,7 +589,6 @@ public class NiciraNvpResource implements ServerResource { return new ConfigureStaticNatRulesOnLogicalRouterAnswer(cmd, e); } } - } private Answer executeRequest(ConfigurePortForwardingRulesOnLogicalRouterCommand cmd, int numRetries) { @@ -621,63 +599,45 @@ public class NiciraNvpResource implements ServerResource { // Any other SourceNat rule should have a corresponding DestinationNat rule for (PortForwardingRuleTO rule : cmd.getRules()) { - if (rule.isAlreadyAdded()) { + if (rule.isAlreadyAdded() && !rule.revoked()) { // Don't need to do anything continue; } - // Find if a DestinationNat rule exists for this rule - String insideIp = rule.getDstIp(); - String insideCidr = rule.getDstIp() + "/32"; - String outsideIp = rule.getSrcIp(); - String outsideCidr = rule.getSrcIp() + "/32"; + if (rule.getDstPortRange()[0] != rule.getDstPortRange()[1]) { + return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, false, "Nicira NVP doesn't support port ranges for port forwarding"); + } + + NatRule[] rulepair = generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(), rule.getProtocol()); NatRule incoming = null; NatRule outgoing = null; for (NatRule storedRule : existingRules.getResults()) { - if ("SourceNatRule".equals(storedRule.getType())) { - if (outsideIp.equals(storedRule.getToSourceIpAddressMin()) && - outsideIp.equals(storedRule.getToSourceIpAddressMax()) && - storedRule.getToSourcePortMin() == rule.getSrcPortRange()[0] && - storedRule.getToSourcePortMax() == rule.getSrcPortRange()[1]) { - // The outgoing rule exists - outgoing = storedRule; - } - } - else if ("DestinationNatRule".equals(storedRule.getType())) { - if (insideIp.equals(storedRule.getToDestinationIpAddressMin()) && - insideIp.equals(storedRule.getToDestinationIpAddressMax()) && - storedRule.getToDestinationPort() == rule.getDstPortRange()[0]) { - // The incoming rule exists - incoming = storedRule; - } + if (storedRule.equalsIgnoreUuid(rulepair[1])) { + // The outgoing rule exists + outgoing = storedRule; + s_logger.debug("Found matching outgoing rule " + outgoing.getUuid()); + if (incoming != null) { + break; + } + } + else if (storedRule.equalsIgnoreUuid(rulepair[0])) { + // The incoming rule exists + incoming = storedRule; + s_logger.debug("Found matching incoming rule " + incoming.getUuid()); + if (outgoing != null) { + break; + } } } if (incoming != null && outgoing != null) { - if (insideIp.equals(incoming.getToDestinationIpAddressMin())) { - if (rule.revoked()) { - s_logger.debug("Deleting incoming rule " + incoming.getUuid()); - _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), incoming.getUuid()); - - s_logger.debug("Deleting outgoing rule " + outgoing.getUuid()); - _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), outgoing.getUuid()); - } - } - else { - s_logger.debug("Updating outgoing rule " + outgoing.getUuid()); - outgoing.setToDestinationIpAddressMin(insideIp); - outgoing.setToDestinationIpAddressMax(insideIp); - outgoing.setToDestinationPort(rule.getDstPortRange()[0]); - _niciraNvpApi.modifyLogicalRouterNatRule(cmd.getLogicalRouterUuid(), outgoing); - - s_logger.debug("Updating incoming rule " + outgoing.getUuid()); - incoming.setToSourceIpAddressMin(insideIp); - incoming.setToSourceIpAddressMax(insideIp); - incoming.setToSourcePortMin(rule.getSrcPortRange()[0]); - incoming.setToSourcePortMax(rule.getSrcPortRange()[1]); - _niciraNvpApi.modifyLogicalRouterNatRule(cmd.getLogicalRouterUuid(), incoming); - break; + if (rule.revoked()) { + s_logger.debug("Deleting incoming rule " + incoming.getUuid()); + _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), incoming.getUuid()); + + s_logger.debug("Deleting outgoing rule " + outgoing.getUuid()); + _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), outgoing.getUuid()); } } else { @@ -687,45 +647,17 @@ public class NiciraNvpResource implements ServerResource { break; } - // api createLogicalRouterNatRule - // create the dnat rule - Match m = new Match(); - m.setDestinationIpAddresses(outsideCidr); - if ("tcp".equals(rule.getProtocol())) { - m.setProtocol(6); - } - else if ("udp".equals(rule.getProtocol())) { - m.setProtocol(17); - } - m.setDestinationPortMin(rule.getSrcPortRange()[0]); - m.setDestinationPortMax(rule.getSrcPortRange()[1]); - DestinationNatRule newDnatRule = new DestinationNatRule(); - newDnatRule.setMatch(m); - newDnatRule.setToDestinationIpAddressMin(insideIp); - newDnatRule.setToDestinationIpAddressMax(insideIp); - newDnatRule.setToDestinationPort(rule.getDstPortRange()[0]); - newDnatRule = (DestinationNatRule) _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), newDnatRule); - s_logger.debug("Created " + natRuleToString(newDnatRule)); + rulepair[0] = _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0]); + s_logger.debug("Created " + natRuleToString(rulepair[0])); - // create matching snat rule - m = new Match(); - m.setSourceIpAddresses(insideIp + "/32"); - if ("tcp".equals(rule.getProtocol())) { - m.setProtocol(6); + try { + rulepair[1] = _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[1]); + s_logger.debug("Created " + natRuleToString(rulepair[1])); + } catch (NiciraNvpApiException ex) { + s_logger.warn("NiciraNvpApiException during create call, rolling back previous create"); + _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0].getUuid()); + throw ex; // Rethrow the original exception } - else if ("udp".equals(rule.getProtocol())) { - m.setProtocol(17); - } - m.setSourcePortMin(rule.getDstPortRange()[0]); - m.setSourcePortMax(rule.getDstPortRange()[1]); - SourceNatRule newSnatRule = new SourceNatRule(); - newSnatRule.setMatch(m); - newSnatRule.setToSourceIpAddressMin(outsideIp); - newSnatRule.setToSourceIpAddressMax(outsideIp); - newSnatRule.setToSourcePortMin(rule.getSrcPortRange()[0]); - newSnatRule.setToSourcePortMax(rule.getSrcPortRange()[1]); - newSnatRule = (SourceNatRule) _niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), newSnatRule); - s_logger.debug("Created " + natRuleToString(newSnatRule)); } } @@ -750,9 +682,8 @@ public class NiciraNvpResource implements ServerResource { } private Answer retry(Command cmd, int numRetries) { - int numRetriesRemaining = numRetries - 1; - s_logger.warn("Retrying " + cmd.getClass().getSimpleName() + ". Number of retries remaining: " + numRetriesRemaining); - return executeRequest(cmd, numRetriesRemaining); + s_logger.warn("Retrying " + cmd.getClass().getSimpleName() + ". Number of retries remaining: " + numRetries); + return executeRequest(cmd, numRetries); } private String natRuleToString(NatRule rule) { @@ -769,7 +700,7 @@ public class NiciraNvpResource implements ServerResource { natRuleStr.append(" "); natRuleStr.append(m.getSourceIpAddresses()); natRuleStr.append(" ["); - natRuleStr.append(m.getSource_port_min()); + natRuleStr.append(m.getSourcePortMin()); natRuleStr.append("-"); natRuleStr.append(m.getSourcePortMax()); natRuleStr.append(" ] -> "); @@ -809,4 +740,59 @@ public class NiciraNvpResource implements ServerResource { } } + protected NatRule[] generateStaticNatRulePair(String insideIp, String outsideIp) { + NatRule[] rulepair = new NatRule[2]; + rulepair[0] = new NatRule(); + rulepair[0].setType("DestinationNatRule"); + rulepair[1] = new NatRule(); + rulepair[1].setType("SourceNatRule"); + + Match m = new Match(); + m.setDestinationIpAddresses(outsideIp); + rulepair[0].setMatch(m); + rulepair[0].setToDestinationIpAddressMin(insideIp); + rulepair[0].setToDestinationIpAddressMax(insideIp); + + // create matching snat rule + m = new Match(); + m.setSourceIpAddresses(insideIp); + rulepair[1].setMatch(m); + rulepair[1].setToSourceIpAddressMin(outsideIp); + rulepair[1].setToSourceIpAddressMax(outsideIp); + + return rulepair; + + } + + protected NatRule[] generatePortForwardingRulePair(String insideIp, int[] insidePorts, String outsideIp, int[] outsidePorts, String protocol) { + // Start with a basic static nat rule, then add port and protocol details + NatRule[] rulepair = generateStaticNatRulePair(insideIp, outsideIp); + + rulepair[0].setToDestinationPort(insidePorts[0]); + rulepair[0].getMatch().setDestinationPortMin(outsidePorts[0]); + rulepair[0].getMatch().setDestinationPortMax(outsidePorts[1]); + rulepair[0].getMatch().setEthertype("IPv4"); + if ("tcp".equals(protocol)) { + rulepair[0].getMatch().setProtocol(6); + } + else if ("udp".equals(protocol)) { + rulepair[0].getMatch().setProtocol(17); + } + + rulepair[1].setToSourcePortMin(outsidePorts[0]); + rulepair[1].setToSourcePortMax(outsidePorts[1]); + rulepair[1].getMatch().setSourcePortMin(insidePorts[0]); + rulepair[1].getMatch().setSourcePortMax(insidePorts[1]); + rulepair[1].getMatch().setEthertype("IPv4"); + if ("tcp".equals(protocol)) { + rulepair[1].getMatch().setProtocol(6); + } + else if ("udp".equals(protocol)) { + rulepair[1].getMatch().setProtocol(17); + } + + return rulepair; + + } + } diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java new file mode 100644 index 00000000000..f8d9652da60 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java @@ -0,0 +1,343 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.network.guru; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Collections; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import com.cloud.agent.AgentManager; +import com.cloud.agent.api.Command; +import com.cloud.agent.api.CreateLogicalSwitchAnswer; +import com.cloud.agent.api.DeleteLogicalSwitchAnswer; +import com.cloud.dc.DataCenter; +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.deploy.DeployDestination; +import com.cloud.deploy.DeploymentPlan; +import com.cloud.domain.Domain; +import com.cloud.exception.InsufficientVirtualNetworkCapcityException; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDao; +import com.cloud.network.Network; +import com.cloud.network.Network.GuestType; +import com.cloud.network.Network.Service; +import com.cloud.network.Network.State; +import com.cloud.network.NetworkManager; +import com.cloud.network.NetworkProfile; +import com.cloud.network.NetworkVO; +import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.NiciraNvpDeviceVO; +import com.cloud.network.PhysicalNetworkVO; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NiciraNvpDao; +import com.cloud.network.dao.PhysicalNetworkDao; +import com.cloud.offering.NetworkOffering; +import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; +import com.cloud.user.Account; +import com.cloud.vm.ReservationContext; + +import edu.emory.mathcs.backport.java.util.Arrays; + +public class NiciraNvpGuestNetworkGuruTest { + PhysicalNetworkDao physnetdao = mock (PhysicalNetworkDao.class); + NiciraNvpDao nvpdao = mock(NiciraNvpDao.class); + DataCenterDao dcdao = mock(DataCenterDao.class); + NetworkOfferingServiceMapDao nosd = mock(NetworkOfferingServiceMapDao.class); + AgentManager agentmgr = mock (AgentManager.class); + NetworkManager netmgr = mock (NetworkManager.class); + HostDao hostdao = mock (HostDao.class); + NetworkDao netdao = mock(NetworkDao.class); + NiciraNvpGuestNetworkGuru guru; + + + @Before + public void setUp() { + guru = new NiciraNvpGuestNetworkGuru(); + ((GuestNetworkGuru) guru)._physicalNetworkDao = physnetdao; + guru._physicalNetworkDao = physnetdao; + guru._niciraNvpDao = nvpdao; + guru._dcDao = dcdao; + guru._ntwkOfferingSrvcDao = nosd; + guru._networkMgr = netmgr; + guru._hostDao = hostdao; + guru._agentMgr = agentmgr; + guru._networkDao = netdao; + + DataCenterVO dc = mock(DataCenterVO.class); + when(dc.getNetworkType()).thenReturn(NetworkType.Advanced); + when(dc.getGuestNetworkCidr()).thenReturn("10.1.1.1/24"); + + when(dcdao.findById((Long) any())).thenReturn((DataCenterVO) dc); + } + + @Test + public void testCanHandle() { + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(true); + + assertTrue(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); + + // Not supported TrafficType != Guest + when(offering.getTrafficType()).thenReturn(TrafficType.Management); + assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); + + // Not supported: GuestType Shared + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Shared); + assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); + + // Not supported: Basic networking + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + assertFalse(guru.canHandle(offering, NetworkType.Basic, physnet) == true); + + // Not supported: IsolationMethod != STT + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "VLAN" })); + assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); + + } + + + @Test + public void testDesign() { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); + when(device.getId()).thenReturn(1L); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(true); + + DeploymentPlan plan = mock(DeploymentPlan.class); + Network network = mock(Network.class); + Account account = mock(Account.class); + + Network designednetwork = guru.design(offering, plan, network, account); + assertTrue(designednetwork != null); + assertTrue(designednetwork.getBroadcastDomainType() == BroadcastDomainType.Lswitch); + } + + @Test + public void testDesignNoElementOnPhysicalNetwork() { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Collections. emptyList()); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + DeploymentPlan plan = mock(DeploymentPlan.class); + Network network = mock(Network.class); + Account account = mock(Account.class); + + Network designednetwork = guru.design(offering, plan, network, account); + assertTrue(designednetwork == null); + } + + @Test + public void testDesignNoIsolationMethodSTT() { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "VLAN" })); + when(physnet.getId()).thenReturn(42L); + + NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Collections. emptyList()); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + DeploymentPlan plan = mock(DeploymentPlan.class); + Network network = mock(Network.class); + Account account = mock(Account.class); + + Network designednetwork = guru.design(offering, plan, network, account); + assertTrue(designednetwork == null); + } + + @Test + public void testDesignNoConnectivityInOffering() { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); + when(device.getId()).thenReturn(1L); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(false); + + DeploymentPlan plan = mock(DeploymentPlan.class); + Network network = mock(Network.class); + Account account = mock(Account.class); + + Network designednetwork = guru.design(offering, plan, network, account); + assertTrue(designednetwork == null); + } + + @Test + public void testImplement() throws InsufficientVirtualNetworkCapcityException { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); + when(device.getId()).thenReturn(1L); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(false); + + DeploymentPlan plan = mock(DeploymentPlan.class); + + NetworkVO network = mock(NetworkVO.class); + when(network.getName()).thenReturn("testnetwork"); + when(network.getState()).thenReturn(State.Implementing); + + DeployDestination dest = mock(DeployDestination.class); + + DataCenter dc = mock(DataCenter.class); + when(dest.getDataCenter()).thenReturn(dc); + + HostVO niciraHost = mock(HostVO.class); + when(hostdao.findById(anyLong())).thenReturn(niciraHost); + when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); + when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); + when(niciraHost.getId()).thenReturn(42L); + + when(netmgr.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(42L); + Domain dom = mock(Domain.class); + when(dom.getName()).thenReturn("domain"); + Account acc = mock(Account.class); + when(acc.getAccountName()).thenReturn("accountname"); + ReservationContext res = mock(ReservationContext.class); + when(res.getDomain()).thenReturn(dom); + when(res.getAccount()).thenReturn(acc); + + CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); + when(answer.getResult()).thenReturn(true); + when(agentmgr.easySend(eq(42L), (Command)any())).thenReturn(answer); + + Network implementednetwork = guru.implement(network, offering, dest, res); + assertTrue(implementednetwork != null); + verify(agentmgr, times(1)).easySend(eq(42L), (Command)any()); + } + + @Test + public void testShutdown() throws InsufficientVirtualNetworkCapcityException, URISyntaxException { + PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); + when(physnetdao.findById((Long) any())).thenReturn(physnet); + when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT" })); + when(physnet.getId()).thenReturn(42L); + + NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); + when(nvpdao.listByPhysicalNetwork(42L)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device })); + when(device.getId()).thenReturn(1L); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + when(nosd.areServicesSupportedByNetworkOffering(42L, Service.Connectivity)).thenReturn(false); + + DeploymentPlan plan = mock(DeploymentPlan.class); + + NetworkVO network = mock(NetworkVO.class); + when(network.getName()).thenReturn("testnetwork"); + when(network.getState()).thenReturn(State.Implementing); + when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); + when(network.getBroadcastUri()).thenReturn(new URI("lswitch:aaaaa")); + when(network.getPhysicalNetworkId()).thenReturn(42L); + when(netdao.findById(42L)).thenReturn(network); + + DeployDestination dest = mock(DeployDestination.class); + + DataCenter dc = mock(DataCenter.class); + when(dest.getDataCenter()).thenReturn(dc); + + HostVO niciraHost = mock(HostVO.class); + when(hostdao.findById(anyLong())).thenReturn(niciraHost); + when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); + when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); + when(niciraHost.getId()).thenReturn(42L); + + when(netmgr.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(42L); + Domain dom = mock(Domain.class); + when(dom.getName()).thenReturn("domain"); + Account acc = mock(Account.class); + when(acc.getAccountName()).thenReturn("accountname"); + ReservationContext res = mock(ReservationContext.class); + when(res.getDomain()).thenReturn(dom); + when(res.getAccount()).thenReturn(acc); + + DeleteLogicalSwitchAnswer answer = mock(DeleteLogicalSwitchAnswer.class); + when(answer.getResult()).thenReturn(true); + when(agentmgr.easySend(eq(42L), (Command)any())).thenReturn(answer); + + NetworkProfile implementednetwork = mock(NetworkProfile.class); + when(implementednetwork.getId()).thenReturn(42L); + when(implementednetwork.getBroadcastUri()).thenReturn(new URI("lswitch:aaaa")); + when(offering.getSpecifyVlan()).thenReturn(false); + + guru.shutdown(implementednetwork, offering); + verify(agentmgr, times(1)).easySend(eq(42L), (Command)any()); + verify(implementednetwork, times(1)).setBroadcastUri(null); + } +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java similarity index 57% rename from plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java rename to plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java index f1ea9052a41..88c5402822d 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/DestinationNatRule.java +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java @@ -16,9 +16,32 @@ // under the License. package com.cloud.network.nicira; -public class DestinationNatRule extends NatRule { - { - type = "DestinationNatRule"; - } +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.google.gson.Gson; + +public class NatRuleTest { + Gson gson = new Gson(); + + @Test + public void testNatRuleEncoding() { + NatRule rn1 = new NatRule(); + rn1.setToDestinationIpAddressMax("10.10.10.10"); + rn1.setToDestinationIpAddressMin("10.10.10.10"); + rn1.setToDestinationPort(80); + Match mr1 = new Match(); + mr1.setSourceIpAddresses("11.11.11.11/24"); + mr1.setEthertype("IPv4"); + mr1.setProtocol(6); + rn1.setMatch(mr1); + + + String jsonString = gson.toJson(rn1); + NatRule dnr = gson.fromJson(jsonString, NatRule.class); + + assertTrue(rn1.equals(dnr)); + } } diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java new file mode 100644 index 00000000000..42eb96e42d8 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NiciraNvpApiTest.java @@ -0,0 +1,306 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.network.nicira; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import java.io.IOException; +import java.util.Collections; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.methods.DeleteMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.commons.httpclient.params.HttpClientParams; +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; + +public class NiciraNvpApiTest { + NiciraNvpApi _api; + HttpClient _client = mock(HttpClient.class); + HttpMethod _method; + + @Before + public void setUp() { + HttpClientParams hmp = mock(HttpClientParams.class); + when (_client.getParams()).thenReturn(hmp); + _api = new NiciraNvpApi() { + @Override + protected HttpClient createHttpClient() { + return _client; + } + + @Override + protected HttpMethod createMethod(String type, String uri) { + return _method; + } + }; + _api.setAdminCredentials("admin", "adminpass"); + _api.setControllerAddress("localhost"); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteLoginWithoutHostname() throws NiciraNvpApiException { + _api.setControllerAddress(null); + _api.login(); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteLoginWithoutCredentials() throws NiciraNvpApiException { + _api.setAdminCredentials(null, null); + _api.login(); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteUpdateObjectWithoutHostname() throws NiciraNvpApiException { + _api.setControllerAddress(null); + _api.executeUpdateObject(new String(), "/", Collections. emptyMap()); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteUpdateObjectWithoutCredentials() throws NiciraNvpApiException { + _api.setAdminCredentials(null, null); + _api.executeUpdateObject(new String(), "/", Collections. emptyMap()); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteCreateObjectWithoutHostname() throws NiciraNvpApiException { + _api.setControllerAddress(null); + _api.executeCreateObject(new String(), String.class, "/", Collections. emptyMap()); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteCreateObjectWithoutCredentials() throws NiciraNvpApiException { + _api.setAdminCredentials(null, null); + _api.executeCreateObject(new String(), String.class, "/", Collections. emptyMap()); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteDeleteObjectWithoutHostname() throws NiciraNvpApiException { + _api.setControllerAddress(null); + _api.executeDeleteObject("/"); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteDeleteObjectWithoutCredentials() throws NiciraNvpApiException { + _api.setAdminCredentials(null, null); + _api.executeDeleteObject("/"); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteRetrieveObjectWithoutHostname() throws NiciraNvpApiException { + _api.setControllerAddress(null); + _api.executeRetrieveObject(String.class, "/", Collections. emptyMap()); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteRetrieveObjectWithoutCredentials() throws NiciraNvpApiException { + _api.setAdminCredentials(null, null); + _api.executeDeleteObject("/"); + } + + @Test + public void executeMethodTest() throws NiciraNvpApiException { + GetMethod gm = mock(GetMethod.class); + + when(gm.getStatusCode()).thenReturn(HttpStatus.SC_OK); + _api.executeMethod(gm); + verify(gm, times(1)).getStatusCode(); + } + + /* Bit of a roundabout way to ensure that login is called after an un authorized result + * It not possible to properly mock login() + */ + @Test (expected=NiciraNvpApiException.class) + public void executeMethodTestWithLogin() throws NiciraNvpApiException, HttpException, IOException { + GetMethod gm = mock(GetMethod.class); + when(_client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); + when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED); + _api.executeMethod(gm); + verify(gm, times(1)).getStatusCode(); + } + + @Test + public void testExecuteCreateObject() throws NiciraNvpApiException, IOException { + LogicalSwitch ls = new LogicalSwitch(); + _method = mock(PostMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED); + when(_method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); + ls = _api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections. emptyMap()); + assertTrue("aaaa".equals(ls.getUuid())); + verify(_method, times(1)).releaseConnection(); + + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteCreateObjectFailure() throws NiciraNvpApiException, IOException { + LogicalSwitch ls = new LogicalSwitch(); + _method = mock(PostMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(_method.getResponseHeader("Content-Type")).thenReturn(header); + when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + when(_method.isRequestSent()).thenReturn(true); + try { + ls = _api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections. emptyMap()); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteCreateObjectException() throws NiciraNvpApiException, IOException { + LogicalSwitch ls = new LogicalSwitch(); + when(_client.executeMethod((HttpMethod) any())).thenThrow(new HttpException()); + _method = mock(PostMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(_method.getResponseHeader("Content-Type")).thenReturn(header); + when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + try { + ls = _api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections. emptyMap()); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } + + @Test + public void testExecuteUpdateObject() throws NiciraNvpApiException, IOException { + LogicalSwitch ls = new LogicalSwitch(); + _method = mock(PutMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + _api.executeUpdateObject(ls, "/", Collections. emptyMap()); + verify(_method, times(1)).releaseConnection(); + verify(_client, times(1)).executeMethod(_method); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteUpdateObjectFailure() throws NiciraNvpApiException, IOException { + LogicalSwitch ls = new LogicalSwitch(); + _method = mock(PutMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(_method.getResponseHeader("Content-Type")).thenReturn(header); + when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + when(_method.isRequestSent()).thenReturn(true); + try { + _api.executeUpdateObject(ls, "/", Collections. emptyMap()); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteUpdateObjectException() throws NiciraNvpApiException, IOException { + LogicalSwitch ls = new LogicalSwitch(); + _method = mock(PutMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + when(_client.executeMethod((HttpMethod) any())).thenThrow(new IOException()); + try { + _api.executeUpdateObject(ls, "/", Collections. emptyMap()); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } + + @Test + public void testExecuteDeleteObject() throws NiciraNvpApiException, IOException { + _method = mock(DeleteMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); + _api.executeDeleteObject("/"); + verify(_method, times(1)).releaseConnection(); + verify(_client, times(1)).executeMethod(_method); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteDeleteObjectFailure() throws NiciraNvpApiException, IOException { + _method = mock(DeleteMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(_method.getResponseHeader("Content-Type")).thenReturn(header); + when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + when(_method.isRequestSent()).thenReturn(true); + try { + _api.executeDeleteObject("/"); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteDeleteObjectException() throws NiciraNvpApiException, IOException { + _method = mock(DeleteMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); + when(_client.executeMethod((HttpMethod) any())).thenThrow(new HttpException()); + try { + _api.executeDeleteObject("/"); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } + + @Test + public void testExecuteRetrieveObject() throws NiciraNvpApiException, IOException { + _method = mock(GetMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + when(_method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); + _api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); + verify(_method, times(1)).releaseConnection(); + verify(_client, times(1)).executeMethod(_method); + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteRetrieveObjectFailure() throws NiciraNvpApiException, IOException { + _method = mock(GetMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + when(_method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); + Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(_method.getResponseHeader("Content-Type")).thenReturn(header); + when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + when(_method.isRequestSent()).thenReturn(true); + try { + _api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } + + @Test (expected=NiciraNvpApiException.class) + public void testExecuteRetrieveObjectException() throws NiciraNvpApiException, IOException { + _method = mock(GetMethod.class); + when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + when(_method.getResponseBodyAsString()).thenReturn("{ \"uuid\" : \"aaaa\" }"); + when(_client.executeMethod((HttpMethod) any())).thenThrow(new HttpException()); + try { + _api.executeRetrieveObject(LogicalSwitch.class, "/", Collections. emptyMap()); + } finally { + verify(_method, times(1)).releaseConnection(); + } + } + +} diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java new file mode 100644 index 00000000000..e3789108f34 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java @@ -0,0 +1,830 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.network.resource; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.naming.ConfigurationException; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentMatcher; + +import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterAnswer; +import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterCommand; +import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer; +import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand; +import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer; +import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand; +import com.cloud.agent.api.CreateLogicalRouterAnswer; +import com.cloud.agent.api.CreateLogicalRouterCommand; +import com.cloud.agent.api.CreateLogicalSwitchAnswer; +import com.cloud.agent.api.CreateLogicalSwitchCommand; +import com.cloud.agent.api.CreateLogicalSwitchPortAnswer; +import com.cloud.agent.api.CreateLogicalSwitchPortCommand; +import com.cloud.agent.api.DeleteLogicalRouterAnswer; +import com.cloud.agent.api.DeleteLogicalRouterCommand; +import com.cloud.agent.api.DeleteLogicalSwitchAnswer; +import com.cloud.agent.api.DeleteLogicalSwitchCommand; +import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer; +import com.cloud.agent.api.DeleteLogicalSwitchPortCommand; +import com.cloud.agent.api.FindLogicalSwitchPortAnswer; +import com.cloud.agent.api.FindLogicalSwitchPortCommand; +import com.cloud.agent.api.PingCommand; +import com.cloud.agent.api.StartupCommand; +import com.cloud.agent.api.UpdateLogicalSwitchPortAnswer; +import com.cloud.agent.api.UpdateLogicalSwitchPortCommand; +import com.cloud.agent.api.to.PortForwardingRuleTO; +import com.cloud.agent.api.to.StaticNatRuleTO; +import com.cloud.host.Host; +import com.cloud.network.nicira.Attachment; +import com.cloud.network.nicira.ControlClusterStatus; +import com.cloud.network.nicira.LogicalRouterConfig; +import com.cloud.network.nicira.LogicalRouterPort; +import com.cloud.network.nicira.LogicalSwitch; +import com.cloud.network.nicira.LogicalSwitchPort; +import com.cloud.network.nicira.NatRule; +import com.cloud.network.nicira.NiciraNvpApi; +import com.cloud.network.nicira.NiciraNvpApiException; +import com.cloud.network.nicira.NiciraNvpList; + +public class NiciraNvpResourceTest { + NiciraNvpApi _nvpApi = mock(NiciraNvpApi.class); + NiciraNvpResource _resource; + Map _parameters; + + @Before + public void setUp() throws ConfigurationException { + _resource = new NiciraNvpResource() { + protected NiciraNvpApi createNiciraNvpApi() { + return _nvpApi; + } + }; + + _parameters = new HashMap(); + _parameters.put("name","nvptestdevice"); + _parameters.put("ip","127.0.0.1"); + _parameters.put("adminuser","adminuser"); + _parameters.put("guid", "aaaaa-bbbbb-ccccc"); + _parameters.put("zoneId", "blublub"); + _parameters.put("adminpass","adminpass"); + } + + @Test (expected=ConfigurationException.class) + public void resourceConfigureFailure() throws ConfigurationException { + _resource.configure("NiciraNvpResource", Collections.emptyMap()); + } + + @Test + public void resourceConfigure() throws ConfigurationException { + _resource.configure("NiciraNvpResource", _parameters); + + verify(_nvpApi).setAdminCredentials("adminuser", "adminpass"); + verify(_nvpApi).setControllerAddress("127.0.0.1"); + + assertTrue("nvptestdevice".equals(_resource.getName())); + + /* Pretty lame test, but here to assure this plugin fails + * if the type name ever changes from L2Networking + */ + assertTrue(_resource.getType() == Host.Type.L2Networking); + } + + @Test + public void testInitialization() throws ConfigurationException { + _resource.configure("NiciraNvpResource", _parameters); + + StartupCommand[] sc = _resource.initialize(); + assertTrue(sc.length ==1); + assertTrue("aaaaa-bbbbb-ccccc".equals(sc[0].getGuid())); + assertTrue("nvptestdevice".equals(sc[0].getName())); + assertTrue("blublub".equals(sc[0].getDataCenter())); + } + + @Test + public void testPingCommandStatusOk() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + ControlClusterStatus ccs = mock(ControlClusterStatus.class); + when(ccs.getClusterStatus()).thenReturn("stable"); + when(_nvpApi.getControlClusterStatus()).thenReturn(ccs); + + PingCommand ping = _resource.getCurrentStatus(42); + assertTrue(ping != null); + assertTrue(ping.getHostId() == 42); + assertTrue(ping.getHostType() == Host.Type.L2Networking); + } + + @Test + public void testPingCommandStatusFail() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + ControlClusterStatus ccs = mock(ControlClusterStatus.class); + when(ccs.getClusterStatus()).thenReturn("unstable"); + when(_nvpApi.getControlClusterStatus()).thenReturn(ccs); + + PingCommand ping = _resource.getCurrentStatus(42); + assertTrue(ping == null); + } + + @Test + public void testPingCommandStatusApiException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + ControlClusterStatus ccs = mock(ControlClusterStatus.class); + when(ccs.getClusterStatus()).thenReturn("unstable"); + when(_nvpApi.getControlClusterStatus()).thenThrow(new NiciraNvpApiException()); + + PingCommand ping = _resource.getCurrentStatus(42); + assertTrue(ping == null); + } + + @Test + public void testRetries() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalSwitch ls = mock(LogicalSwitch.class); + when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); + when(_nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenThrow(new NiciraNvpApiException()).thenThrow(new NiciraNvpApiException()).thenReturn(ls); + + CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)_parameters.get("guid"), "stt", "loigicalswitch","owner"); + CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) _resource.executeRequest(clsc); + assertTrue(clsa.getResult()); + } + + @Test + public void testCreateLogicalSwitch() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalSwitch ls = mock(LogicalSwitch.class); + when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); + when(_nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenReturn(ls); + + CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)_parameters.get("guid"), "stt", "loigicalswitch","owner"); + CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) _resource.executeRequest(clsc); + assertTrue(clsa.getResult()); + assertTrue("cccc".equals(clsa.getLogicalSwitchUuid())); + } + + @Test + public void testCreateLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalSwitch ls = mock(LogicalSwitch.class); + when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); + when(_nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenThrow(new NiciraNvpApiException()); + + CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)_parameters.get("guid"), "stt", "loigicalswitch","owner"); + CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) _resource.executeRequest(clsc); + assertFalse(clsa.getResult()); + } + + @Test + public void testDeleteLogicalSwitch() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); + DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer) _resource.executeRequest(dlsc); + assertTrue(dlsa.getResult()); + } + + @Test + public void testDeleteLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + doThrow(new NiciraNvpApiException()).when(_nvpApi).deleteLogicalSwitch((String)any()); + + DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); + DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer) _resource.executeRequest(dlsc); + assertFalse(dlsa.getResult()); + } + + @Test + public void testCreateLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + when(lsp.getUuid()).thenReturn("eeee"); + when(_nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenReturn(lsp); + + CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); + CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) _resource.executeRequest(clspc); + assertTrue(clspa.getResult()); + assertTrue("eeee".equals(clspa.getLogicalSwitchPortUuid())); + + } + + @Test + public void testCreateLogicalSwitchPortApiExceptionInCreate() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + when(lsp.getUuid()).thenReturn("eeee"); + when(_nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenThrow(new NiciraNvpApiException()); + + CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); + CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) _resource.executeRequest(clspc); + assertFalse(clspa.getResult()); + } + + @Test + public void testCreateLogicalSwitchPortApiExceptionInModify() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + when(lsp.getUuid()).thenReturn("eeee"); + when(_nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenReturn(lsp); + doThrow(new NiciraNvpApiException()).when(_nvpApi).modifyLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any()); + + + CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); + CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) _resource.executeRequest(clspc); + assertFalse(clspa.getResult()); + verify(_nvpApi, atLeastOnce()).deleteLogicalSwitchPort((String) any(), (String) any()); + } + + @Test + public void testDeleteLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + doThrow(new NiciraNvpApiException()).when(_nvpApi).deleteLogicalSwitchPort((String) any(), (String) any()); + DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer) _resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa","bbbb")); + assertFalse(dlspa.getResult()); + } + + @Test + public void testUpdateLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + doThrow(new NiciraNvpApiException()).when(_nvpApi).modifyLogicalSwitchPortAttachment((String) any(), (String) any(), (Attachment) any()); + UpdateLogicalSwitchPortAnswer dlspa = (UpdateLogicalSwitchPortAnswer) _resource.executeRequest( + new UpdateLogicalSwitchPortCommand("aaaa","bbbb","cccc","owner","nicname")); + assertFalse(dlspa.getResult()); + } + + @Test + public void testFindLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + @SuppressWarnings("unchecked") + NiciraNvpList lspl = (NiciraNvpList)mock(NiciraNvpList.class); + when(lspl.getResultCount()).thenReturn(1); + when(_nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); + + FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) _resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); + assertTrue(flspa.getResult()); + } + + @Test + public void testFindLogicalSwitchPortNotFound() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + @SuppressWarnings("unchecked") + NiciraNvpList lspl = (NiciraNvpList)mock(NiciraNvpList.class); + when(lspl.getResultCount()).thenReturn(0); + when(_nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); + + FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) _resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); + assertFalse(flspa.getResult()); + } + + @Test + public void testFindLogicalSwitchPortApiException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + when(_nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenThrow(new NiciraNvpApiException()); + + FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) _resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); + assertFalse(flspa.getResult()); + } + + @Test + public void testCreateLogicalRouter() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); + LogicalRouterPort lrp = mock(LogicalRouterPort.class); + LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + when(lrc.getUuid()).thenReturn("ccccc"); + when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee"); + when(lsp.getUuid()).thenReturn("fffff"); + when(_nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc); + when(_nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp); + when(_nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp); + CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); + CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) _resource.executeRequest(clrc); + + assertTrue(clra.getResult()); + assertTrue("ccccc".equals(clra.getLogicalRouterUuid())); + verify(_nvpApi, atLeast(1)).createLogicalRouterNatRule((String) any(), (NatRule) any()); + } + + @Test + public void testCreateLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + when(_nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenThrow(new NiciraNvpApiException()); + CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); + CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) _resource.executeRequest(clrc); + + assertFalse(clra.getResult()); + } + + @Test + public void testCreateLogicalRouterApiExceptionRollbackRouter() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); + when(lrc.getUuid()).thenReturn("ccccc"); + when(_nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc); + when(_nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenThrow(new NiciraNvpApiException()); + CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); + CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) _resource.executeRequest(clrc); + + assertFalse(clra.getResult()); + verify(_nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc")); + } + + @Test + public void testCreateLogicalRouterApiExceptionRollbackRouterAndSwitchPort() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); + LogicalRouterPort lrp = mock(LogicalRouterPort.class); + LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); + when(lrc.getUuid()).thenReturn("ccccc"); + when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee"); + when(lsp.getUuid()).thenReturn("fffff"); + when(_nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc); + when(_nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp); + when(_nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp); + when(_nvpApi.createLogicalRouterNatRule((String) any(), (NatRule)any())).thenThrow(new NiciraNvpApiException()); + CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); + CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) _resource.executeRequest(clrc); + + assertFalse(clra.getResult()); + verify(_nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc")); + verify(_nvpApi, atLeast(1)).deleteLogicalSwitchPort(eq("bbbbb"), eq("fffff")); + } + + @Test + public void testDeleteLogicalRouterApiException() throws ConfigurationException,NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + doThrow(new NiciraNvpApiException()).when(_nvpApi).deleteLogicalRouter(eq("aaaaa")); + DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer) _resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa")); + assertFalse(dlspa.getResult()); + } + + @Test + public void testConfigurePublicIpsOnLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + + ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class); + @SuppressWarnings("unchecked") + NiciraNvpList list = mock(NiciraNvpList.class); + + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb"); + doThrow(new NiciraNvpApiException()).when(_nvpApi).modifyLogicalRouterPort((String) any(), (LogicalRouterPort) any()); + when(_nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa","bbbbb")).thenReturn(list); + + ConfigurePublicIpsOnLogicalRouterAnswer answer = + (ConfigurePublicIpsOnLogicalRouterAnswer) _resource.executeRequest(cmd); + assertFalse(answer.getResult()); + + } + + @Test + public void testConfigureStaticNatRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); + StaticNatRuleTO rule = new StaticNatRuleTO(1,"11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + // Mock the api create calls + NatRule[] rulepair = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + rulepair[0].setUuid("bbbbb"); + rulepair[1].setUuid("ccccc"); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + + ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertTrue(a.getResult()); + verify(_nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + NatRule rule = (NatRule) argument; + if (rule.getType().equals("DestinationNatRule") && + rule.getToDestinationIpAddressMin().equals("10.10.10.10")) { + return true; + } + if (rule.getType().equals("SourceNatRule") && + rule.getToSourceIpAddressMin().equals("11.11.11.11")) { + return true; + } + return false; + } })); + } + + @Test + public void testConfigureStaticNatRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); + StaticNatRuleTO rule = new StaticNatRuleTO(1,"11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api create calls + NatRule[] rulepair = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + rulepair[0].setUuid("bbbbb"); + rulepair[1].setUuid("ccccc"); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(storedRules.getResultCount()).thenReturn(2); + when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertTrue(a.getResult()); + verify(_nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + NatRule rule = (NatRule) argument; + if (rule.getType().equals("DestinationNatRule") && + rule.getToDestinationIpAddressMin().equals("10.10.10.10")) { + return true; + } + if (rule.getType().equals("SourceNatRule") && + rule.getToSourceIpAddressMin().equals("11.11.11.11")) { + return true; + } + return false; + } })); + } + + @Test + public void testConfigureStaticNatRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); + StaticNatRuleTO rule = new StaticNatRuleTO(1,"11.11.11.11", null, null, "10.10.10.10", null, null, null, true, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api create calls + NatRule[] rulepair = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + rulepair[0].setUuid("bbbbb"); + rulepair[1].setUuid("ccccc"); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(storedRules.getResultCount()).thenReturn(2); + when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertTrue(a.getResult()); + verify(_nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + String uuid = (String) argument; + if ("bbbbb".equals(uuid) || "ccccc".equals(uuid)) { + return true; + } + return false; + } })); + } + + @Test + public void testConfigureStaticNatRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); + StaticNatRuleTO rule = new StaticNatRuleTO(1,"11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api create calls + NatRule[] rulepair = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + rulepair[0].setUuid("bbbbb"); + rulepair[1].setUuid("ccccc"); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(storedRules.getResultCount()).thenReturn(0); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertFalse(a.getResult()); + verify(_nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq("bbbbb")); + } + + @Test + public void testConfigurePortForwardingRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); + PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + // Mock the api create calls + NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80}, "tcp"); + rulepair[0].setUuid("bbbbb"); + rulepair[1].setUuid("ccccc"); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + + ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertTrue(a.getResult()); + verify(_nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + NatRule rule = (NatRule) argument; + if (rule.getType().equals("DestinationNatRule") && + rule.getToDestinationIpAddressMin().equals("10.10.10.10")) { + return true; + } + if (rule.getType().equals("SourceNatRule") && + rule.getToSourceIpAddressMin().equals("11.11.11.11")) { + return true; + } + return false; + } })); + } + + @Test + public void testConfigurePortForwardingRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); + PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, true); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api create calls + NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80}, "tcp"); + rulepair[0].setUuid("bbbbb"); + rulepair[1].setUuid("ccccc"); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(storedRules.getResultCount()).thenReturn(2); + when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertTrue(a.getResult()); + verify(_nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + NatRule rule = (NatRule) argument; + if (rule.getType().equals("DestinationNatRule") && + rule.getToDestinationIpAddressMin().equals("10.10.10.10")) { + return true; + } + if (rule.getType().equals("SourceNatRule") && + rule.getToSourceIpAddressMin().equals("11.11.11.11")) { + return true; + } + return false; + } })); + } + + @Test + public void testConfigurePortForwardingRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); + PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", true, true); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api create calls + NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80}, "tcp"); + rulepair[0].setUuid("bbbbb"); + rulepair[1].setUuid("ccccc"); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(storedRules.getResultCount()).thenReturn(2); + when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertTrue(a.getResult()); + verify(_nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + String uuid = (String) argument; + if ("bbbbb".equals(uuid) || "ccccc".equals(uuid)) { + return true; + } + return false; + } })); + } + + @Test + public void testConfigurePortForwardingRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); + PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api create calls + NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80}, "tcp"); + rulepair[0].setUuid("bbbbb"); + rulepair[1].setUuid("ccccc"); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(storedRules.getResultCount()).thenReturn(0); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + assertFalse(a.getResult()); + verify(_nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq("bbbbb")); + } + + @Test + public void testConfigurePortForwardingRulesOnLogicalRouterPortRange() throws ConfigurationException, NiciraNvpApiException { + _resource.configure("NiciraNvpResource", _parameters); + /* StaticNat + * Outside IP: 11.11.11.11 + * Inside IP: 10.10.10.10 + */ + + // Mock the command + ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); + PortForwardingRuleTO rule = new PortForwardingRuleTO(1,"11.11.11.11", 80, 85, "10.10.10.10", 80, 85, "tcp", false, false); + List rules = new ArrayList(); + rules.add(rule); + when(cmd.getRules()).thenReturn(rules); + when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); + + // Mock the api find call + @SuppressWarnings("unchecked") + NiciraNvpList storedRules = mock(NiciraNvpList.class); + when(_nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); + + // Mock the api create calls + NatRule[] rulepair = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 80, 85 }, "11.11.11.11", new int[] { 80, 85}, "tcp"); + rulepair[0].setUuid("bbbbb"); + rulepair[1].setUuid("ccccc"); + when(_nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); + + ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _resource.executeRequest(cmd); + + // The expected result is false, Nicira does not support port ranges in DNAT + assertFalse(a.getResult()); + + } + + @Test + public void testGenerateStaticNatRulePair() { + NatRule[] rules = _resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); + assertTrue("DestinationNatRule".equals(rules[0].getType())); + assertTrue("SourceNatRule".equals(rules[1].getType())); + + assertTrue(rules[0].getToDestinationIpAddressMin().equals("10.10.10.10") && rules[0].getToDestinationIpAddressMax().equals("10.10.10.10")); + assertTrue(rules[0].getToDestinationPort() == null); + assertTrue(rules[0].getMatch().getDestinationIpAddresses().equals("11.11.11.11")); + + assertTrue(rules[1].getToSourceIpAddressMin().equals("11.11.11.11") && rules[1].getToSourceIpAddressMax().equals("11.11.11.11")); + assertTrue(rules[1].getToSourcePortMin() == null && rules[1].getToSourcePortMax() == null); + assertTrue(rules[1].getMatch().getSourceIpAddresses().equals("10.10.10.10")); + } + + @Test + public void testGeneratePortForwardingRulePair() { + NatRule[] rules = _resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp" ); + assertTrue("DestinationNatRule".equals(rules[0].getType())); + assertTrue("SourceNatRule".equals(rules[1].getType())); + + assertTrue(rules[0].getToDestinationIpAddressMin().equals("10.10.10.10") && rules[0].getToDestinationIpAddressMax().equals("10.10.10.10")); + assertTrue(rules[0].getToDestinationPort() == 8080); + assertTrue(rules[0].getMatch().getDestinationIpAddresses().equals("11.11.11.11")); + assertTrue(rules[0].getMatch().getDestinationPortMin() == 80 && rules[0].getMatch().getDestinationPortMax() == 80); + assertTrue(rules[0].getMatch().getEthertype().equals("IPv4") && rules[0].getMatch().getProtocol() == 6); + + assertTrue(rules[1].getToSourceIpAddressMin().equals("11.11.11.11") && rules[1].getToSourceIpAddressMax().equals("11.11.11.11")); + assertTrue(rules[1].getToSourcePortMin() == 80 && rules[1].getToSourcePortMax() == 80); + assertTrue(rules[1].getMatch().getSourceIpAddresses().equals("10.10.10.10")); + assertTrue(rules[1].getMatch().getSourcePortMin() == 8080 && rules[1].getMatch().getSourcePortMax() == 8080); + assertTrue(rules[1].getMatch().getEthertype().equals("IPv4") && rules[1].getMatch().getProtocol() == 6); + } +} + diff --git a/plugins/network-elements/ovs/build.xml b/plugins/network-elements/ovs/build.xml deleted file mode 100755 index 718720b7736..00000000000 --- a/plugins/network-elements/ovs/build.xml +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java b/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java index b7a978e72d6..5e8639c3188 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java +++ b/plugins/network-elements/ovs/src/com/cloud/network/element/OvsElement.java @@ -16,7 +16,6 @@ // under the License. package com.cloud.network.element; -import java.util.List; import java.util.Map; import java.util.Set; @@ -65,18 +64,18 @@ public class OvsElement extends AdapterBase implements NetworkElement { @Override public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { //Consider actually implementing the network here - return true; + return true; } @Override public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, - InsufficientCapacityException { + throws ConcurrentOperationException, ResourceUnavailableException, + InsufficientCapacityException { if (nic.getBroadcastType() != Networks.BroadcastDomainType.Vswitch) { return true; } @@ -116,7 +115,7 @@ public class OvsElement extends AdapterBase implements NetworkElement { @Override public boolean isReady(PhysicalNetworkServiceProvider provider) { - return true; + return true; } @Override diff --git a/plugins/pom.xml b/plugins/pom.xml index 2009302423e..af8621028db 100644 --- a/plugins/pom.xml +++ b/plugins/pom.xml @@ -38,6 +38,7 @@ hypervisors/ovm hypervisors/xen hypervisors/kvm + hypervisors/simulator network-elements/elastic-loadbalancer network-elements/ovs network-elements/nicira-nvp @@ -46,6 +47,7 @@ user-authenticators/md5 user-authenticators/plain-text user-authenticators/sha256salted + network-elements/dns-notifier @@ -123,6 +125,17 @@ hypervisors/vmware + + simulator + + + nonoss + + + + hypervisors/simulator + + diff --git a/plugins/storage-allocators/random/build.xml b/plugins/storage-allocators/random/build.xml deleted file mode 100755 index e5fcebebbc8..00000000000 --- a/plugins/storage-allocators/random/build.xml +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/user-authenticators/ldap/build.xml b/plugins/user-authenticators/ldap/build.xml deleted file mode 100755 index c0ae8b89d18..00000000000 --- a/plugins/user-authenticators/ldap/build.xml +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/user-authenticators/md5/build.xml b/plugins/user-authenticators/md5/build.xml deleted file mode 100755 index eee2fc70bff..00000000000 --- a/plugins/user-authenticators/md5/build.xml +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/user-authenticators/plain-text/build.xml b/plugins/user-authenticators/plain-text/build.xml deleted file mode 100755 index a59bb5d9e65..00000000000 --- a/plugins/user-authenticators/plain-text/build.xml +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - Cloud Stack ant build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/pom.xml b/pom.xml index 1fc60f93317..fa5288f119e 100644 --- a/pom.xml +++ b/pom.xml @@ -82,7 +82,10 @@ 1.2 1.0-20081010.060147 4.1 - + 1.9.5 + 1.3.21.1 + 2.6 + 1.4 @@ -206,8 +209,12 @@ CHANGES INSTALL.md + .idea/ + *.log + **/*.patch **/.classpath **/.project + **/*.iml **/.settings/** .metadata/** .git/** diff --git a/scripts/storage/qcow2/create_private_template.sh b/scripts/storage/qcow2/create_private_template.sh index 4b93380bc52..8e9e26c4104 100755 --- a/scripts/storage/qcow2/create_private_template.sh +++ b/scripts/storage/qcow2/create_private_template.sh @@ -31,7 +31,13 @@ create_template() { local fspath=$1 local destpath=$2 - qemu-img convert -O qcow2 /$fspath $destpath + # if backing image exists, we need to combine them, otherwise + # copy the image to preserve snapshots/compression + if $qemu_img info "$tmpltimg" | grep -q backing; then + qemu-img convert -O qcow2 /$fspath $destpath + else + cp -f /$fspath $destpath + fi if [ $? -gt 0 ]; then printf " Failed to export template $destpath\n" >&2 diff --git a/scripts/storage/qcow2/createtmplt.sh b/scripts/storage/qcow2/createtmplt.sh index 84d2ba80b8c..152268f651a 100755 --- a/scripts/storage/qcow2/createtmplt.sh +++ b/scripts/storage/qcow2/createtmplt.sh @@ -100,7 +100,13 @@ create_from_file() { if [ -b $tmpltimg ]; then $qemu_img convert -f raw -O qcow2 "$tmpltimg" /$tmpltfs/$tmpltname else + # if backing image exists, we need to combine them, otherwise + # copy the image to preserve snapshots/compression + if $qemu_img info "$tmpltimg" | grep -q backing; then $qemu_img convert -f qcow2 -O qcow2 "$tmpltimg" /$tmpltfs/$tmpltname >& /dev/null + else + cp -f $tmpltimg /$tmpltfs/$tmpltname + fi fi if [ "$cleanup" == "true" ] diff --git a/scripts/storage/qcow2/createvolume.sh b/scripts/storage/qcow2/createvolume.sh index cfafed156f9..527aa68db28 100755 --- a/scripts/storage/qcow2/createvolume.sh +++ b/scripts/storage/qcow2/createvolume.sh @@ -99,9 +99,15 @@ create_from_file() { local volimg="$2" local volname=$3 if [ -b $volimg ]; then - $qemu-img convert -f raw -O qcow2 "$volimg" /$volfs/$volname + $qemu_img convert -f raw -O qcow2 "$volimg" /$volfs/$volname else + # if backing image exists, we need to combine them, otherwise + # copy the image to preserve snapshots/compression + if $qemu_img info "$volimg" | grep -q backing; then $qemu_img convert -f qcow2 -O qcow2 "$volimg" /$volfs/$volname >& /dev/null + else + cp -f $volimg /$volfs/$volname + fi fi if [ "$cleanup" == "true" ] diff --git a/scripts/vm/hypervisor/xenserver/s3xen b/scripts/vm/hypervisor/xenserver/s3xen new file mode 100644 index 00000000000..4d9c12d6a5a --- /dev/null +++ b/scripts/vm/hypervisor/xenserver/s3xen @@ -0,0 +1,297 @@ +#!/usr/bin/python +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Version @VERSION@ +# +# A plugin for executing script needed by cloud stack +from __future__ import with_statement + +from copy import copy +from datetime import datetime +from httplib import * +from string import join + +import os +import sys +import time +import hashlib +import base64 +import hmac +import traceback +import urllib2 + +import XenAPIPlugin +sys.path.extend(["/opt/xensource/sm/"]) +import util + +NULL = 'null' + +# Value conversion utility functions ... + + +def to_none(value): + return value if value is not None and value.strip() != NULL else None + + +def to_bool(value): + return True if to_none(value) in ['true', 'True', None] else False + + +def to_integer(value, default): + return int(value) if to_none(value) is not None else default + + +def optional_str_value(value, default): + return value if is_not_blank(value) else default + + +def is_not_blank(value): + return True if to_none(value) is not None and value.strip != '' else False + + +def get_optional_key(map, key, default=''): + return map[key] if key in map else default + + +def log(message): + util.SMlog('#### VMOPS %s ####' % message) + + +def echo(fn): + def wrapped(*v, **k): + name = fn.__name__ + log("enter %s ####" % name) + res = fn(*v, **k) + log("exit %s with result %s" % name, res) + return res + return wrapped + + +def require_str_value(value, error_message): + + if is_not_blank(value): + return value + + raise ValueError(error_message) + + +def retry(max_attempts, fn): + + attempts = 1 + while attempts <= max_attempts: + log("Attempting execution {0}/{1} of {2}". + format(attempts, max_attempts, fn.__name__)) + try: + return fn() + except: + if (attempts >= max_attempts): + raise + attempts = attempts + 1 + + +def compute_md5(filename, buffer_size=8192): + + hasher = hashlib.md5() + + with open(filename, 'rb') as file: + data = file.read(buffer_size) + while data != "": + hasher.update(data) + data = file.read(buffer_size) + + return base64.encodestring(hasher.digest())[:-1] + + +class S3Client(object): + + DEFAULT_END_POINT = 's3.amazonaws.com' + DEFAULT_CONNECTION_TIMEOUT = 50000 + DEFAULT_SOCKET_TIMEOUT = 50000 + DEFAULT_MAX_ERROR_RETRY = 3 + + HEADER_CONTENT_MD5 = 'Content-MD5' + HEADER_CONTENT_TYPE = 'Content-Type' + HEADER_CONTENT_LENGTH = 'Content-Length' + + def __init__(self, access_key, secret_key, end_point=None, + https_flag=None, connection_timeout=None, socket_timeout=None, + max_error_retry=None): + + self.access_key = require_str_value( + access_key, 'An access key must be specified.') + self.secret_key = require_str_value( + secret_key, 'A secret key must be specified.') + self.end_point = optional_str_value(end_point, self.DEFAULT_END_POINT) + self.https_flag = to_bool(https_flag) + self.connection_timeout = to_integer( + connection_timeout, self.DEFAULT_CONNECTION_TIMEOUT) + self.socket_timeout = to_integer( + socket_timeout, self.DEFAULT_SOCKET_TIMEOUT) + self.max_error_retry = to_integer( + max_error_retry, self.DEFAULT_MAX_ERROR_RETRY) + + def build_canocialized_resource(self, bucket, key): + + return '/{bucket}/{key}'.format(bucket=bucket, key=key) + + def noop_send_body(): + pass + + def noop_read(response): + return response.read() + + def do_operation( + self, method, bucket, key, input_headers={}, + fn_send_body=noop_send_body, fn_read=noop_read): + + headers = copy(input_headers) + headers['Expect'] = '100-continue' + + uri = self.build_canocialized_resource(bucket, key) + signature, request_date = self.sign_request(method, uri, headers) + headers['Authorization'] = "AWS {0}:{1}".format( + self.access_key, signature) + headers['Date'] = request_date + + connection = HTTPSConnection(self.end_point) \ + if self.https_flag else HTTPConnection(self.end_point) + connection.timeout = self.socket_timeout + + def perform_request(): + + connection.request(method, uri, fn_send_body(), headers) + response = connection.getresponse() + log("Sent {0} request to {1} {2} with headers {3}. \ + Got response status {4}: {5}". + format(method, self.end_point, uri, headers, + response.status, response.reason)) + return fn_read(response) + + try: + return retry(self.max_error_retry, perform_request) + finally: + connection.close() + + ''' + See http://bit.ly/MMC5de for more information regarding the creation of + AWS authorization tokens and header signing + ''' + def sign_request(self, operation, canocialized_resource, headers): + + request_date = datetime.utcnow( + ).strftime('%a, %d %b %Y %H:%M:%S +0000') + + content_hash = get_optional_key(headers, self.HEADER_CONTENT_MD5) + content_type = get_optional_key(headers, self.HEADER_CONTENT_TYPE) + + string_to_sign = join( + [operation, content_hash, content_type, request_date, + canocialized_resource], '\n') + + signature = base64.encodestring( + hmac.new(self.secret_key, string_to_sign.encode('utf8'), + hashlib.sha1).digest())[:-1] + + return signature, request_date + + def put(self, bucket, key, src_filename): + + headers = { + self.HEADER_CONTENT_MD5: compute_md5(src_filename), + self.HEADER_CONTENT_TYPE: 'application/octet-stream', + self.HEADER_CONTENT_LENGTH: os.stat(src_filename).st_size, + } + + def send_body(): + return open(src_filename, 'rb') + + self.do_operation('PUT', bucket, key, headers, send_body) + + def get(self, bucket, key, target_filename): + + def read(response): + + with open(target_filename, 'wb') as file: + while True: + block = response.read(8192) + if not block: + break + file.write(block) + + return self.do_operation('GET', bucket, key, fn_read=read) + + def delete(self, bucket, key): + + return self.do_operation('DELETE', bucket, key) + + +def parseArguments(args): + + # The keys in the args map will correspond to the properties defined on + # the com.cloud.utils.S3Utils#ClientOptions interface + client = S3Client( + args['accessKey'], args['secretKey'], args['endPoint'], + args['isHttps'], args['connectionTimeout'], args['socketTimeout']) + + operation = args['operation'] + bucket = args['bucket'] + key = args['key'] + filename = args['filename'] + + if is_blank(operation): + raise ValueError('An operation must be specified.') + + if is_blank(bucket): + raise ValueError('A bucket must be specified.') + + if is_blank(key): + raise ValueError('A value must be specified.') + + if is_blank(filename): + raise ValueError('A filename must be specified.') + + return client, operation, bucket, key, filename + + +@echo +def s3(session, args): + + client, operation, bucket, key, filename = parseArguments(args) + + try: + + if operation == 'put': + client.put(bucket, key, filename) + elif operation == 'get': + client.get(bucket, key, filename) + elif operation == 'delete': + client.delete(bucket, key, filename) + else: + raise RuntimeError( + "S3 plugin does not support operation {0}.".format(operation)) + + return 'true' + + except: + log("Operation {0} on file {1} from/in bucket {2} key {3}.".format( + operation, filename, bucket, key)) + log(traceback.format_exc()) + return 'false' + +if __name__ == "__main__": + XenAPIPlugin.dispatch({"s3": s3}) diff --git a/scripts/vm/hypervisor/xenserver/xenserver56/patch b/scripts/vm/hypervisor/xenserver/xenserver56/patch index d485414fdcb..36dba3dc06b 100644 --- a/scripts/vm/hypervisor/xenserver/xenserver56/patch +++ b/scripts/vm/hypervisor/xenserver/xenserver56/patch @@ -62,3 +62,5 @@ cloud-prepare-upgrade.sh=..,0755,/opt/xensource/bin bumpUpPriority.sh=../../../../network/domr/,0755,/opt/xensource/bin swift=..,0755,/opt/xensource/bin swiftxen=..,0755,/etc/xapi.d/plugins +s3xen=..,0755,/etc/xapi.d/plugins + diff --git a/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch b/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch index 9fe9740756c..d20e60f2e49 100644 --- a/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch +++ b/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch @@ -61,3 +61,5 @@ cloud-prepare-upgrade.sh=..,0755,/opt/xensource/bin bumpUpPriority.sh=../../../../network/domr/,0755,/opt/xensource/bin swift=..,0755,/opt/xensource/bin swiftxen=..,0755,/etc/xapi.d/plugins +s3xen=..,0755,/etc/xapi.d/plugins + diff --git a/scripts/vm/hypervisor/xenserver/xenserver60/patch b/scripts/vm/hypervisor/xenserver/xenserver60/patch index f0491092749..c9125f4c5b2 100644 --- a/scripts/vm/hypervisor/xenserver/xenserver60/patch +++ b/scripts/vm/hypervisor/xenserver/xenserver60/patch @@ -66,3 +66,5 @@ cloud-prepare-upgrade.sh=..,0755,/opt/xensource/bin bumpUpPriority.sh=../../../../network/domr/,0755,/opt/xensource/bin swift=..,0755,/opt/xensource/bin swiftxen=..,0755,/etc/xapi.d/plugins +s3xen=..,0755,/etc/xapi.d/plugins + diff --git a/scripts/vm/network/security_group.py b/scripts/vm/network/security_group.py index b0798907c8a..dcb01a7604b 100755 --- a/scripts/vm/network/security_group.py +++ b/scripts/vm/network/security_group.py @@ -24,6 +24,7 @@ import sys import os import xml.dom.minidom from optparse import OptionParser, OptionGroup, OptParseError, BadOptionError, OptionError, OptionConflictError, OptionValueError +import re iptables = Command("iptables") bash = Command("/bin/bash") virsh = Command("virsh") @@ -420,12 +421,11 @@ def network_rules_for_rebooted_vm(vmName): delete_rules_for_vm_in_bridge_firewall_chain(vm_name) - brName = execute("iptables-save |grep physdev-is-bridged |grep FORWARD |grep BF |grep '\-o' |awk '{print $9}'").split("\n") - if brName is None: + brName = execute("iptables-save |grep physdev-is-bridged |grep FORWARD |grep BF |grep '\-o' |awk '{print $9}' | head -1").strip() + if brName is None or brName is "": brName = "cloudbr0" else: - brName.pop() - brName = brName[0].split("-")[1] + brName = re.sub("^BF-", "", brName) if 1 in [ vm_name.startswith(c) for c in ['r-', 's-', 'v-'] ]: diff --git a/server/pom.xml b/server/pom.xml index 99da97fbe3c..c253e43acc7 100644 --- a/server/pom.xml +++ b/server/pom.xml @@ -67,6 +67,11 @@ jstl ${cs.jstl.version} + + commons-codec + commons-codec + ${cs.codec.version} + org.apache.cloudstack cloud-utils @@ -74,7 +79,6 @@ tests test - install diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index ac7aeb62bb7..4b5b32352ab 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -177,6 +177,7 @@ import com.cloud.storage.StoragePoolVO; import com.cloud.storage.StorageStats; import com.cloud.storage.UploadVO; import com.cloud.storage.VMTemplateHostVO; +import com.cloud.storage.VMTemplateS3VO; import com.cloud.storage.VMTemplateSwiftVO; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Volume.Type; @@ -192,6 +193,7 @@ import com.cloud.storage.dao.UploadDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplateDetailsDao; import com.cloud.storage.dao.VMTemplateHostDao; +import com.cloud.storage.dao.VMTemplateS3Dao; import com.cloud.storage.dao.VMTemplateSwiftDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.dao.VolumeHostDao; @@ -265,6 +267,7 @@ public class ApiDBUtils { private static VMTemplateDetailsDao _templateDetailsDao; private static VMTemplateHostDao _templateHostDao; private static VMTemplateSwiftDao _templateSwiftDao; + private static VMTemplateS3Dao _templateS3Dao; private static UploadDao _uploadDao; private static UserDao _userDao; private static UserStatisticsDao _userStatsDao; @@ -353,6 +356,7 @@ public class ApiDBUtils { _templateDetailsDao = locator.getDao(VMTemplateDetailsDao.class); _templateHostDao = locator.getDao(VMTemplateHostDao.class); _templateSwiftDao = locator.getDao(VMTemplateSwiftDao.class); + _templateS3Dao = locator.getDao(VMTemplateS3Dao.class); _uploadDao = locator.getDao(UploadDao.class); _userDao = locator.getDao(UserDao.class); _userStatsDao = locator.getDao(UserStatisticsDao.class); @@ -689,6 +693,10 @@ public class ApiDBUtils { return _templateSwiftDao.findOneByTemplateId(templateId); } + public static VMTemplateS3VO findTemplateS3Ref(long templateId) { + return _templateS3Dao.findOneByTemplateId(templateId); + } + public static UploadVO findUploadById(Long id) { return _uploadDao.findById(id); } diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java index 6fcfb79d808..e9a7571d9cd 100755 --- a/server/src/com/cloud/api/ApiDispatcher.java +++ b/server/src/com/cloud/api/ApiDispatcher.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.api; +import static org.apache.commons.lang.StringUtils.isNotBlank; + import java.lang.reflect.Field; import java.text.DateFormat; import java.text.ParseException; @@ -607,10 +609,20 @@ public class ApiDispatcher { } break; case FLOAT: - field.set(cmdObj, Float.valueOf(paramObj.toString())); + // Assuming that the parameters have been checked for required before now, + // we ignore blank or null values and defer to the command to set a default + // value for optional parameters ... + if (paramObj != null && isNotBlank(paramObj.toString())) { + field.set(cmdObj, Float.valueOf(paramObj.toString())); + } break; case INTEGER: - field.set(cmdObj, Integer.valueOf(paramObj.toString())); + // Assuming that the parameters have been checked for required before now, + // we ignore blank or null values and defer to the command to set a default + // value for optional parameters ... + if (paramObj != null && isNotBlank(paramObj.toString())) { + field.set(cmdObj, Integer.valueOf(paramObj.toString())); + } break; case LIST: List listParam = new ArrayList(); diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 5cb0f4890a8..b2bfee89098 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -16,6 +16,9 @@ // under the License. package com.cloud.api; +import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; + import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Date; @@ -127,8 +130,8 @@ import org.apache.cloudstack.api.response.VpcOfferingResponse; import org.apache.cloudstack.api.response.VpcResponse; import org.apache.cloudstack.api.response.VpnUsersResponse; import org.apache.cloudstack.api.response.ZoneResponse; -import org.bouncycastle.util.IPAddress; +import com.cloud.api.response.S3Response; import com.cloud.async.AsyncJob; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityVO; @@ -215,6 +218,7 @@ import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.GuestOS; import com.cloud.storage.GuestOSCategoryVO; +import com.cloud.storage.S3; import com.cloud.storage.Snapshot; import com.cloud.storage.Storage; import com.cloud.storage.Storage.ImageFormat; @@ -226,6 +230,7 @@ import com.cloud.storage.StorageStats; import com.cloud.storage.Swift; import com.cloud.storage.UploadVO; import com.cloud.storage.VMTemplateHostVO; +import com.cloud.storage.VMTemplateS3VO; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.VMTemplateSwiftVO; import com.cloud.storage.VMTemplateVO; @@ -634,6 +639,25 @@ public class ApiResponseHelper implements ResponseGenerator { return swiftResponse; } + @Override + public S3Response createS3Response(final S3 result) { + + final S3Response response = new S3Response(); + + response.setAccessKey(result.getAccessKey()); + response.setConnectionTimeout(result.getConnectionTimeout()); + response.setEndPoint(result.getEndPoint()); + response.setHttpsFlag(result.getHttpsFlag()); + response.setMaxErrorRetry(result.getMaxErrorRetry()); + response.setObjectId(result.getId()); + response.setSecretKey(result.getSecretKey()); + response.setSocketTimeout(result.getSocketTimeout()); + response.setTemplateBucketName(result.getBucketName()); + + return response; + + } + @Override public VlanIpRangeResponse createVlanIpRangeResponse(Vlan vlan) { Long podId = ApiDBUtils.getPodIdForVlan(vlan.getId()); @@ -1751,7 +1775,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public List createIsoResponses(long isoId, Long zoneId, boolean readyOnly) { - List isoResponses = new ArrayList(); + final List isoResponses = new ArrayList(); VirtualMachineTemplate iso = findTemplateById(isoId); if (iso.getTemplateType() == TemplateType.PERHOST) { TemplateResponse isoResponse = new TemplateResponse(); @@ -1789,11 +1813,17 @@ public class ApiResponseHelper implements ResponseGenerator { return isoResponses; } else { if (zoneId == null || zoneId == -1) { - isoResponses = createSwiftIsoResponses(iso); + isoResponses.addAll(createSwiftIsoResponses(iso)); if (!isoResponses.isEmpty()) { return isoResponses; } - List dcs = new ArrayList(); + + isoResponses.addAll(createS3IsoResponses(iso)); + if (!isoResponses.isEmpty()) { + return isoResponses; + } + + final List dcs = new ArrayList(); dcs.addAll(ApiDBUtils.listZones()); for (DataCenterVO dc : dcs) { isoResponses.addAll(createIsoResponses(iso, dc.getId(), readyOnly)); @@ -1805,6 +1835,65 @@ public class ApiResponseHelper implements ResponseGenerator { } } + private List createS3IsoResponses(final VirtualMachineTemplate iso) { + + final VMTemplateS3VO s3Iso = ApiDBUtils.findTemplateS3Ref(iso.getId()); + + if (s3Iso == null) { + return emptyList(); + } + + final TemplateResponse templateResponse = new TemplateResponse(); + + templateResponse.setId(iso.getUuid()); + templateResponse.setName(iso.getName()); + templateResponse.setDisplayText(iso.getDisplayText()); + templateResponse.setPublic(iso.isPublicTemplate()); + templateResponse.setExtractable(iso.isExtractable()); + templateResponse.setCreated(s3Iso.getCreated()); + templateResponse.setReady(true); + templateResponse.setBootable(iso.isBootable()); + templateResponse.setFeatured(iso.isFeatured()); + templateResponse.setCrossZones(iso.isCrossZones()); + templateResponse.setChecksum(iso.getChecksum()); + templateResponse.setDetails(iso.getDetails()); + + final GuestOS os = ApiDBUtils.findGuestOSById(iso.getGuestOSId()); + + if (os != null) { + templateResponse.setOsTypeId(os.getUuid()); + templateResponse.setOsTypeName(os.getDisplayName()); + } else { + templateResponse.setOsTypeId(""); + templateResponse.setOsTypeName(""); + } + + final Account account = ApiDBUtils.findAccountByIdIncludingRemoved(iso.getAccountId()); + populateAccount(templateResponse, account.getId()); + populateDomain(templateResponse, account.getDomainId()); + + boolean isAdmin = false; + if ((account == null) || BaseCmd.isAdmin(account.getType())) { + isAdmin = true; + } + + // If the user is an admin, add the template download status + if (isAdmin || account.getId() == iso.getAccountId()) { + // add download status + templateResponse.setStatus("Successfully Installed"); + } + + final Long isoSize = s3Iso.getSize(); + if (isoSize > 0) { + templateResponse.setSize(isoSize); + } + + templateResponse.setObjectName("iso"); + + return singletonList(templateResponse); + + } + private List createSwiftIsoResponses(VirtualMachineTemplate iso) { long isoId = iso.getId(); List isoResponses = new ArrayList(); @@ -2526,7 +2615,7 @@ public class ApiResponseHelper implements ResponseGenerator { } // populate network offering information - NetworkOffering networkOffering = ApiDBUtils.findNetworkOfferingById(network.getNetworkOfferingId()); + NetworkOffering networkOffering = (NetworkOffering) ApiDBUtils.findNetworkOfferingById(network.getNetworkOfferingId()); if (networkOffering != null) { response.setNetworkOfferingId(networkOffering.getUuid()); response.setNetworkOfferingName(networkOffering.getName()); diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index 9e549efc73e..1551e44fe25 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -119,6 +119,8 @@ import com.cloud.user.UserVO; import com.cloud.utils.IdentityProxy; import com.cloud.utils.Pair; import com.cloud.utils.component.Adapters; +import com.cloud.utils.PropertiesUtil; +import com.cloud.utils.StringUtils; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.concurrency.NamedThreadFactory; @@ -220,7 +222,7 @@ public class ApiServer implements HttpRequestHandler { InetAddress remoteAddr = ((SocketHttpServerConnection) connObj).getRemoteAddress(); sb.append(remoteAddr.toString() + " -- "); } - sb.append(request.getRequestLine()); + sb.append(StringUtils.cleanString(request.getRequestLine().toString())); try { List paramList = null; @@ -513,22 +515,13 @@ public class ApiServer implements HttpRequestHandler { return; } auditTrailSb.append(" " + HttpServletResponse.SC_OK + " "); - auditTrailSb.append(result); - /* - * if (command.equals("queryAsyncJobResult")){ //For this command we need to also log job status and job - * resultcode for - * (Pair pair : resultValues){ String key = pair.first(); if (key.equals("jobstatus")){ - * auditTrailSb.append(" "); auditTrailSb.append(key); auditTrailSb.append("="); - * auditTrailSb.append(pair.second()); - * }else if (key.equals("jobresultcode")){ auditTrailSb.append(" "); auditTrailSb.append(key); - * auditTrailSb.append("="); - * auditTrailSb.append(pair.second()); } } }else { for (Pair pair : resultValues){ if - * (pair.first().equals("jobid")){ // Its an async job so report the jobid auditTrailSb.append(" "); - * auditTrailSb.append(pair.first()); auditTrailSb.append("="); auditTrailSb.append(pair.second()); } } } - */ + if (command.equals("createSSHKeyPair")){ + auditTrailSb.append("This result was not logged because it contains sensitive data."); + } else { + auditTrailSb.append(StringUtils.cleanString(result)); + } } - public boolean verifyRequest(Map requestParameters, Long userId) throws ServerApiException { try { String apiKey = null; diff --git a/server/src/com/cloud/api/ApiServlet.java b/server/src/com/cloud/api/ApiServlet.java index 895481938e7..19091f25ff2 100755 --- a/server/src/com/cloud/api/ApiServlet.java +++ b/server/src/com/cloud/api/ApiServlet.java @@ -38,6 +38,7 @@ import com.cloud.server.ManagementServer; import com.cloud.user.Account; import com.cloud.user.AccountService; import com.cloud.user.UserContext; +import com.cloud.utils.StringUtils; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.exception.CloudRuntimeException; @@ -125,7 +126,7 @@ public class ApiServlet extends HttpServlet { String reqStr = ""; if (s_logger.isDebugEnabled()) { reqStr = auditTrailSb.toString() + " " + req.getQueryString(); - s_logger.debug("===START=== " + reqStr); + s_logger.debug("===START=== " + StringUtils.cleanString(reqStr)); } try { @@ -342,7 +343,7 @@ public class ApiServlet extends HttpServlet { } finally { s_accessLogger.info(auditTrailSb.toString()); if (s_logger.isDebugEnabled()) { - s_logger.debug("===END=== " + reqStr); + s_logger.debug("===END=== " + StringUtils.cleanString(reqStr)); } // cleanup user context to prevent from being peeked in other request context UserContext.unregisterContext(); diff --git a/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java b/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java index cfc20d06913..063b28bde4b 100644 --- a/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java +++ b/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java @@ -50,11 +50,25 @@ public class AddTrafficMonitorCmd extends BaseCmd { @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the traffic monitor Host") private String url; + + @Parameter(name=ApiConstants.INCL_ZONES, type=CommandType.STRING, description="Traffic going into the listed zones will be metered") + private String inclZones; + + @Parameter(name=ApiConstants.EXCL_ZONES, type=CommandType.STRING, description="Traffic going into the listed zones will not be metered") + private String exclZones; /////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// + public String getInclZones() { + return inclZones; + } + + public String getExclZones() { + return exclZones; + } + public Long getZoneId() { return zoneId; } diff --git a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java index 5a1deeca7e6..9e37ff9a105 100644 --- a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java +++ b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java @@ -312,6 +312,11 @@ public class ApiXmlDocWriter { impl = clas.getSuperclass().getAnnotation(Implementation.class); } + if (impl == null) { + throw new IllegalStateException(String.format("An %1$s annotation is required for class %2$s.", + Implementation.class.getCanonicalName(), clas.getCanonicalName())); + } + if (impl.includeInApiDoc()) { String commandDescription = impl.description(); if (commandDescription != null && !commandDescription.isEmpty()) { diff --git a/server/src/com/cloud/cluster/ClusterServiceServletImpl.java b/server/src/com/cloud/cluster/ClusterServiceServletImpl.java index 0c3a175c5c5..3270315785b 100644 --- a/server/src/com/cloud/cluster/ClusterServiceServletImpl.java +++ b/server/src/com/cloud/cluster/ClusterServiceServletImpl.java @@ -62,11 +62,7 @@ public class ClusterServiceServletImpl implements ClusterService { method.addParameter("stopOnError", pdu.isStopOnError() ? "1" : "0"); method.addParameter("pduType", Integer.toString(pdu.getPduType())); - try { - return executePostMethod(client, method); - } finally { - method.releaseConnection(); - } + return executePostMethod(client, method); } @Override @@ -81,15 +77,11 @@ public class ClusterServiceServletImpl implements ClusterService { method.addParameter("method", Integer.toString(RemoteMethodConstants.METHOD_PING)); method.addParameter("callingPeer", callingPeer); - try { - String returnVal = executePostMethod(client, method); - if("true".equalsIgnoreCase(returnVal)) { - return true; - } - return false; - } finally { - method.releaseConnection(); + String returnVal = executePostMethod(client, method); + if("true".equalsIgnoreCase(returnVal)) { + return true; } + return false; } private String executePostMethod(HttpClient client, PostMethod method) { @@ -115,6 +107,8 @@ public class ClusterServiceServletImpl implements ClusterService { s_logger.error("IOException from : " + _serviceUrl + ", method : " + method.getParameter("method")); } catch(Throwable e) { s_logger.error("Exception from : " + _serviceUrl + ", method : " + method.getParameter("method") + ", exception :", e); + } finally { + method.releaseConnection(); } return result; diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java index 66ac2762de1..ea32025ba32 100755 --- a/server/src/com/cloud/configuration/Config.java +++ b/server/src/com/cloud/configuration/Config.java @@ -105,6 +105,8 @@ public enum Config { SecurityGroupDefaultAdding("Network", ManagementServer.class, Boolean.class, "network.securitygroups.defaultadding", "true", "If true, the user VM would be added to the default security group by default", null), + GuestOSNeedGatewayOnNonDefaultNetwork("Network", NetworkManager.class, String.class, "network.dhcp.nondefaultnetwork.setgateway.guestos", "Windows", "The guest OS's name start with this fields would result in DHCP server response gateway information even when the network it's on is not default network. Names are separated by comma.", null), + //VPN RemoteAccessVpnPskLength("Network", AgentManager.class, Integer.class, "remote.access.vpn.psk.length", "24", "The length of the ipsec preshared key (minimum 8, maximum 256)", null), RemoteAccessVpnClientIpRange("Network", AgentManager.class, String.class, "remote.access.vpn.client.iprange", "10.1.2.1-10.1.2.8", "The range of ips to be allocated to remote access vpn clients. The first ip in the range is used by the VPN server", null), @@ -140,8 +142,8 @@ public enum Config { JobExpireMinutes("Advanced", ManagementServer.class, String.class, "job.expire.minutes", "1440", "Time (in minutes) for async-jobs to be kept in system", null), JobCancelThresholdMinutes("Advanced", ManagementServer.class, String.class, "job.cancel.threshold.minutes", "60", "Time (in minutes) for async-jobs to be forcely cancelled if it has been in process for long", null), SwiftEnable("Advanced", ManagementServer.class, Boolean.class, "swift.enable", "false", "enable swift ", null), - - EventPurgeInterval("Advanced", ManagementServer.class, Integer.class, "event.purge.interval", "86400", "The interval (in seconds) to wait before running the event purge thread", null), + S3Enable("Advanced", ManagementServer.class, Boolean.class, "s3.enable", "false", "enable s3 ", null), + EventPurgeInterval("Advanced", ManagementServer.class, Integer.class, "event.purge.interval", "86400", "The interval (in seconds) to wait before running the event purge thread", null), AccountCleanupInterval("Advanced", ManagementServer.class, Integer.class, "account.cleanup.interval", "86400", "The interval (in seconds) between cleanup for removed accounts", null), AllowPublicUserTemplates("Advanced", ManagementServer.class, Integer.class, "allow.public.user.templates", "true", "If false, users will not be able to create public templates.", null), InstanceName("Advanced", AgentManager.class, String.class, "instance.name", "VM", "Name of the deployment instance.", "instanceName"), @@ -274,6 +276,8 @@ public enum Config { DirectNetworkStatsInterval("Usage", ManagementServer.class, Integer.class, "direct.network.stats.interval", "86400", "Interval (in seconds) to collect stats from Traffic Monitor", null), UsageSanityCheckInterval("Usage", ManagementServer.class, Integer.class, "usage.sanity.check.interval", null, "Interval (in days) to check sanity of usage data", null), UsageAggregationTimezone("Usage", ManagementServer.class, String.class, "usage.aggregation.timezone", "GMT", "The timezone to use for usage stats aggregation", null), + TrafficSentinelIncludeZones("Usage", ManagementServer.class, Integer.class, "traffic.sentinel.include.zones", "EXTERNAL", "Traffic going into specified list of zones is metered. For metering all traffic leave this parameter empty", null), + TrafficSentinelExcludeZones("Usage", ManagementServer.class, Integer.class, "traffic.sentinel.exclude.zones", "", "Traffic going into specified list of zones is not metered.", null), // Hidden UseSecondaryStorageVm("Hidden", ManagementServer.class, Boolean.class, "secondary.storage.vm", "false", "Deploys a VM per zone to manage secondary storage if true, otherwise secondary storage is mounted on management server", null), @@ -291,6 +295,7 @@ public enum Config { VmOpCleanupWait("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.wait", "3600", "Time (in seconds) to wait before cleanuping up any vm work items", "Seconds"), VmOpCancelInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cancel.interval", "3600", "Time (in seconds) to wait before cancelling a operation", "Seconds"), + DefaultPageSize("Advanced", ManagementServer.class, Long.class, "default.page.size", "500", "Default page size for API list* commands", null), TaskCleanupRetryInterval("Advanced", ManagementServer.class, Integer.class, "task.cleanup.retry.interval", "600", "Time (in seconds) to wait before retrying cleanup of tasks if the cleanup failed previously. 0 means to never retry.", "Seconds"), diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index c25b3b7ba6f..f3403c3a6c0 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -65,59 +65,27 @@ import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd; import com.cloud.capacity.dao.CapacityDao; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; -import com.cloud.dc.AccountVlanMapVO; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.DataCenter; +import com.cloud.dc.*; import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.DataCenterIpAddressVO; -import com.cloud.dc.DataCenterLinkLocalIpAddressVO; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.HostPodVO; -import com.cloud.dc.Pod; -import com.cloud.dc.PodVlanMapVO; -import com.cloud.dc.Vlan; import com.cloud.dc.Vlan.VlanType; -import com.cloud.dc.VlanVO; -import com.cloud.dc.dao.AccountVlanMapDao; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.dc.dao.DataCenterIpAddressDao; -import com.cloud.dc.dao.DataCenterLinkLocalIpAddressDaoImpl; -import com.cloud.dc.dao.HostPodDao; -import com.cloud.dc.dao.PodVlanMapDao; -import com.cloud.dc.dao.VlanDao; +import com.cloud.dc.dao.*; import com.cloud.deploy.DataCenterDeployment; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.PermissionDeniedException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; +import com.cloud.exception.*; import com.cloud.host.HostVO; import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.network.IPAddressVO; -import com.cloud.network.Network; +import com.cloud.network.*; import com.cloud.network.Network.Capability; import com.cloud.network.Network.GuestType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; -import com.cloud.network.NetworkManager; -import com.cloud.network.NetworkVO; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetworkVO; -import com.cloud.network.dao.FirewallRulesDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao; -import com.cloud.network.dao.PhysicalNetworkTrafficTypeVO; +import com.cloud.network.dao.*; import com.cloud.network.vpc.VpcManager; import com.cloud.offering.DiskOffering; import com.cloud.offering.NetworkOffering; @@ -136,16 +104,13 @@ import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.SwiftVO; import com.cloud.storage.dao.DiskOfferingDao; +import com.cloud.storage.dao.S3Dao; import com.cloud.storage.dao.SwiftDao; +import com.cloud.storage.s3.S3Manager; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.swift.SwiftManager; import com.cloud.test.IPRangeConfig; -import com.cloud.user.Account; -import com.cloud.user.AccountManager; -import com.cloud.user.AccountVO; -import com.cloud.user.ResourceLimitService; -import com.cloud.user.User; -import com.cloud.user.UserContext; +import com.cloud.user.*; import com.cloud.user.dao.AccountDao; import com.cloud.utils.NumbersUtil; import com.cloud.utils.StringUtils; @@ -161,8 +126,20 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; import com.cloud.vm.VirtualMachine; import com.cloud.vm.dao.NicDao; - import edu.emory.mathcs.backport.java.util.Arrays; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import javax.naming.Context; +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +import javax.naming.directory.InitialDirContext; +import java.net.URI; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; @Local(value = { ConfigurationManager.class, ConfigurationService.class }) public class ConfigurationManagerImpl implements ConfigurationManager, ConfigurationService { @@ -184,6 +161,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Inject SwiftDao _swiftDao; @Inject + S3Dao _s3Dao; + @Inject ServiceOfferingDao _serviceOfferingDao; @Inject DiskOfferingDao _diskOfferingDao; @@ -224,6 +203,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Inject SwiftManager _swiftMgr; @Inject + S3Manager _s3Mgr; + @Inject PhysicalNetworkTrafficTypeDao _trafficTypeDao; @Inject NicDao _nicDao; @@ -485,6 +466,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (swift != null) { return " can not change " + Config.SwiftEnable.key() + " after you have added Swift"; } + if (this._s3Mgr.isS3Enabled()) { + return String.format("Swift is not supported when S3 is enabled."); + } + } + if (Config.S3Enable.key().equals(name)) { + if (this._swiftMgr.isSwiftEnabled()) { + return String.format("S3-backed Secondary Storage is not supported when Swift is enabled."); + } } return null; } @@ -1586,6 +1575,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura createDefaultSystemNetworks(zone.getId()); _swiftMgr.propagateSwiftTmplteOnZone(zone.getId()); + _s3Mgr.propagateTemplatesToZone(zone); txn.commit(); return zone; } catch (Exception ex) { @@ -3136,20 +3126,33 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura void validateStaticNatServiceCapablities(Map staticNatServiceCapabilityMap) { if (staticNatServiceCapabilityMap != null && !staticNatServiceCapabilityMap.isEmpty()) { - if (staticNatServiceCapabilityMap.keySet().size() > 1) { - throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " capabilitiy can be sepcified for static nat service"); + if (staticNatServiceCapabilityMap.keySet().size() > 2) { + throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " and " + Capability.AssociatePublicIP.getName() + " capabilitiy can be sepcified for static nat service"); } - + boolean eipEnabled = false; + boolean eipDisabled = false; + boolean associatePublicIP = true; for (Capability capability : staticNatServiceCapabilityMap.keySet()) { String value = staticNatServiceCapabilityMap.get(capability); if (capability == Capability.ElasticIp) { - boolean enabled = value.contains("true"); - boolean disabled = value.contains("false"); - if (!enabled && !disabled) { + eipEnabled = value.contains("true"); + eipDisabled = value.contains("false"); + if (!eipEnabled && !eipDisabled) { throw new InvalidParameterValueException("Unknown specified value for " + Capability.ElasticIp.getName()); } + } else if (capability == Capability.AssociatePublicIP) { + if (value.contains("true")) { + associatePublicIP = true; + } else if (value.contains("false")) { + associatePublicIP = false; + } else { + throw new InvalidParameterValueException("Unknown specified value for " + Capability.AssociatePublicIP.getName()); + } } else { - throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " capabilitiy can be sepcified for static nat service"); + throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " and " + Capability.AssociatePublicIP.getName() + " capabilitiy can be sepcified for static nat service"); + } + if (eipDisabled && associatePublicIP) { + throw new InvalidParameterValueException("Capability " + Capability.AssociatePublicIP.getName() + " can only be set when capability " + Capability.ElasticIp.getName() + " is true"); } } } @@ -3203,6 +3206,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura boolean sharedSourceNat = false; boolean redundantRouter = false; boolean elasticIp = false; + boolean associatePublicIp = false; if (serviceCapabilityMap != null && !serviceCapabilityMap.isEmpty()) { Map lbServiceCapabilityMap = serviceCapabilityMap.get(Service.Lb); @@ -3243,13 +3247,17 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String param = staticNatServiceCapabilityMap.get(Capability.ElasticIp); if (param != null) { elasticIp = param.contains("true"); + String associatePublicIP = staticNatServiceCapabilityMap.get(Capability.AssociatePublicIP); + if (associatePublicIP != null) { + associatePublicIp = associatePublicIP.contains("true"); + } } } } NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, systemOnly, specifyVlan, networkRate, multicastRate, isDefault, availability, tags, type, conserveMode, dedicatedLb, - sharedSourceNat, redundantRouter, elasticIp, elasticLb, specifyIpRanges); + sharedSourceNat, redundantRouter, elasticIp, elasticLb, associatePublicIp, specifyIpRanges); if (serviceOfferingId != null) { offering.setServiceOfferingId(serviceOfferingId); diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index e1616c000b4..d50ac35f650 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -157,6 +157,7 @@ import com.cloud.storage.dao.DiskOfferingDaoImpl; import com.cloud.storage.dao.GuestOSCategoryDaoImpl; import com.cloud.storage.dao.GuestOSDaoImpl; import com.cloud.storage.dao.LaunchPermissionDaoImpl; +import com.cloud.storage.dao.S3DaoImpl; import com.cloud.storage.dao.SnapshotDaoImpl; import com.cloud.storage.dao.SnapshotPolicyDaoImpl; import com.cloud.storage.dao.SnapshotScheduleDaoImpl; @@ -169,11 +170,13 @@ import com.cloud.storage.dao.VMTemplateDaoImpl; import com.cloud.storage.dao.VMTemplateDetailsDaoImpl; import com.cloud.storage.dao.VMTemplateHostDaoImpl; import com.cloud.storage.dao.VMTemplatePoolDaoImpl; +import com.cloud.storage.dao.VMTemplateS3DaoImpl; import com.cloud.storage.dao.VMTemplateSwiftDaoImpl; import com.cloud.storage.dao.VMTemplateZoneDaoImpl; import com.cloud.storage.dao.VolumeDaoImpl; import com.cloud.storage.dao.VolumeHostDaoImpl; import com.cloud.storage.download.DownloadMonitorImpl; +import com.cloud.storage.s3.S3ManagerImpl; import com.cloud.storage.secondary.SecondaryStorageManagerImpl; import com.cloud.storage.snapshot.SnapshotManagerImpl; import com.cloud.storage.snapshot.SnapshotSchedulerImpl; @@ -292,6 +295,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("VMTemplateHostDao", VMTemplateHostDaoImpl.class); addDao("VolumeHostDao", VolumeHostDaoImpl.class); addDao("VMTemplateSwiftDao", VMTemplateSwiftDaoImpl.class); + addDao("VMTemplateS3Dao", VMTemplateS3DaoImpl.class); addDao("UploadDao", UploadDaoImpl.class); addDao("VMTemplatePoolDao", VMTemplatePoolDaoImpl.class); addDao("LaunchPermissionDao", LaunchPermissionDaoImpl.class); @@ -341,6 +345,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("KeystoreDao", KeystoreDaoImpl.class); addDao("DcDetailsDao", DcDetailsDaoImpl.class); addDao("SwiftDao", SwiftDaoImpl.class); + addDao("S3Dao", S3DaoImpl.class); addDao("AgentTransferMapDao", HostTransferMapDaoImpl.class); addDao("ProjectDao", ProjectDaoImpl.class); addDao("InlineLoadBalancerNicMapDao", InlineLoadBalancerNicMapDaoImpl.class); @@ -427,6 +432,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com info.addParameter("consoleproxy.sslEnabled", "true"); addManager("ProjectManager", ProjectManagerImpl.class); addManager("SwiftManager", SwiftManagerImpl.class); + addManager("S3Manager", S3ManagerImpl.class); addManager("StorageNetworkManager", StorageNetworkManagerImpl.class); addManager("ExternalLoadBalancerUsageManager", ExternalLoadBalancerUsageManagerImpl.class); addManager("HA Manager", HighAvailabilityManagerImpl.class); diff --git a/server/src/com/cloud/maint/UpgradeManagerImpl.java b/server/src/com/cloud/maint/UpgradeManagerImpl.java index c1ce3f0517f..7875c97ec50 100644 --- a/server/src/com/cloud/maint/UpgradeManagerImpl.java +++ b/server/src/com/cloud/maint/UpgradeManagerImpl.java @@ -131,6 +131,8 @@ public class UpgradeManagerImpl implements UpgradeManager { return "Unable to retrieve the file from " + url; } catch (final IOException e) { return "Unable to retrieve the file from " + url; + } finally { + method.releaseConnection(); } file.delete(); diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 347cb2ffcc5..493109a3f28 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -40,6 +40,7 @@ import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; +import com.cloud.utils.db.*; import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd; import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd; import org.apache.cloudstack.api.command.user.network.RestartNetworkCmd; @@ -49,14 +50,7 @@ import com.cloud.acl.ControlledEntity.ACLType; import com.cloud.acl.SecurityChecker.AccessType; import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; -import com.cloud.agent.api.AgentControlAnswer; -import com.cloud.agent.api.AgentControlCommand; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CheckNetworkAnswer; -import com.cloud.agent.api.CheckNetworkCommand; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.StartupRoutingCommand; +import com.cloud.agent.api.*; import com.cloud.agent.api.to.NicTO; import com.cloud.alert.AlertManager; import com.cloud.api.ApiDBUtils; @@ -66,8 +60,7 @@ import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; -import com.cloud.dc.AccountVlanMapVO; -import com.cloud.dc.DataCenter; +import com.cloud.dc.*; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.DataCenterVO; import com.cloud.dc.Pod; @@ -90,17 +83,7 @@ import com.cloud.event.EventTypes; import com.cloud.event.UsageEventVO; import com.cloud.event.dao.EventDao; import com.cloud.event.dao.UsageEventDao; -import com.cloud.exception.AccountLimitException; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.ConnectionException; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InsufficientVirtualNetworkCapcityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.PermissionDeniedException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.exception.UnsupportedServiceException; +import com.cloud.exception.*; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.Status; @@ -118,39 +101,14 @@ import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetwork.BroadcastDomainRange; import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; import com.cloud.network.addr.PublicIp; -import com.cloud.network.dao.FirewallRulesDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.LoadBalancerDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkDomainDao; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; -import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao; -import com.cloud.network.dao.PhysicalNetworkTrafficTypeVO; -import com.cloud.network.element.ConnectivityProvider; -import com.cloud.network.element.DhcpServiceProvider; -import com.cloud.network.element.FirewallServiceProvider; -import com.cloud.network.element.SourceNatServiceProvider; -import com.cloud.network.element.IpDeployer; -import com.cloud.network.element.LoadBalancingServiceProvider; -import com.cloud.network.element.NetworkACLServiceProvider; -import com.cloud.network.element.NetworkElement; -import com.cloud.network.element.PortForwardingServiceProvider; -import com.cloud.network.element.RemoteAccessVPNServiceProvider; -import com.cloud.network.element.Site2SiteVpnServiceProvider; -import com.cloud.network.element.StaticNatServiceProvider; -import com.cloud.network.element.UserDataServiceProvider; -import com.cloud.network.element.VirtualRouterElement; -import com.cloud.network.element.VpcVirtualRouterElement; +import com.cloud.network.dao.*; +import com.cloud.network.element.*; import com.cloud.network.guru.NetworkGuru; import com.cloud.network.lb.LoadBalancingRule; import com.cloud.network.lb.LoadBalancingRule.LbDestination; import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy; import com.cloud.network.lb.LoadBalancingRulesManager; -import com.cloud.network.rules.FirewallManager; -import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.*; import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.rules.PortForwardingRule; @@ -177,13 +135,7 @@ import com.cloud.projects.ProjectManager; import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.tags.ResourceTagVO; import com.cloud.tags.dao.ResourceTagDao; -import com.cloud.user.Account; -import com.cloud.user.AccountManager; -import com.cloud.user.AccountVO; -import com.cloud.user.DomainManager; -import com.cloud.user.ResourceLimitService; -import com.cloud.user.User; -import com.cloud.user.UserContext; +import com.cloud.user.*; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserStatisticsDao; import com.cloud.utils.AnnotationHelper; @@ -193,14 +145,8 @@ import com.cloud.utils.component.Adapters; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.Filter; -import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.JoinBuilder.JoinType; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.Ip; import com.cloud.utils.net.NetUtils; @@ -221,6 +167,19 @@ import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; import edu.emory.mathcs.backport.java.util.Collections; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.net.URI; +import java.security.InvalidParameterException; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; /** * NetworkManagerImpl implements NetworkManager. @@ -1015,6 +974,38 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override @ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "allocating Ip", create = true) + public IpAddress allocateIP(Account ipOwner, long zoneId, Long networkId) + throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException { + + if (networkId != null) { + Network network = _networksDao.findById(networkId); + if (network == null) { + throw new InvalidParameterValueException("Invalid network id is given"); + } + if (network.getGuestType() == Network.GuestType.Shared) { + DataCenter zone = _configMgr.getZone(zoneId); + if (zone == null) { + throw new InvalidParameterValueException("Invalid zone Id is given"); + } + + // if shared network in the advanced zone, then check the caller against the network for 'AccessType.UseNetwork' + if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId()) && zone.getNetworkType() == NetworkType.Advanced) { + Account caller = UserContext.current().getCaller(); + long callerUserId = UserContext.current().getCallerUserId(); + _accountMgr.checkAccess(caller, AccessType.UseNetwork, false, network); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId()); + } + return allocateIp(ipOwner, false, caller, zone); + } else { + throw new InvalidParameterValueException("Associate IP address can only be called on the shared networks in the advanced zone" + + " with Firewall/Source Nat/Static Nat/Port Forwarding/Load balancing services enabled"); + } + } + } + + return allocateIP(ipOwner, false, zoneId); + } public IpAddress allocateIP(Account ipOwner, boolean isSystem, long zoneId) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException { @@ -1024,12 +1015,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _accountMgr.checkAccess(caller, null, false, ipOwner); DataCenter zone = _configMgr.getZone(zoneId); - - return allocateIp(ipOwner, isSystem, caller, callerUserId, zone); + + return allocateIp(ipOwner, isSystem, caller, zone); } @DB - public IpAddress allocateIp(Account ipOwner, boolean isSystem, Account caller, long callerUserId, DataCenter zone) + public IpAddress allocateIp(Account ipOwner, boolean isSystem, Account caller, DataCenter zone) throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException { @@ -1050,7 +1041,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Account accountToLock = null; try { if (s_logger.isDebugEnabled()) { - s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId()); + s_logger.debug("Associate IP address called by the user " + caller.getId()); } accountToLock = _accountDao.acquireInLockTable(ipOwner.getId()); if (accountToLock == null) { @@ -1130,7 +1121,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag IPAddressVO ipToAssoc = _ipAddressDao.findById(ipId); if (ipToAssoc != null) { - _accountMgr.checkAccess(caller, null, true, ipToAssoc); + Network network = _networksDao.findById(networkId); + if (network == null) { + throw new InvalidParameterValueException("Invalid network id is given"); + } + + DataCenter zone = _configMgr.getZone(network.getDataCenterId()); + if (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced) { + if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) { + _accountMgr.checkAccess(UserContext.current().getCaller(), AccessType.UseNetwork, false, network); + } else { + throw new InvalidParameterValueException("IP can be associated with guest network of 'shared' type only if" + + "network service Source Nat, Static Nat, Port Forwarding, Load balancing, firewall are enabled in the network"); + } + } else { + _accountMgr.checkAccess(caller, null, true, ipToAssoc); + } owner = _accountMgr.getAccount(ipToAssoc.getAllocatedToAccountId()); } else { s_logger.debug("Unable to find ip address by id: " + ipId); @@ -1154,20 +1160,23 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // allow associating IP addresses to guest network only if (network.getTrafficType() != TrafficType.Guest) { - throw new InvalidParameterValueException("Ip address can be associated to the network with trafficType " + - TrafficType.Guest); + throw new InvalidParameterValueException("Ip address can be associated to the network with trafficType " + TrafficType.Guest); } - // Check that network belongs to IP owner - skip this check for Basic zone as there is just one guest network, - // and it belongs to the system - if (zone.getNetworkType() != NetworkType.Basic && network.getAccountId() != owner.getId()) { - throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP"); + // Check that network belongs to IP owner - skip this check + // - if zone is basic zone as there is just one guest network, + // - if shared network in Advanced zone + // - and it belongs to the system + if (network.getAccountId() != owner.getId()) { + if (zone.getNetworkType() != NetworkType.Basic && !(zone.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Shared)) { + throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP"); + } } - // In Advance zone only allow to do IP assoc for Isolated networks with source nat service enabled - if (zone.getNetworkType() == NetworkType.Advanced && - !(network.getGuestType() == GuestType.Isolated && areServicesSupportedInNetwork(network.getId(), - Service.SourceNat))) { + // In Advance zone only allow to do IP assoc + // - for Isolated networks with source nat service enabled + // - for shared networks with source nat service enabled + if (zone.getNetworkType() == NetworkType.Advanced && (!areServicesSupportedInNetwork(network.getId(), Service.SourceNat))) { throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated only to the network of guest type " + GuestType.Isolated + " with the " + Service.SourceNat.getName() + " enabled"); @@ -1938,12 +1947,21 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag try { NetworkGuru guru = _networkGurus.get(network.getGuruName()); Network.State state = network.getState(); - if (state == Network.State.Implemented || state == Network.State.Setup || state == Network.State.Implementing) { + if (state == Network.State.Implemented || state == Network.State.Implementing) { s_logger.debug("Network id=" + networkId + " is already implemented"); implemented.set(guru, network); return implemented; } + if (state == Network.State.Setup) { + DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); + if (!isSharedNetworkOfferingWithServices(network.getNetworkOfferingId()) || (zone.getNetworkType() == NetworkType.Basic)) { + s_logger.debug("Network id=" + networkId + " is already implemented"); + implemented.set(guru, network); + return implemented; + } + } + if (s_logger.isDebugEnabled()) { s_logger.debug("Asking " + guru.getName() + " to implement " + network); } @@ -1987,18 +2005,25 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } + @Override + public boolean equals(Object o) { + return super.equals(o); //To change body of overridden methods use File | Settings | File Templates. + } + private void implementNetworkElementsAndResources(DeployDestination dest, ReservationContext context, - NetworkVO network, NetworkOfferingVO offering) + NetworkVO network, NetworkOfferingVO offering) throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException { - // If this is a 1) guest virtual network 2) network has sourceNat service 3) network offering does not support a - // Shared source NAT rule, - // associate a source NAT IP (if one isn't already associated with the network) + + // Associate a source NAT IP (if one isn't already associated with the network) if this is a + // 1) 'Isolated' or 'Shared' guest virtual network in the advance zone + // 2) network has sourceNat service + // 3) network offering does not support a shared source NAT rule boolean sharedSourceNat = offering.getSharedSourceNat(); - - if (network.getGuestType() == Network.GuestType.Isolated - && areServicesSupportedInNetwork(network.getId(), Service.SourceNat) - && !sharedSourceNat) { + DataCenter zone = _dcDao.findById(network.getDataCenterId()); + if (!sharedSourceNat && areServicesSupportedInNetwork(network.getId(), Service.SourceNat) + && (network.getGuestType() == Network.GuestType.Isolated || + (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced))) { List ips = null; if (network.getVpcId() != null) { @@ -2029,9 +2054,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); } + if (s_logger.isDebugEnabled()) { s_logger.debug("Asking " + element.getName() + " to implemenet " + network); } + if (!element.implement(network, offering, dest, context)) { CloudRuntimeException ex = new CloudRuntimeException("Failed to implement provider " + element.getProvider().getName() + " for network with specified id"); ex.addProxyObject(network, network.getId(), "networkId"); @@ -2471,6 +2498,82 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } + private void checkSharedNetworkCidrOverlap(Long zoneId, long physicalNetworkId, String cidr) { + if (zoneId == null || cidr == null) { + return; + } + + DataCenter zone = _dcDao.findById(zoneId); + List networks = _networksDao.listByZone(zoneId); + Map networkToCidr = new HashMap(); + + // check for CIDR overlap with all possible CIDR for isolated guest networks + // in the zone when using external networking + PhysicalNetworkVO pNetwork = _physicalNetworkDao.findById(physicalNetworkId); + if (pNetwork.getVnet() != null) { + String vlanRange[] = pNetwork.getVnet().split("-"); + int lowestVlanTag = Integer.valueOf(vlanRange[0]); + int highestVlanTag = Integer.valueOf(vlanRange[1]); + for (int vlan=lowestVlanTag; vlan <= highestVlanTag; ++vlan) { + int offset = vlan - lowestVlanTag; + String globalVlanBits = _configDao.getValue(Config.GuestVlanBits.key()); + int cidrSize = 8 + Integer.parseInt(globalVlanBits); + String guestNetworkCidr = zone.getGuestNetworkCidr(); + String[] cidrTuple = guestNetworkCidr.split("\\/"); + long newCidrAddress = (NetUtils.ip2Long(cidrTuple[0]) & 0xff000000) | (offset << (32 - cidrSize)); + if (NetUtils.isNetworksOverlap(NetUtils.long2Ip(newCidrAddress), cidr)) { + throw new InvalidParameterValueException("Specified CIDR for shared network conflict with CIDR that is reserved for zone vlan " + vlan); + } + } + } + + // check for CIDR overlap with all CIDR's of the shared networks in the zone + for (NetworkVO network : networks) { + if (network.getGuestType() == GuestType.Isolated) { + continue; + } + if (network.getCidr() != null) { + networkToCidr.put(network.getId(), network.getCidr()); + } + } + if (networkToCidr != null && !networkToCidr.isEmpty()) { + for (long networkId : networkToCidr.keySet()) { + String ntwkCidr = networkToCidr.get(networkId); + if (NetUtils.isNetworksOverlap(ntwkCidr, cidr)) { + throw new InvalidParameterValueException("Specified CIDR for shared network conflict with CIDR of a shared network in the zone."); + } + } + } + } + public void checkVirtualNetworkCidrOverlap(Long zoneId, String cidr) { + if (zoneId == null) { + return; + } + if (cidr == null) { + return; + } + List networks = _networksDao.listByZone(zoneId); + Map networkToCidr = new HashMap(); + for (NetworkVO network : networks) { + if (network.getGuestType() != GuestType.Isolated) { + continue; + } + if (network.getCidr() != null) { + networkToCidr.put(network.getId(), network.getCidr()); + } + } + if (networkToCidr == null || networkToCidr.isEmpty()) { + return; + } + + for (long networkId : networkToCidr.keySet()) { + String ntwkCidr = networkToCidr.get(networkId); + if (NetUtils.isNetworksOverlap(ntwkCidr, cidr)) { + throw new InvalidParameterValueException("Warning: The specified existing network has conflict CIDR subnets with new network!"); + } + } + } + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_NETWORK_CREATE, eventDescription = "creating network") @@ -2664,10 +2767,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - if (cidr != null && networkOfferingIsConfiguredForExternalNetworking(networkOfferingId)) { - throw new InvalidParameterValueException("Cannot specify CIDR when using network offering with external devices!"); + Collection ntwkProviders = finalizeServicesAndProvidersForNetwork(ntwkOff, physicalNetworkId).values(); + if (cidr != null && providersConfiguredForExternalNetworking(ntwkProviders)) { + if (ntwkOff.getGuestType() == GuestType.Shared && (zone.getNetworkType() == NetworkType.Advanced) && + isSharedNetworkOfferingWithServices(networkOfferingId)) { + // validate if CIDR specified overlaps with any of the CIDR's allocated for isolated networks and shared networks in the zone + checkSharedNetworkCidrOverlap(zoneId, pNtwk.getId(), cidr); + } else { + throw new InvalidParameterValueException("Cannot specify CIDR when using network offering with external devices!"); + } } + // Vlan is created in 2 cases - works in Advance zone only: // 1) GuestType is Shared // 2) GuestType is Isolated, but SourceNat service is disabled @@ -2850,10 +2961,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists in zone " + zoneId); } } else { - //don't allow to create Shared network with Vlan that already exists in the zone for Isolated networks - if (_networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Isolated) > 0) { - throw new InvalidParameterValueException("Isolated network with vlan " + vlanId + " already exists " + - "in zone " + zoneId); + //don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or + //shared network with same Vlan ID in the zone + if (_networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Isolated) > 0 || + _networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Shared) > 0) { + throw new InvalidParameterValueException("There is a isolated/shared network with vlan id: " + vlanId + " already exists " + "in zone " + zoneId); } } } @@ -3441,7 +3553,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag applyProfileToNetwork(network, profile); - network.setState(Network.State.Allocated); + DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); + if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId()) && (zone.getNetworkType() == NetworkType.Advanced)) { + network.setState(Network.State.Setup); + } else { + network.setState(Network.State.Allocated); + } + network.setRestartRequired(false); _networksDao.update(network.getId(), network); _networksDao.clearCheckForGc(networkId); @@ -4366,17 +4484,28 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return false; } } - - public boolean networkOfferingIsConfiguredForExternalNetworking(long networkOfferingId) { - boolean netscalerInNetworkOffering = isProviderForNetworkOffering(Network.Provider.Netscaler, networkOfferingId); - boolean juniperInNetworkOffering = isProviderForNetworkOffering(Network.Provider.JuniperSRX, networkOfferingId); - boolean f5InNetworkOffering = isProviderForNetworkOffering(Network.Provider.F5BigIp, networkOfferingId); - - if (netscalerInNetworkOffering || juniperInNetworkOffering || f5InNetworkOffering) { - return true; - } else { - return false; + + public boolean providersConfiguredForExternalNetworking(Collection providers) { + for(String providerStr : providers){ + Provider provider = Network.Provider.getProvider(providerStr); + if(provider.isExternal()){ + return true; + } } + return false; + } + + public boolean isSharedNetworkOfferingWithServices(long networkOfferingId) { + NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId); + if ( (networkOffering.getGuestType() == Network.GuestType.Shared) && ( + areServicesSupportedByNetworkOffering(networkOfferingId, Service.SourceNat) || + areServicesSupportedByNetworkOffering(networkOfferingId, Service.StaticNat) || + areServicesSupportedByNetworkOffering(networkOfferingId, Service.Firewall) || + areServicesSupportedByNetworkOffering(networkOfferingId, Service.PortForwarding) || + areServicesSupportedByNetworkOffering(networkOfferingId, Service.Lb))) { + return true; + } + return false; } @Override @@ -4461,18 +4590,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public List listNetworksForAccount(long accountId, long zoneId, Network.GuestType type) { - List accountNetworks = new ArrayList(); - List zoneNetworks = _networksDao.listByZone(zoneId); - - for (NetworkVO network : zoneNetworks) { - if (!isNetworkSystem(network)) { - if (network.getGuestType() == Network.GuestType.Shared || !_networksDao.listBy(accountId, network.getId()).isEmpty()) { - if (type == null || type == network.getGuestType()) { - accountNetworks.add(network); - } - } - } - } + List accountNetworks = _networksDao.listNetworksByAccount(accountId, zoneId, type, false); return accountNetworks; } @@ -4651,7 +4769,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } if (networkOfferingId != oldNetworkOfferingId) { - if (networkOfferingIsConfiguredForExternalNetworking(networkOfferingId) != networkOfferingIsConfiguredForExternalNetworking(oldNetworkOfferingId) + NetworkOffering oldNtwkOff = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId); + Collection newProviders = finalizeServicesAndProvidersForNetwork(networkOffering, network.getPhysicalNetworkId()).values(); + Collection oldProviders = finalizeServicesAndProvidersForNetwork(oldNtwkOff, network.getPhysicalNetworkId()).values(); + + if (providersConfiguredForExternalNetworking(newProviders) != providersConfiguredForExternalNetworking(oldProviders) && !changeCidr) { throw new InvalidParameterValueException("Updating network failed since guest CIDR needs to be changed!"); } diff --git a/server/src/com/cloud/network/NetworkUsageManagerImpl.java b/server/src/com/cloud/network/NetworkUsageManagerImpl.java index 3207c6f0e37..b30f1858922 100755 --- a/server/src/com/cloud/network/NetworkUsageManagerImpl.java +++ b/server/src/com/cloud/network/NetworkUsageManagerImpl.java @@ -108,6 +108,8 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta @Inject ResourceManager _resourceMgr; ScheduledExecutorService _executor; int _networkStatsInterval; + String _TSinclZones; + String _TSexclZones; protected SearchBuilder AllocatedIpSearch; @Override @@ -148,8 +150,8 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta hostParams.put("zone", String.valueOf(zoneId)); hostParams.put("ipaddress", ipAddress); hostParams.put("url", cmd.getUrl()); - //hostParams("numRetries", numRetries); - //hostParams("timeout", timeout); + hostParams.put("inclZones", (cmd.getInclZones() != null) ? cmd.getInclZones() : _TSinclZones); + hostParams.put("exclZones", (cmd.getExclZones() != null) ? cmd.getExclZones() : _TSexclZones); hostParams.put("guid", guid); hostParams.put("name", guid); @@ -162,7 +164,14 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta Map hostDetails = new HashMap(); hostDetails.put("url", cmd.getUrl()); hostDetails.put("last_collection", ""+System.currentTimeMillis()); - + if(cmd.getInclZones() != null){ + hostDetails.put("inclZones", cmd.getInclZones()); + } + if(cmd.getExclZones() != null){ + hostDetails.put("exclZones", cmd.getExclZones()); + } + + Host trafficMonitor = _resourceMgr.addHost(zoneId, resource, Host.Type.TrafficMonitor, hostDetails); return trafficMonitor; } @@ -222,6 +231,8 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta AllocatedIpSearch.done(); _networkStatsInterval = NumbersUtil.parseInt(_configDao.getValue(Config.DirectNetworkStatsInterval.key()), 86400); + _TSinclZones = _configDao.getValue(Config.TrafficSentinelIncludeZones.key()); + _TSexclZones = _configDao.getValue(Config.TrafficSentinelExcludeZones.key()); _agentMgr.registerForHostEvents(new DirectNetworkStatsListener( _networkStatsInterval), true, false, false); _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); return true; @@ -372,7 +383,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta //Get usage for Ips which were assigned for the entire duration if(fullDurationIpUsage.size() > 0){ - DirectNetworkUsageCommand cmd = new DirectNetworkUsageCommand(IpList, lastCollection, now); + DirectNetworkUsageCommand cmd = new DirectNetworkUsageCommand(IpList, lastCollection, now, _TSinclZones, _TSexclZones); DirectNetworkUsageAnswer answer = (DirectNetworkUsageAnswer) _agentMgr.easySend(host.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; @@ -405,7 +416,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta for(UsageIPAddressVO usageIp : IpPartialUsage){ IpList = new ArrayList() ; IpList.add(usageIp.getAddress()); - DirectNetworkUsageCommand cmd = new DirectNetworkUsageCommand(IpList, usageIp.getAssigned(), usageIp.getReleased()); + DirectNetworkUsageCommand cmd = new DirectNetworkUsageCommand(IpList, usageIp.getAssigned(), usageIp.getReleased(), _TSinclZones, _TSexclZones); DirectNetworkUsageAnswer answer = (DirectNetworkUsageAnswer) _agentMgr.easySend(host.getId(), cmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; @@ -532,8 +543,11 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { - // TODO Auto-generated method stub - return null; + if(host.getType() != Host.Type.TrafficMonitor){ + return null; + } + + return new DeleteHostAnswer(true); } } diff --git a/server/src/com/cloud/network/dao/NetworkDao.java b/server/src/com/cloud/network/dao/NetworkDao.java index a2e37b7b33b..4079955c2e9 100644 --- a/server/src/com/cloud/network/dao/NetworkDao.java +++ b/server/src/com/cloud/network/dao/NetworkDao.java @@ -108,4 +108,6 @@ public interface NetworkDao extends GenericDao { long countVpcNetworks(long vpcId); + List listNetworksByAccount(long accountId, long zoneId, Network.GuestType type, boolean isSystem); + } diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index cbfec895b32..8228393f93f 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -72,8 +72,8 @@ public class NetworkDaoImpl extends GenericDaoBase implements N final SearchBuilder SourceNATSearch; final GenericSearchBuilder CountByZoneAndURI; final GenericSearchBuilder VpcNetworksCount; - - + final SearchBuilder OfferingAccountNetworkSearch; + ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class); NetworkAccountDaoImpl _accountsDao = ComponentLocator.inject(NetworkAccountDaoImpl.class); NetworkDomainDaoImpl _domainsDao = ComponentLocator.inject(NetworkDomainDaoImpl.class); @@ -202,6 +202,17 @@ public class NetworkDaoImpl extends GenericDaoBase implements N VpcNetworksCount.select(null, Func.COUNT, VpcNetworksCount.entity().getId()); VpcNetworksCount.done(); + OfferingAccountNetworkSearch = createSearchBuilder(); + OfferingAccountNetworkSearch.select(null, Func.DISTINCT, OfferingAccountNetworkSearch.entity().getId()); + SearchBuilder ntwkOfferingJoin = _ntwkOffDao.createSearchBuilder(); + ntwkOfferingJoin.and("isSystem", ntwkOfferingJoin.entity().isSystemOnly(), Op.EQ); + OfferingAccountNetworkSearch.join("ntwkOfferingSearch", ntwkOfferingJoin, OfferingAccountNetworkSearch.entity().getNetworkOfferingId(), ntwkOfferingJoin.entity().getId(), JoinBuilder.JoinType.LEFT); + SearchBuilder ntwkAccountJoin = _accountsDao.createSearchBuilder(); + ntwkAccountJoin.and("accountId", ntwkAccountJoin.entity().getAccountId(), Op.EQ); + OfferingAccountNetworkSearch.join("ntwkAccountSearch", ntwkAccountJoin, OfferingAccountNetworkSearch.entity().getId(), ntwkAccountJoin.entity().getNetworkId(), JoinBuilder.JoinType.INNER); + OfferingAccountNetworkSearch.and("zoneId", OfferingAccountNetworkSearch.entity().getDataCenterId(), Op.EQ); + OfferingAccountNetworkSearch.and("type", OfferingAccountNetworkSearch.entity().getGuestType(), Op.EQ); + OfferingAccountNetworkSearch.done(); } @Override @@ -551,4 +562,16 @@ public class NetworkDaoImpl extends GenericDaoBase implements N sc.setParameters("vpcId", vpcId); return customSearch(sc, null).get(0); } + + @Override + public List listNetworksByAccount(long accountId, long zoneId, Network.GuestType type, boolean isSystem) { + SearchCriteria sc = OfferingAccountNetworkSearch.create(); + sc.setJoinParameters("ntwkOfferingSearch", "isSystem", isSystem); + sc.setJoinParameters("ntwkAccountSearch", "accountId", accountId); + sc.setParameters("zoneId", zoneId); + sc.setParameters("type", type); + + List networks = search(sc, null); + return networks; + } } diff --git a/server/src/com/cloud/network/element/VpcVirtualRouterElement.java b/server/src/com/cloud/network/element/VpcVirtualRouterElement.java index 2a2d05a76ec..0acc47d7d88 100644 --- a/server/src/com/cloud/network/element/VpcVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VpcVirtualRouterElement.java @@ -304,7 +304,7 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc Map networkACLCapabilities = new HashMap(); networkACLCapabilities.put(Capability.SupportedProtocols, "tcp,udp,icmp"); capabilities.put(Service.NetworkACL, networkACLCapabilities); - + return capabilities; } diff --git a/server/src/com/cloud/network/guru/GuestNetworkGuru.java b/server/src/com/cloud/network/guru/GuestNetworkGuru.java index cebfb08e952..2a8a092b835 100755 --- a/server/src/com/cloud/network/guru/GuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/GuestNetworkGuru.java @@ -442,15 +442,17 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur @Override public void shutdown(NetworkProfile profile, NetworkOffering offering) { - s_logger.debug("Releasing vnet for the network id=" + profile.getId()); - if (profile.getBroadcastUri() != null && !offering.getSpecifyVlan()) { + + if (profile.getBroadcastDomainType() == BroadcastDomainType.Vlan && + profile.getBroadcastUri() != null && !offering.getSpecifyVlan()) { + s_logger.debug("Releasing vnet for the network id=" + profile.getId()); _dcDao.releaseVnet(profile.getBroadcastUri().getHost(), profile.getDataCenterId(), profile.getPhysicalNetworkId(), profile.getAccountId(), profile.getReservationId()); EventUtils.saveEvent(UserContext.current().getCallerUserId(), profile.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_RELEASE, "Released Zone Vlan: " +profile.getBroadcastUri().getHost()+" for Network: "+profile.getId(), 0); - profile.setBroadcastUri(null); } + profile.setBroadcastUri(null); } @Override diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 2026c8e6ba3..e9ea6fb445b 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -338,6 +338,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian int _routerCheckInterval = 30; protected ServiceOfferingVO _offering; private String _dnsBasicZoneUpdates = "all"; + private Set _guestOSNeedGatewayOnNonDefaultNetwork = new HashSet(); private boolean _disable_rp_filter = false; int _routerExtraPublicNics = 2; @@ -498,6 +499,14 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian if(virtualRouter == null){ throw new CloudRuntimeException("Failed to stop router with id " + routerId); } + + // Clear stop pending flag after stopped successfully + if (router.isStopPending()) { + s_logger.info("Clear the stop pending flag of router " + router.getHostName() + " after stop router successfully"); + router.setStopPending(false); + router = _routerDao.persist(router); + virtualRouter.setStopPending(false); + } return virtualRouter; } @@ -581,6 +590,14 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian _routerExtraPublicNics = NumbersUtil.parseInt(_configDao.getValue(Config.RouterExtraPublicNics.key()), 2); + String guestOSString = configs.get("network.dhcp.nondefaultnetwork.setgateway.guestos"); + if (guestOSString != null) { + String[] guestOSList = guestOSString.split(","); + for (String os : guestOSList) { + _guestOSNeedGatewayOnNonDefaultNetwork.add(os); + } + } + String value = configs.get("start.retry"); _retry = NumbersUtil.parseInt(value, 2); @@ -1389,15 +1406,31 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian offeringId = _offering.getId(); } - PublicIp sourceNatIp = null; - if (publicNetwork) { - sourceNatIp = _networkMgr.assignSourceNatIpAddressToGuestNetwork(owner, guestNetwork); - } - // 3) deploy virtual router(s) int count = routerCount - routers.size(); DeploymentPlan plan = planAndRouters.first(); for (int i = 0; i < count; i++) { + PublicIp sourceNatIp = null; + if (publicNetwork) { + int failCount = 0; + // Generate different MAC for VR + while (sourceNatIp == null) { + sourceNatIp = _networkMgr.assignSourceNatIpAddressToGuestNetwork(owner, guestNetwork); + NicVO nic = _nicDao.findByMacAddress(sourceNatIp.getMacAddress()); + // We got duplicate MAC here, so regenerate the mac + if (nic != null) { + s_logger.debug("Failed to find a different mac for redundant router. Try again. The current mac is " + sourceNatIp.getMacAddress()); + sourceNatIp = null; + failCount ++; + } + //Prevent infinite loop + if (failCount > 3) { + s_logger.error("Failed to find a different mac for redundant router! Abort operation!"); + throw new InsufficientAddressCapacityException("Failed to find a different mac for redundant router", null, offeringId); + } + } + } + List> networks = createRouterNetworks(owner, isRedundant, plan, guestNetwork, new Pair(publicNetwork, sourceNatIp)); //don't start the router as we are holding the network lock that needs to be released at the end of router allocation @@ -2410,6 +2443,11 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian ConcurrentOperationException, ResourceUnavailableException { s_logger.debug("Starting router " + router); if (_itMgr.start(router, params, user, caller, planToDeploy) != null) { + if (router.isStopPending()) { + s_logger.info("Clear the stop pending flag of router " + router.getHostName() + " after start router successfully!"); + router.setStopPending(false); + router = _routerDao.persist(router); + } // We don't want the failure of VPN Connection affect the status of router, so we try to make connection // only after router start successfully Long vpcId = router.getVpcId(); @@ -2649,6 +2687,12 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian } } + //After start network, check if it's already running + router = _routerDao.findById(routerId); + if (router.getState() == State.Running) { + return router; + } + UserVO user = _userDao.findById(UserContext.current().getCallerUserId()); Map params = new HashMap(); if (reprogramNetwork) { @@ -2915,14 +2959,22 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), vm.getHostName()); DataCenterVO dcVo = _dcDao.findById(router.getDataCenterIdToDeployIn()); String gatewayIp = findGatewayIp(vm.getId()); + boolean needGateway = true; if (!gatewayIp.equals(nic.getGateway())) { + needGateway = false; GuestOSVO guestOS = _guestOSDao.findById(vm.getGuestOSId()); - // Don't set dhcp:router option for non-default nic on CentOS/RHEL, because they would set routing on wrong interface - // This is tricky, we may need to update this when we have more information on various OS's behavior - if (guestOS.getDisplayName().startsWith("CentOS") || guestOS.getDisplayName().startsWith("Red Hat Enterprise")) { - gatewayIp = "0.0.0.0"; + // Do set dhcp:router option for non-default nic on certain OS(including Windows), and leave other OS unset. + // Because some OS(e.g. CentOS) would set routing on wrong interface + for (String name : _guestOSNeedGatewayOnNonDefaultNetwork) { + if (guestOS.getDisplayName().startsWith(name)) { + needGateway = true; + break; + } } } + if (!needGateway) { + gatewayIp = "0.0.0.0"; + } dhcpCommand.setDefaultRouter(gatewayIp); dhcpCommand.setDefaultDns(findDefaultDnsIp(vm.getId())); @@ -3305,6 +3357,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian List routers = _routerDao.listIsolatedByHostId(host.getId()); for (DomainRouterVO router : routers) { if (router.isStopPending()) { + s_logger.info("Stopping router " + router.getInstanceName() + " due to stop pending flag found!"); State state = router.getState(); if (state != State.Stopped && state != State.Destroyed) { try { diff --git a/server/src/com/cloud/network/rules/RulesManagerImpl.java b/server/src/com/cloud/network/rules/RulesManagerImpl.java index dced8f9ca97..dd091740021 100755 --- a/server/src/com/cloud/network/rules/RulesManagerImpl.java +++ b/server/src/com/cloud/network/rules/RulesManagerImpl.java @@ -80,6 +80,11 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.Type; import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.UserVmDao; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.util.*; @Local(value = { RulesManager.class, RulesService.class }) public class RulesManagerImpl implements RulesManager, RulesService, Manager { @@ -1184,11 +1189,12 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { Network guestNetwork = _networkMgr.getNetwork(ipAddress.getAssociatedWithNetworkId()); NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); if (offering.getElasticIp()) { - getSystemIpAndEnableStaticNatForVm(_vmDao.findById(vmId), true); - return true; - } else { - return disableStaticNat(ipId, caller, ctx.getCallerUserId(), false); + if (offering.getAssociatePublicIP()) { + getSystemIpAndEnableStaticNatForVm(_vmDao.findById(vmId), true); + return true; + } } + return disableStaticNat(ipId, caller, ctx.getCallerUserId(), false); } @Override @@ -1374,7 +1380,11 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { Network guestNetwork = _networkMgr.getNetwork(nic.getNetworkId()); NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); if (offering.getElasticIp()) { - + boolean isSystemVM = (vm.getType() == Type.ConsoleProxy || vm.getType() == Type.SecondaryStorageVm); + // for user VM's associate public IP only if offering is marked to associate a public IP by default on start of VM + if (!isSystemVM && !offering.getAssociatePublicIP()) { + continue; + } // check if there is already static nat enabled if (_ipAddressDao.findByAssociatedVmId(vm.getId()) != null && !getNewIp) { s_logger.debug("Vm " + vm + " already has ip associated with it in guest network " + guestNetwork); @@ -1389,7 +1399,6 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { s_logger.debug("Allocated system ip " + ip + ", now enabling static nat on it for vm " + vm); - boolean isSystemVM = (vm.getType() == Type.ConsoleProxy || vm.getType() == Type.SecondaryStorageVm); try { success = enableStaticNat(ip.getId(), vm.getId(), guestNetwork.getId(), isSystemVM); } catch (NetworkRuleConflictException ex) { diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index 6cb1d2aebc8..ca315f981b8 100755 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.offerings; +import com.cloud.network.Networks; + import java.util.Date; import java.util.UUID; @@ -34,6 +36,10 @@ import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; import com.cloud.utils.db.GenericDao; +import javax.persistence.*; +import java.util.Date; +import java.util.UUID; + @Entity @Table(name = "network_offerings") public class NetworkOfferingVO implements NetworkOffering { @@ -122,6 +128,9 @@ public class NetworkOfferingVO implements NetworkOffering { @Column(name = "elastic_lb_service") boolean elasticLb; + @Column(name = "eip_associate_public_ip") + boolean eipAssociatePublicIp; + @Override public String getDisplayText() { return displayText; @@ -282,18 +291,20 @@ public class NetworkOfferingVO implements NetworkOffering { this.redundantRouter = false; this.elasticIp = false; this.elasticLb = false; + this.eipAssociatePublicIp = true; this.specifyIpRanges = specifyIpRanges; } public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, boolean isDefault, Availability availability, String tags, Network.GuestType guestType, boolean conserveMode, boolean dedicatedLb, boolean sharedSourceNat, boolean redundantRouter, boolean elasticIp, boolean elasticLb, - boolean specifyIpRanges) { + boolean associatePublicIP, boolean specifyIpRanges) { this(name, displayText, trafficType, systemOnly, specifyVlan, rateMbps, multicastRateMbps, isDefault, availability, tags, guestType, conserveMode, specifyIpRanges); this.dedicatedLB = dedicatedLb; this.sharedSourceNat = sharedSourceNat; this.redundantRouter = redundantRouter; this.elasticIp = elasticIp; this.elasticLb = elasticLb; + this.eipAssociatePublicIp = associatePublicIP; } public NetworkOfferingVO() { @@ -355,6 +366,11 @@ public class NetworkOfferingVO implements NetworkOffering { return elasticIp; } + @Override + public boolean getAssociatePublicIP() { + return eipAssociatePublicIp; + } + @Override public boolean getElasticLb() { return elasticLb; diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java index cfdb8becdcd..db01c3dd435 100755 --- a/server/src/com/cloud/resource/ResourceManagerImpl.java +++ b/server/src/com/cloud/resource/ResourceManagerImpl.java @@ -35,6 +35,11 @@ import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd; import org.apache.cloudstack.api.command.admin.cluster.DeleteClusterCmd; import org.apache.cloudstack.api.command.admin.host.*; import org.apache.cloudstack.api.command.admin.swift.ListSwiftsCmd; +import com.cloud.api.commands.AddS3Cmd; +import com.cloud.api.commands.ListS3sCmd; +import com.cloud.storage.S3; +import com.cloud.storage.S3VO; +import com.cloud.storage.s3.S3Manager; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; @@ -177,6 +182,8 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma @Inject protected SwiftManager _swiftMgr; @Inject + protected S3Manager _s3Mgr; + @Inject protected HostDetailsDao _hostDetailsDao; @Inject protected ConfigurationDao _configDao; @@ -557,6 +564,16 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma return _swiftMgr.listSwifts(cmd); } + @Override + public S3 discoverS3(final AddS3Cmd cmd) throws DiscoveryException { + return this._s3Mgr.addS3(cmd); + } + + @Override + public List listS3s(final ListS3sCmd cmd) { + return this._s3Mgr.listS3s(cmd); + } + private List discoverHostsFull(Long dcId, Long podId, Long clusterId, String clusterName, String url, String username, String password, String hypervisorType, List hostTags, Map params) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException { URI uri = null; diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index 3c155ed0e5f..c0c29ed8eb8 100755 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -16,36 +16,6 @@ // under the License. package com.cloud.server; -import java.io.DataInputStream; -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.UUID; -import java.util.regex.Pattern; - -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; - -import org.apache.commons.codec.binary.Base64; -import org.apache.log4j.Logger; - import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationVO; import com.cloud.configuration.Resource; @@ -75,18 +45,13 @@ import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.NetworkDao; -import com.cloud.network.guru.ControlNetworkGuru; -import com.cloud.network.guru.DirectPodBasedNetworkGuru; -import com.cloud.network.guru.PodBasedNetworkGuru; -import com.cloud.network.guru.PublicNetworkGuru; -import com.cloud.network.guru.StorageNetworkGuru; +import com.cloud.network.guru.*; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.offerings.NetworkOfferingServiceMapVO; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; -import com.cloud.server.auth.UserAuthenticator; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; @@ -98,7 +63,6 @@ import com.cloud.user.User; import com.cloud.user.dao.AccountDao; import com.cloud.utils.PasswordGenerator; import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.db.DB; @@ -107,6 +71,20 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; import com.cloud.utils.script.Script; import com.cloud.uuididentity.dao.IdentityDao; +import org.apache.commons.codec.binary.Base64; +import org.apache.log4j.Logger; + +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import java.io.*; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.security.NoSuchAlgorithmException; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; +import java.util.regex.Pattern; public class ConfigurationServerImpl implements ConfigurationServer { public static final Logger s_logger = Logger.getLogger(ConfigurationServerImpl.class.getName()); @@ -266,7 +244,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { // store the public and private keys in the database updateKeyPairs(); - + // generate a random password for system vm updateSystemvmPassword(); @@ -338,7 +316,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { } // insert system user insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created)" + - " VALUES (1, 'system', RAND(), 1, 'system', 'cloud', now())"; + " VALUES (1, 'system', RAND(), 1, 'system', 'cloud', now())"; txn = Transaction.currentTxn(); try { PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql); @@ -352,7 +330,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { String username = "admin"; String firstname = "admin"; String lastname = "cloud"; - + // create an account for the admin user first insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (" + id + ", '" + username + "', '1', '1')"; txn = Transaction.currentTxn(); @@ -540,29 +518,29 @@ public class ConfigurationServerImpl implements ConfigurationServer { if (!userid.startsWith("cloud")) { return; } - + if (!Boolean.valueOf(_configDao.getValue("system.vm.random.password"))) { - return; + return; } - String already = _configDao.getValue("system.vm.password"); - if (already == null) { - Transaction txn = Transaction.currentTxn(); - try { - String rpassword = PasswordGenerator.generatePresharedKey(8); - String wSql = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " - + "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword - + "','randmon password generated each management server starts for system vm')"; - PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql); - stmt.executeUpdate(wSql); - s_logger.info("Updated systemvm password in database"); - } catch (SQLException e) { - s_logger.error("Cannot retrieve systemvm password", e); - } - } + String already = _configDao.getValue("system.vm.password"); + if (already == null) { + Transaction txn = Transaction.currentTxn(); + try { + String rpassword = PasswordGenerator.generatePresharedKey(8); + String wSql = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + + "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword + + "','randmon password generated each management server starts for system vm')"; + PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql); + stmt.executeUpdate(wSql); + s_logger.info("Updated systemvm password in database"); + } catch (SQLException e) { + s_logger.error("Cannot retrieve systemvm password", e); + } + } + + } - } - @Override @DB public void updateKeyPairs() { @@ -570,17 +548,17 @@ public class ConfigurationServerImpl implements ConfigurationServer { String username = System.getProperty("user.name"); Boolean devel = Boolean.valueOf(_configDao.getValue("developer")); - if (!username.equalsIgnoreCase("cloud") && !devel) { + if (!username.equalsIgnoreCase("cloud") || !devel) { s_logger.warn("Systemvm keypairs could not be set. Management server should be run as cloud user, or in development mode."); return; } String already = _configDao.getValue("ssh.privatekey"); String homeDir = null; homeDir = Script.runSimpleBashScript("echo ~" + username); - if (homeDir == null) { + if (homeDir == null) { throw new CloudRuntimeException("Cannot get home directory for account: " + username); } - + if (s_logger.isInfoEnabled()) { s_logger.info("Processing updateKeyPairs"); } @@ -658,11 +636,11 @@ public class ConfigurationServerImpl implements ConfigurationServer { } s_logger.info("Going to update systemvm iso with generated keypairs if needed"); try { - injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath()); + injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath()); } catch (CloudRuntimeException e) { - if (!devel) { - throw new CloudRuntimeException(e.getMessage()); - } + if (!devel) { + throw new CloudRuntimeException(e.getMessage()); + } } } @@ -928,7 +906,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { defaultSharedSGNetworkOffering.setState(NetworkOffering.State.Enabled); defaultSharedSGNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultSharedSGNetworkOffering); - + for (Service service : defaultSharedSGNetworkOfferingProviders.keySet()) { NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultSharedSGNetworkOffering.getId(), service, defaultSharedSGNetworkOfferingProviders.get(service)); _ntwkOfferingServiceMapDao.persist(offService); @@ -993,7 +971,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { "Offering for Shared networks with Elastic IP and Elastic LB capabilities", TrafficType.Guest, false, true, null, null, true, Availability.Optional, - null, Network.GuestType.Shared, true, false, false, false, true, true, true); + null, Network.GuestType.Shared, true, false, false, false, true, true, true, true); defaultNetscalerNetworkOffering.setState(NetworkOffering.State.Enabled); defaultNetscalerNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetscalerNetworkOffering); @@ -1003,7 +981,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } - + // Offering #6 NetworkOfferingVO defaultNetworkOfferingForVpcNetworks = new NetworkOfferingVO( NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks, @@ -1014,7 +992,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { defaultNetworkOfferingForVpcNetworks.setState(NetworkOffering.State.Enabled); defaultNetworkOfferingForVpcNetworks = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetworkOfferingForVpcNetworks); - + Map defaultVpcNetworkOfferingProviders = new HashMap(); defaultVpcNetworkOfferingProviders.put(Service.Dhcp, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProviders.put(Service.Dns, Provider.VPCVirtualRouter); @@ -1026,14 +1004,14 @@ public class ConfigurationServerImpl implements ConfigurationServer { defaultVpcNetworkOfferingProviders.put(Service.StaticNat, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProviders.put(Service.PortForwarding, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProviders.put(Service.Vpn, Provider.VPCVirtualRouter); - + for (Service service : defaultVpcNetworkOfferingProviders.keySet()) { NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO (defaultNetworkOfferingForVpcNetworks.getId(), service, defaultVpcNetworkOfferingProviders.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } - + // Offering #7 NetworkOfferingVO defaultNetworkOfferingForVpcNetworksNoLB = new NetworkOfferingVO( NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB, @@ -1044,7 +1022,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { defaultNetworkOfferingForVpcNetworksNoLB.setState(NetworkOffering.State.Enabled); defaultNetworkOfferingForVpcNetworksNoLB = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetworkOfferingForVpcNetworksNoLB); - + Map defaultVpcNetworkOfferingProvidersNoLB = new HashMap(); defaultVpcNetworkOfferingProvidersNoLB.put(Service.Dhcp, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProvidersNoLB.put(Service.Dns, Provider.VPCVirtualRouter); @@ -1055,16 +1033,16 @@ public class ConfigurationServerImpl implements ConfigurationServer { defaultVpcNetworkOfferingProvidersNoLB.put(Service.StaticNat, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProvidersNoLB.put(Service.PortForwarding, Provider.VPCVirtualRouter); defaultVpcNetworkOfferingProvidersNoLB.put(Service.Vpn, Provider.VPCVirtualRouter); - + for (Service service : defaultVpcNetworkOfferingProvidersNoLB.keySet()) { NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO (defaultNetworkOfferingForVpcNetworksNoLB.getId(), service, defaultVpcNetworkOfferingProvidersNoLB.get(service)); _ntwkOfferingServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService); } - - - + + + txn.commit(); } diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java index 824af6a744c..110e9558bb0 100755 --- a/server/src/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/com/cloud/storage/StorageManagerImpl.java @@ -151,11 +151,13 @@ import com.cloud.storage.dao.StoragePoolWorkDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplateHostDao; import com.cloud.storage.dao.VMTemplatePoolDao; +import com.cloud.storage.dao.VMTemplateS3Dao; import com.cloud.storage.dao.VMTemplateSwiftDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.dao.VolumeHostDao; import com.cloud.storage.download.DownloadMonitor; import com.cloud.storage.listener.StoragePoolMonitor; +import com.cloud.storage.s3.S3Manager; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.storage.snapshot.SnapshotScheduler; @@ -262,6 +264,10 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag @Inject protected VMTemplateSwiftDao _vmTemplateSwiftDao = null; @Inject + protected VMTemplateS3Dao _vmTemplateS3Dao; + @Inject + protected S3Manager _s3Mgr; + @Inject protected VMTemplateDao _vmTemplateDao = null; @Inject protected StoragePoolHostDao _poolHostDao = null; @@ -663,7 +669,6 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag String vdiUUID = null; Long snapshotId = snapshot.getId(); Long volumeId = snapshot.getVolumeId(); - String primaryStoragePoolNameLabel = pool.getUuid(); // pool's uuid is actually the namelabel. Long dcId = snapshot.getDataCenterId(); String secondaryStoragePoolUrl = _snapMgr.getSecondaryStorageURL(snapshot); long accountId = snapshot.getAccountId(); @@ -707,8 +712,10 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag try { if (snapshot.getSwiftId() != null && snapshot.getSwiftId() != 0) { _snapshotMgr.downloadSnapshotsFromSwift(snapshot); + } else if (snapshot.getS3Id() != null && snapshot.getS3Id() != 0) { + _snapshotMgr.downloadSnapshotsFromS3(snapshot); } - CreateVolumeFromSnapshotCommand createVolumeFromSnapshotCommand = new CreateVolumeFromSnapshotCommand(primaryStoragePoolNameLabel, secondaryStoragePoolUrl, dcId, accountId, volumeId, + CreateVolumeFromSnapshotCommand createVolumeFromSnapshotCommand = new CreateVolumeFromSnapshotCommand(pool, secondaryStoragePoolUrl, dcId, accountId, volumeId, backedUpSnapshotUuid, snapshot.getName(), _createVolumeFromSnapshotWait); CreateVolumeFromSnapshotAnswer answer; if (!_snapshotDao.lockInLockTable(snapshotId.toString(), 10)) { @@ -1281,7 +1288,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } URI uri = null; try { - uri = new URI(cmd.getUrl()); + uri = new URI(UriUtils.encodeURIComponent(cmd.getUrl())); if (uri.getScheme() == null) { throw new InvalidParameterValueException("scheme is null " + cmd.getUrl() + ", add nfs:// as a prefix"); } else if (uri.getScheme().equalsIgnoreCase("nfs")) { @@ -2983,6 +2990,14 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag if (tsvs != null && tsvs.size() > 0) { size = tsvs.get(0).getSize(); } + + if (size == null && _s3Mgr.isS3Enabled()) { + VMTemplateS3VO vmTemplateS3VO = _vmTemplateS3Dao.findOneByTemplateId(template.getId()); + if (vmTemplateS3VO != null) { + size = vmTemplateS3VO.getSize(); + } + } + if (size == null) { List sss = _vmTemplateHostDao.search(sc, null); if (sss == null || sss.size() == 0) { diff --git a/server/src/com/cloud/storage/dao/S3Dao.java b/server/src/com/cloud/storage/dao/S3Dao.java new file mode 100644 index 00000000000..ebea3531339 --- /dev/null +++ b/server/src/com/cloud/storage/dao/S3Dao.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.storage.dao; + +import com.cloud.agent.api.to.S3TO; +import com.cloud.storage.S3VO; +import com.cloud.utils.db.GenericDao; + +public interface S3Dao extends GenericDao { + + S3TO getS3TO(final Long id); + +} diff --git a/server/src/com/cloud/storage/dao/S3DaoImpl.java b/server/src/com/cloud/storage/dao/S3DaoImpl.java new file mode 100644 index 00000000000..6162e6ebf73 --- /dev/null +++ b/server/src/com/cloud/storage/dao/S3DaoImpl.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.storage.dao; + +import com.cloud.agent.api.to.S3TO; +import com.cloud.storage.S3VO; +import com.cloud.utils.db.GenericDaoBase; + +import javax.ejb.Local; + +@Local(S3Dao.class) +public class S3DaoImpl extends GenericDaoBase implements S3Dao { + + @Override + public S3TO getS3TO(final Long id) { + + if (id != null) { + + final S3VO s3VO = findById(id); + if (s3VO != null) { + return s3VO.toS3TO(); + } + + } + + // NOTE: Excluded listAll / shuffle operation implemented in SwiftDaoImpl ... + + return null; + + } +} diff --git a/server/src/com/cloud/storage/dao/VMTemplateDao.java b/server/src/com/cloud/storage/dao/VMTemplateDao.java index f5b6913df8a..1284ba103cf 100755 --- a/server/src/com/cloud/storage/dao/VMTemplateDao.java +++ b/server/src/com/cloud/storage/dao/VMTemplateDao.java @@ -71,4 +71,6 @@ public interface VMTemplateDao extends GenericDao { List listPrivateTemplatesByHost(Long hostId); public Long countTemplatesForAccount(long accountId); + List findTemplatesToSyncToS3(); + } diff --git a/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java b/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java index 0d9f5723f58..008922af45e 100755 --- a/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java +++ b/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java @@ -92,6 +92,14 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem private final String SELECT_TEMPLATE_SWIFT_REF = "SELECT t.id, t.unique_name, t.name, t.public, t.featured, t.type, t.hvm, t.bits, t.url, t.format, t.created, t.account_id, " + "t.checksum, t.display_text, t.enable_password, t.guest_os_id, t.bootable, t.prepopulate, t.cross_zones, t.hypervisor_type FROM vm_template t"; + + private static final String SELECT_S3_CANDIDATE_TEMPLATES = "SELECT t.id, t.unique_name, t.name, t.public, t.featured, " + + "t.type, t.hvm, t.bits, t.url, t.format, t.created, t.account_id, t.checksum, t.display_text, " + + "t.enable_password, t.guest_os_id, t.bootable, t.prepopulate, t.cross_zones, t.hypervisor_type " + + "FROM vm_template t JOIN template_host_ref r ON t.id=r.template_id JOIN host h ON h.id=r.host_id " + + "WHERE t.hypervisor_type IN (SELECT hypervisor_type FROM host) AND r.download_state = 'DOWNLOADED' AND " + + "r.template_id NOT IN (SELECT template_id FROM template_s3_ref) AND r.destroyed = 0 AND t.type <> 'PERHOST'"; + protected SearchBuilder TemplateNameSearch; protected SearchBuilder UniqueNameSearch; protected SearchBuilder tmpltTypeSearch; @@ -917,5 +925,10 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); } - + + @Override + public List findTemplatesToSyncToS3() { + return executeList(SELECT_S3_CANDIDATE_TEMPLATES, new Object[] {}); + } + } diff --git a/server/src/com/cloud/storage/dao/VMTemplateS3Dao.java b/server/src/com/cloud/storage/dao/VMTemplateS3Dao.java new file mode 100644 index 00000000000..d36fb3a2257 --- /dev/null +++ b/server/src/com/cloud/storage/dao/VMTemplateS3Dao.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.storage.dao; + +import com.cloud.storage.VMTemplateS3VO; +import com.cloud.utils.db.GenericDao; + +import java.util.List; + +public interface VMTemplateS3Dao extends GenericDao { + + List listByS3Id(long id); + + VMTemplateS3VO findOneByTemplateId(long id); + + VMTemplateS3VO findOneByS3Template(long s3Id, long templateId); + + void expungeAllByTemplateId(long templateId); + +} diff --git a/server/src/com/cloud/storage/dao/VMTemplateS3DaoImpl.java b/server/src/com/cloud/storage/dao/VMTemplateS3DaoImpl.java new file mode 100644 index 00000000000..f23b803bf68 --- /dev/null +++ b/server/src/com/cloud/storage/dao/VMTemplateS3DaoImpl.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.storage.dao; + +import static com.cloud.utils.db.SearchCriteria.Op.*; +import static com.cloud.storage.VMTemplateS3VO.*; + +import com.cloud.storage.VMTemplateS3VO; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +import javax.ejb.Local; +import java.util.List; + +@Local(VMTemplateS3Dao.class) +public class VMTemplateS3DaoImpl extends GenericDaoBase + implements VMTemplateS3Dao { + + private final SearchBuilder searchBuilder; + + public VMTemplateS3DaoImpl() { + + super(); + + this.searchBuilder = createSearchBuilder(); + this.searchBuilder + .and(S3_ID_COLUMN_NAME, this.searchBuilder.entity().getS3Id(), + EQ) + .and(TEMPLATE_ID_COLUMN_NAME, + this.searchBuilder.entity().getTemplateId(), EQ).done(); + + } + + @Override + public List listByS3Id(final long s3id) { + + final SearchCriteria criteria = this.searchBuilder + .create(); + + criteria.setParameters(S3_ID_COLUMN_NAME, s3id); + + return this.listBy(criteria); + + } + + @Override + public VMTemplateS3VO findOneByTemplateId(final long templateId) { + + final SearchCriteria criteria = this.searchBuilder + .create(); + + criteria.setParameters(TEMPLATE_ID_COLUMN_NAME, templateId); + + return this.findOneBy(criteria); + + } + + @Override + public VMTemplateS3VO findOneByS3Template(final long s3Id, + final long templateId) { + + final SearchCriteria criteria = this.searchBuilder + .create(); + + criteria.setParameters(S3_ID_COLUMN_NAME, s3Id); + criteria.setParameters(TEMPLATE_ID_COLUMN_NAME, templateId); + + return this.findOneBy(criteria); + + } + + @Override + public void expungeAllByTemplateId(long templateId) { + + final SearchCriteria criteria = this.searchBuilder + .create(); + + criteria.setParameters(TEMPLATE_ID_COLUMN_NAME, templateId); + + this.expunge(criteria); + + } + +} diff --git a/server/src/com/cloud/storage/s3/S3Manager.java b/server/src/com/cloud/storage/s3/S3Manager.java new file mode 100644 index 00000000000..357f2aed463 --- /dev/null +++ b/server/src/com/cloud/storage/s3/S3Manager.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.storage.s3; + +import java.util.List; + +import com.cloud.agent.api.to.S3TO; +import com.cloud.api.commands.AddS3Cmd; +import com.cloud.api.commands.ListS3sCmd; +import com.cloud.dc.DataCenterVO; +import com.cloud.exception.DiscoveryException; +import com.cloud.storage.S3; +import com.cloud.storage.S3VO; +import com.cloud.storage.VMTemplateS3VO; +import com.cloud.storage.VMTemplateVO; +import com.cloud.utils.component.Manager; + +public interface S3Manager extends Manager { + + S3TO getS3TO(); + + S3TO getS3TO(Long s3Id); + + S3 addS3(AddS3Cmd addS3Cmd) throws DiscoveryException; + + Long chooseZoneForTemplateExtract(VMTemplateVO template); + + boolean isS3Enabled(); + + boolean isTemplateInstalled(Long templateId); + + void deleteTemplate(final Long accountId, final Long templateId); + + String downloadTemplateFromS3ToSecondaryStorage(final long dcId, + final long templateId, final int primaryStorageDownloadWait); + + List listS3s(ListS3sCmd listS3sCmd); + + VMTemplateS3VO findByTemplateId(Long templateId); + + void propagateTemplatesToZone(DataCenterVO zone); + + void propagateTemplateToAllZones(VMTemplateS3VO vmTemplateS3VO); + + void uploadTemplateToS3FromSecondaryStorage(final VMTemplateVO template); + +} diff --git a/server/src/com/cloud/storage/s3/S3ManagerImpl.java b/server/src/com/cloud/storage/s3/S3ManagerImpl.java new file mode 100644 index 00000000000..6b072540c66 --- /dev/null +++ b/server/src/com/cloud/storage/s3/S3ManagerImpl.java @@ -0,0 +1,669 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.storage.s3; + +import static com.cloud.storage.S3VO.ID_COLUMN_NAME; +import static com.cloud.utils.DateUtil.now; +import static com.cloud.utils.S3Utils.canConnect; +import static com.cloud.utils.S3Utils.canReadWriteBucket; +import static com.cloud.utils.S3Utils.checkBucketName; +import static com.cloud.utils.S3Utils.checkClientOptions; +import static com.cloud.utils.S3Utils.doesBucketExist; +import static com.cloud.utils.StringUtils.join; +import static com.cloud.utils.db.GlobalLock.executeWithNoWaitLock; +import static com.cloud.utils.db.SearchCriteria.Op.EQ; +import static java.lang.Boolean.TRUE; +import static java.lang.String.format; +import static java.util.Arrays.asList; +import static java.util.Collections.emptyList; +import static java.util.Collections.shuffle; +import static java.util.Collections.singletonList; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Callable; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import com.cloud.agent.AgentManager; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.DeleteTemplateFromS3Command; +import com.cloud.agent.api.DownloadTemplateFromS3ToSecondaryStorageCommand; +import com.cloud.agent.api.UploadTemplateToS3FromSecondaryStorageCommand; +import com.cloud.agent.api.to.S3TO; +import com.cloud.api.commands.AddS3Cmd; +import com.cloud.api.commands.ListS3sCmd; +import com.cloud.configuration.Config; +import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.exception.DiscoveryException; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDao; +import com.cloud.storage.S3; +import com.cloud.storage.S3VO; +import com.cloud.storage.VMTemplateHostVO; +import com.cloud.storage.VMTemplateS3VO; +import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; +import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.VMTemplateZoneVO; +import com.cloud.storage.dao.S3Dao; +import com.cloud.storage.dao.VMTemplateDao; +import com.cloud.storage.dao.VMTemplateHostDao; +import com.cloud.storage.dao.VMTemplateS3Dao; +import com.cloud.storage.dao.VMTemplateZoneDao; +import com.cloud.storage.secondary.SecondaryStorageVmManager; +import com.cloud.utils.S3Utils.ClientOptions; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.exception.CloudRuntimeException; + +@Local(value = { S3Manager.class }) +public class S3ManagerImpl implements S3Manager { + + private static final Logger LOGGER = Logger.getLogger(S3ManagerImpl.class); + + private String name; + + @Inject + private AgentManager agentManager; + + @Inject + private S3Dao s3Dao; + + @Inject + private VMTemplateZoneDao vmTemplateZoneDao; + + @Inject + private VMTemplateS3Dao vmTemplateS3Dao; + + @Inject + private VMTemplateHostDao vmTemplateHostDao; + + @Inject + private VMTemplateDao vmTemplateDao; + + @Inject + private ConfigurationDao configurationDao; + + @Inject + private DataCenterDao dataCenterDao; + + @Inject + private HostDao hostDao; + + @Inject + private SecondaryStorageVmManager secondaryStorageVMManager; + + protected S3ManagerImpl() { + super(); + } + + private void verifyConnection(final S3TO s3) throws DiscoveryException { + + if (!canConnect(s3)) { + throw new DiscoveryException(format("Unable to connect to S3 " + + "using access key %1$s, secret key %2$s, and endpoint, " + + "%3$S", s3.getAccessKey(), s3.getSecretKey(), + s3.getEndPoint() != null ? s3.getEndPoint() : "default")); + } + + } + + private void verifyBuckets(S3TO s3) throws DiscoveryException { + + final List errorMessages = new ArrayList(); + + errorMessages.addAll(verifyBucket(s3, s3.getBucketName())); + + throwDiscoveryExceptionFromErrorMessages(errorMessages); + + } + + private List verifyBucket(final ClientOptions clientOptions, + final String bucketName) { + + if (!doesBucketExist(clientOptions, bucketName)) { + return singletonList(format("Bucket %1$s does not exist.", + bucketName)); + } + + if (!canReadWriteBucket(clientOptions, bucketName)) { + return singletonList(format("Can read/write from bucket %1$s.", + bucketName)); + } + + return emptyList(); + } + + private void validateFields(final S3VO s3VO) { + + final List errorMessages = new ArrayList(); + + errorMessages.addAll(checkClientOptions(s3VO.toS3TO())); + + errorMessages.addAll(checkBucketName("template", s3VO.getBucketName())); + + throwDiscoveryExceptionFromErrorMessages(errorMessages); + + } + + private void enforceS3PreConditions() throws DiscoveryException { + + if (!this.isS3Enabled()) { + throw new DiscoveryException("S3 is not enabled."); + } + + if (this.getS3TO() != null) { + throw new DiscoveryException("Attempt to define multiple S3 " + + "instances. Only one instance definition is supported."); + } + + } + + private void throwDiscoveryExceptionFromErrorMessages( + final List errorMessages) { + + if (!errorMessages.isEmpty()) { + throw new CloudRuntimeException(join(errorMessages, " ")); + } + + } + + @SuppressWarnings("unchecked") + private String determineLockId(final long accountId, final long templateId) { + + // TBD The lock scope may be too coarse grained. Deletes need to lock + // the template across all zones where upload and download could + // probably safely scoped to the zone ... + return join(asList("S3_TEMPLATE", accountId, templateId), "_"); + + } + + @Override + public S3TO getS3TO(final Long s3Id) { + return this.s3Dao.getS3TO(s3Id); + } + + @Override + public S3TO getS3TO() { + + final List s3s = this.s3Dao.listAll(); + + if (s3s == null || (s3s != null && s3s.isEmpty())) { + return null; + } + + if (s3s.size() == 1) { + return s3s.get(0).toS3TO(); + } + + throw new CloudRuntimeException("Multiple S3 instances have been " + + "defined. Only one instance configuration is supported."); + + } + + @Override + public S3 addS3(final AddS3Cmd addS3Cmd) throws DiscoveryException { + + this.enforceS3PreConditions(); + + final S3VO s3VO = new S3VO(UUID.randomUUID().toString(), + addS3Cmd.getAccessKey(), addS3Cmd.getSecretKey(), + addS3Cmd.getEndPoint(), addS3Cmd.getBucketName(), + addS3Cmd.getHttpsFlag(), addS3Cmd.getConnectionTimeout(), + addS3Cmd.getMaxErrorRetry(), addS3Cmd.getSocketTimeout(), now()); + + this.validateFields(s3VO); + + final S3TO s3 = s3VO.toS3TO(); + this.verifyConnection(s3); + this.verifyBuckets(s3); + + return this.s3Dao.persist(s3VO); + + } + + @Override + public boolean isS3Enabled() { + return Boolean + .valueOf(configurationDao.getValue(Config.S3Enable.key())); + } + + @Override + public boolean isTemplateInstalled(final Long templateId) { + throw new UnsupportedOperationException( + "S3Manager#isTemplateInstalled (DeleteIsoCmd) has not yet " + + "been implemented"); + } + + @Override + public void deleteTemplate(final Long templateId, final Long accountId) { + + final S3TO s3 = getS3TO(); + + if (s3 == null) { + final String errorMessage = "Delete Template Failed: No S3 configuration defined."; + LOGGER.error(errorMessage); + throw new CloudRuntimeException(errorMessage); + } + + final VMTemplateS3VO vmTemplateS3VO = vmTemplateS3Dao + .findOneByS3Template(s3.getId(), templateId); + if (vmTemplateS3VO == null) { + final String errorMessage = format( + "Delete Template Failed: Unable to find Template %1$s in S3.", + templateId); + LOGGER.error(errorMessage); + throw new CloudRuntimeException(errorMessage); + } + + try { + + executeWithNoWaitLock(determineLockId(accountId, templateId), + new Callable() { + + @Override + public Void call() throws Exception { + + final Answer answer = agentManager.sendToSSVM(null, + new DeleteTemplateFromS3Command(s3, + accountId, templateId)); + if (answer == null || !answer.getResult()) { + final String errorMessage = format( + "Delete Template Failed: Unable to delete template id %1$s from S3 due to following error: %2$s", + templateId, + ((answer == null) ? "answer is null" + : answer.getDetails())); + LOGGER.error(errorMessage); + throw new CloudRuntimeException(errorMessage); + } + + vmTemplateS3Dao.remove(vmTemplateS3VO.getId()); + LOGGER.debug(format( + "Deleted template %1$s from S3.", + templateId)); + + return null; + + } + + }); + + } catch (Exception e) { + + final String errorMessage = format( + "Delete Template Failed: Unable to delete template id %1$s from S3 due to the following error: %2$s.", + templateId, e.getMessage()); + LOGGER.error(errorMessage); + throw new CloudRuntimeException(errorMessage, e); + + } + + } + + @SuppressWarnings("unchecked") + @Override + public String downloadTemplateFromS3ToSecondaryStorage( + final long dataCenterId, final long templateId, + final int primaryStorageDownloadWait) { + + if (!isS3Enabled()) { + return null; + } + + final VMTemplateVO template = vmTemplateDao.findById(templateId); + if (template == null) { + final String errorMessage = String + .format("Failed to download template id %1$s from S3 because the template definition was not found.", + templateId); + LOGGER.error(errorMessage); + return errorMessage; + } + + final VMTemplateS3VO templateS3VO = findByTemplateId(templateId); + if (templateS3VO == null) { + final String errorMessage = format( + "Failed to download template id %1$s from S3 because it does not exist in S3.", + templateId); + LOGGER.error(errorMessage); + return errorMessage; + } + + final S3TO s3 = getS3TO(templateS3VO.getS3Id()); + if (s3 == null) { + final String errorMessage = format( + "Failed to download template id %1$s from S3 because S3 id %2$s does not exist.", + templateId, templateS3VO); + LOGGER.error(errorMessage); + return errorMessage; + } + + final HostVO secondaryStorageHost = secondaryStorageVMManager + .findSecondaryStorageHost(dataCenterId); + if (secondaryStorageHost == null) { + final String errorMessage = format( + "Unable to find secondary storage host for zone id %1$s.", + dataCenterId); + LOGGER.error(errorMessage); + throw new CloudRuntimeException(errorMessage); + } + + final long accountId = template.getAccountId(); + final DownloadTemplateFromS3ToSecondaryStorageCommand cmd = new DownloadTemplateFromS3ToSecondaryStorageCommand( + s3, accountId, templateId, secondaryStorageHost.getName(), + primaryStorageDownloadWait); + + try { + + executeWithNoWaitLock(determineLockId(accountId, templateId), + new Callable() { + + @Override + public Void call() throws Exception { + + final Answer answer = agentManager.sendToSSVM( + dataCenterId, cmd); + + if (answer == null || !answer.getResult()) { + final String errMsg = String + .format("Failed to download template from S3 to secondary storage due to %1$s", + (answer == null ? "answer is null" + : answer.getDetails())); + LOGGER.error(errMsg); + throw new CloudRuntimeException(errMsg); + } + + final String installPath = join( + asList("template", "tmpl", accountId, + templateId), File.separator); + final VMTemplateHostVO tmpltHost = new VMTemplateHostVO( + secondaryStorageHost.getId(), templateId, + now(), 100, Status.DOWNLOADED, null, null, + null, installPath, template.getUrl()); + tmpltHost.setSize(templateS3VO.getSize()); + tmpltHost.setPhysicalSize(templateS3VO + .getPhysicalSize()); + vmTemplateHostDao.persist(tmpltHost); + + return null; + + } + + }); + + } catch (Exception e) { + final String errMsg = "Failed to download template from S3 to secondary storage due to " + + e.toString(); + LOGGER.error(errMsg); + throw new CloudRuntimeException(errMsg); + } + + return null; + + } + + @Override + public List listS3s(final ListS3sCmd cmd) { + + final Filter filter = new Filter(S3VO.class, ID_COLUMN_NAME, TRUE, + cmd.getStartIndex(), cmd.getPageSizeVal()); + final SearchCriteria criteria = this.s3Dao.createSearchCriteria(); + + if (cmd.getId() != null) { + criteria.addAnd(ID_COLUMN_NAME, EQ, cmd.getId()); + } + + return this.s3Dao.search(criteria, filter); + + } + + @Override + public VMTemplateS3VO findByTemplateId(final Long templateId) { + throw new UnsupportedOperationException( + "S3Manager#findByTemplateId(Long) has not yet " + + "been implemented"); + } + + @Override + public void propagateTemplatesToZone(final DataCenterVO zone) { + + if (!isS3Enabled()) { + return; + } + + final List s3VMTemplateRefs = this.vmTemplateS3Dao + .listAll(); + if (LOGGER.isInfoEnabled()) { + LOGGER.info(format("Propagating %1$s templates to zone %2$s.", + s3VMTemplateRefs.size(), zone.getName())); + } + + for (final VMTemplateS3VO templateS3VO : s3VMTemplateRefs) { + this.vmTemplateZoneDao.persist(new VMTemplateZoneVO(zone.getId(), + templateS3VO.getTemplateId(), now())); + } + + } + + @Override + public boolean configure(final String name, final Map params) + throws ConfigurationException { + + if (LOGGER.isInfoEnabled()) { + LOGGER.info(format("Configuring S3 Manager %1$s", name)); + } + + this.name = name; + + return true; + + } + + @Override + public boolean start() { + LOGGER.info("Starting S3 Manager"); + return true; + } + + @Override + public boolean stop() { + LOGGER.info("Stopping S3 Manager"); + return true; + } + + @Override + public String getName() { + return this.name; + } + + @Override + public void propagateTemplateToAllZones(final VMTemplateS3VO vmTemplateS3VO) { + + final long templateId = vmTemplateS3VO.getId(); + + if (!isS3Enabled()) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace(format( + "Attempt to propogate template id %1$s across all zones. However, S3 is not enabled.", + templateId)); + } + return; + + } + + final S3TO s3 = getS3TO(); + + if (s3 == null) { + LOGGER.warn(format( + "Unable to propagate template id %1$s across all zones because S3 is enabled, but not configured.", + templateId)); + return; + } + + if (vmTemplateS3VO != null) { + final List dataCenters = dataCenterDao.listAll(); + for (DataCenterVO dataCenter : dataCenters) { + final VMTemplateZoneVO tmpltZoneVO = new VMTemplateZoneVO( + dataCenter.getId(), templateId, now()); + vmTemplateZoneDao.persist(tmpltZoneVO); + } + } + + } + + @Override + public Long chooseZoneForTemplateExtract(VMTemplateVO template) { + + final S3TO s3 = getS3TO(); + + if (s3 == null) { + return null; + } + + final List templateHosts = vmTemplateHostDao + .listByOnlyTemplateId(template.getId()); + if (templateHosts != null) { + shuffle(templateHosts); + for (VMTemplateHostVO vmTemplateHostVO : templateHosts) { + final HostVO host = hostDao.findById(vmTemplateHostVO + .getHostId()); + if (host != null) { + return host.getDataCenterId(); + } + throw new CloudRuntimeException( + format("Unable to find secondary storage host for template id %1$s.", + template.getId())); + } + } + + final List dataCenters = dataCenterDao.listAll(); + shuffle(dataCenters); + return dataCenters.get(0).getId(); + + } + + @Override + public void uploadTemplateToS3FromSecondaryStorage( + final VMTemplateVO template) { + + final Long templateId = template.getId(); + + final List templateHostRefs = vmTemplateHostDao + .listByTemplateId(templateId); + + if (templateHostRefs == null + || (templateHostRefs != null && templateHostRefs.isEmpty())) { + throw new CloudRuntimeException( + format("Attempt to sync template id %1$s that is not attached to a host.", + templateId)); + } + + final VMTemplateHostVO templateHostRef = templateHostRefs.get(0); + + if (!isS3Enabled()) { + return; + } + + final S3TO s3 = getS3TO(); + if (s3 == null) { + LOGGER.warn("S3 Template Sync Failed: Attempt to sync templates with S3, but no S3 instance defined."); + return; + } + + final HostVO secondaryHost = this.hostDao.findById(templateHostRef + .getHostId()); + if (secondaryHost == null) { + throw new CloudRuntimeException(format( + "Unable to find secondary storage host id %1$s.", + templateHostRef.getHostId())); + } + + final Long dataCenterId = secondaryHost.getDataCenterId(); + final Long accountId = template.getAccountId(); + + try { + + executeWithNoWaitLock(determineLockId(accountId, templateId), + new Callable() { + + @Override + public Void call() throws Exception { + + final UploadTemplateToS3FromSecondaryStorageCommand cmd = new UploadTemplateToS3FromSecondaryStorageCommand( + s3, secondaryHost.getStorageUrl(), + dataCenterId, accountId, templateId); + + final Answer answer = agentManager.sendToSSVM( + dataCenterId, cmd); + if (answer == null || !answer.getResult()) { + + final String reason = answer != null ? answer + .getDetails() + : "S3 template sync failed due to an unspecified error."; + throw new CloudRuntimeException( + format("Failed to upload template id %1$s to S3 from secondary storage due to %2$s.", + templateId, reason)); + + } + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(format( + "Creating VMTemplateS3VO instance using template id %1s.", + templateId)); + } + + final VMTemplateS3VO vmTemplateS3VO = new VMTemplateS3VO( + s3.getId(), templateId, now(), + templateHostRef.getSize(), templateHostRef + .getPhysicalSize()); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(format("Persisting %1$s", + vmTemplateS3VO)); + } + + vmTemplateS3Dao.persist(vmTemplateS3VO); + propagateTemplateToAllZones(vmTemplateS3VO); + + return null; + + } + + }); + + } catch (Exception e) { + + final String errorMessage = format( + "Failed to upload template id %1$s for zone id %2$s to S3.", + templateId, dataCenterId); + LOGGER.error(errorMessage, e); + + } + + } + +} diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManager.java b/server/src/com/cloud/storage/snapshot/SnapshotManager.java index a10298efb90..a7692de7107 100755 --- a/server/src/com/cloud/storage/snapshot/SnapshotManager.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotManager.java @@ -128,6 +128,8 @@ public interface SnapshotManager { void downloadSnapshotsFromSwift(SnapshotVO ss); + void downloadSnapshotsFromS3(SnapshotVO snapshot); + HostVO getSecondaryStorageHost(SnapshotVO snapshot); String getSecondaryStorageURL(SnapshotVO snapshot); diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java index 242125f7f5b..6a0f71d1f6f 100755 --- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java @@ -17,6 +17,7 @@ package com.cloud.storage.snapshot; import java.util.ArrayList; +import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; @@ -36,9 +37,11 @@ import com.cloud.agent.api.BackupSnapshotCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.DeleteSnapshotBackupCommand; import com.cloud.agent.api.DeleteSnapshotsDirCommand; +import com.cloud.agent.api.DownloadSnapshotFromS3Command; import com.cloud.agent.api.ManageSnapshotAnswer; import com.cloud.agent.api.ManageSnapshotCommand; import com.cloud.agent.api.downloadSnapshotFromSwiftCommand; +import com.cloud.agent.api.to.S3TO; import com.cloud.agent.api.to.SwiftTO; import com.cloud.alert.AlertManager; import org.apache.cloudstack.api.command.user.snapshot.DeleteSnapshotPoliciesCmd; @@ -91,6 +94,7 @@ import com.cloud.storage.dao.SnapshotScheduleDao; import com.cloud.storage.dao.StoragePoolDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VolumeDao; +import com.cloud.storage.s3.S3Manager; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.swift.SwiftManager; import com.cloud.tags.ResourceTagVO; @@ -171,6 +175,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma private ResourceLimitService _resourceLimitMgr; @Inject private SwiftManager _swiftMgr; + @Inject + private S3Manager _s3Mgr; @Inject private SecondaryStorageVmManager _ssvmMgr; @Inject @@ -477,11 +483,25 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma return createdSnapshot; } + private static void checkObjectStorageConfiguration(SwiftTO swift, S3TO s3) { + + if (swift != null && s3 != null) { + throw new CloudRuntimeException( + "Swift and S3 are not simultaneously supported for snapshot backup."); + } + + } @Override public void deleteSnapshotsForVolume (String secondaryStoragePoolUrl, Long dcId, Long accountId, Long volumeId ){ SwiftTO swift = _swiftMgr.getSwiftTO(); - DeleteSnapshotBackupCommand cmd = new DeleteSnapshotBackupCommand(swift, secondaryStoragePoolUrl, dcId, accountId, volumeId, null, true); + S3TO s3 = _s3Mgr.getS3TO(); + + checkObjectStorageConfiguration(swift, s3); + + DeleteSnapshotBackupCommand cmd = new DeleteSnapshotBackupCommand( + swift, s3, secondaryStoragePoolUrl, dcId, accountId, volumeId, + null, true); try { Answer ans = _agentMgr.sendToSSVM(dcId, cmd); if ( ans == null || !ans.getResult() ) { @@ -543,6 +563,54 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } + private List determineBackupUuids(final SnapshotVO snapshot) { + + final List backupUuids = new ArrayList(); + backupUuids.add(0, snapshot.getBackupSnapshotId()); + + SnapshotVO tempSnapshot = snapshot; + while (tempSnapshot.getPrevSnapshotId() != 0) { + tempSnapshot = _snapshotDao.findById(tempSnapshot + .getPrevSnapshotId()); + backupUuids.add(0, tempSnapshot.getBackupSnapshotId()); + } + + return Collections.unmodifiableList(backupUuids); + } + + @Override + public void downloadSnapshotsFromS3(final SnapshotVO snapshot) { + + final VolumeVO volume = _volsDao.findById(snapshot.getVolumeId()); + final Long zoneId = volume.getDataCenterId(); + final HostVO secHost = _storageMgr.getSecondaryStorageHost(zoneId); + + final S3TO s3 = _s3Mgr.getS3TO(snapshot.getS3Id()); + final List backupUuids = determineBackupUuids(snapshot); + + try { + String parent = null; + for (final String backupUuid : backupUuids) { + final DownloadSnapshotFromS3Command cmd = new DownloadSnapshotFromS3Command( + s3, parent, secHost.getStorageUrl(), zoneId, + volume.getAccountId(), volume.getId(), backupUuid, + _backupsnapshotwait); + final Answer answer = _agentMgr.sendToSSVM(zoneId, cmd); + if ((answer == null) || !answer.getResult()) { + throw new CloudRuntimeException(String.format( + "S3 snapshot download failed due to %1$s.", + answer != null ? answer.getDetails() + : "unspecified error")); + } + parent = backupUuid; + } + } catch (Exception e) { + throw new CloudRuntimeException( + "Snapshot download from S3 failed due to " + e.toString(), + e); + } + + } @Override @DB @@ -560,7 +628,6 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma long volumeId = snapshot.getVolumeId(); VolumeVO volume = _volsDao.lockRow(volumeId, true); - String primaryStoragePoolNameLabel = _storageMgr.getPrimaryStorageNameLabel(volume); Long dcId = volume.getDataCenterId(); Long accountId = volume.getAccountId(); @@ -577,6 +644,9 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma SwiftTO swift = _swiftMgr.getSwiftTO(); + S3TO s3 = _s3Mgr.getS3TO(); + + checkObjectStorageConfiguration(swift, s3); long prevSnapshotId = snapshot.getPrevSnapshotId(); if (prevSnapshotId > 0) { @@ -586,7 +656,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma prevBackupUuid = prevSnapshot.getBackupSnapshotId(); prevSnapshotUuid = prevSnapshot.getPath(); } - } else if ( prevSnapshot.getSwiftId() != null && swift != null ) { + } else if ((prevSnapshot.getSwiftId() != null && swift != null) + || (prevSnapshot.getS3Id() != null && s3 != null)) { prevBackupUuid = prevSnapshot.getBackupSnapshotId(); prevSnapshotUuid = prevSnapshot.getPath(); } @@ -594,13 +665,15 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma boolean isVolumeInactive = _storageMgr.volumeInactive(volume); String vmName = _storageMgr.getVmNameOnVolume(volume); StoragePoolVO srcPool = _storagePoolDao.findById(volume.getPoolId()); - BackupSnapshotCommand backupSnapshotCommand = new BackupSnapshotCommand(primaryStoragePoolNameLabel, secondaryStoragePoolUrl, dcId, accountId, volumeId, snapshot.getId(), volume.getPath(), srcPool, snapshotUuid, + BackupSnapshotCommand backupSnapshotCommand = new BackupSnapshotCommand(secondaryStoragePoolUrl, dcId, accountId, volumeId, snapshot.getId(), volume.getPath(), srcPool, snapshotUuid, snapshot.getName(), prevSnapshotUuid, prevBackupUuid, isVolumeInactive, vmName, _backupsnapshotwait); if ( swift != null ) { backupSnapshotCommand.setSwift(swift); + } else if (s3 != null) { + backupSnapshotCommand.setS3(s3); } - + String backedUpSnapshotUuid = null; // By default, assume failed. boolean backedUp = false; @@ -621,6 +694,9 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma if (backupSnapshotCommand.getSwift() != null ) { snapshot.setSwiftId(swift.getId()); snapshot.setBackupSnapshotId(backedUpSnapshotUuid); + } else if (backupSnapshotCommand.getS3() != null) { + snapshot.setS3Id(s3.getId()); + snapshot.setBackupSnapshotId(backedUpSnapshotUuid); } else { snapshot.setSecHostId(secHost.getId()); snapshot.setBackupSnapshotId(backedUpSnapshotUuid); @@ -832,7 +908,13 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma return true; } SwiftTO swift = _swiftMgr.getSwiftTO(snapshot.getSwiftId()); - DeleteSnapshotBackupCommand cmd = new DeleteSnapshotBackupCommand(swift, secondaryStoragePoolUrl, dcId, accountId, volumeId, backupOfSnapshot, false); + S3TO s3 = _s3Mgr.getS3TO(); + + checkObjectStorageConfiguration(swift, s3); + + DeleteSnapshotBackupCommand cmd = new DeleteSnapshotBackupCommand( + swift, s3, secondaryStoragePoolUrl, dcId, accountId, volumeId, + backupOfSnapshot, false); Answer answer = _agentMgr.sendToSSVM(dcId, cmd); if ((answer != null) && answer.getResult()) { @@ -979,9 +1061,15 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } List ssHosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(dcId); SwiftTO swift = _swiftMgr.getSwiftTO(); - if (swift == null) { + S3TO s3 = _s3Mgr.getS3TO(); + + checkObjectStorageConfiguration(swift, s3); + + if (swift == null && s3 == null) { for (HostVO ssHost : ssHosts) { - DeleteSnapshotBackupCommand cmd = new DeleteSnapshotBackupCommand(null, ssHost.getStorageUrl(), dcId, accountId, volumeId, "", true); + DeleteSnapshotBackupCommand cmd = new DeleteSnapshotBackupCommand( + null, null, ssHost.getStorageUrl(), dcId, + accountId, volumeId, "", true); Answer answer = null; try { answer = _agentMgr.sendToSSVM(dcId, cmd); @@ -998,12 +1086,14 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } } } else { - DeleteSnapshotBackupCommand cmd = new DeleteSnapshotBackupCommand(swift, "", dcId, accountId, volumeId, "", true); + DeleteSnapshotBackupCommand cmd = new DeleteSnapshotBackupCommand( + swift, s3, "", dcId, accountId, volumeId, "", true); Answer answer = null; try { answer = _agentMgr.sendToSSVM(dcId, cmd); } catch (Exception e) { - s_logger.warn("Failed to delete all snapshot for volume " + volumeId + " on swift"); + final String storeType = s3 != null ? "S3" : "swift"; + s_logger.warn("Failed to delete all snapshot for volume " + volumeId + " on " + storeType); } if ((answer != null) && answer.getResult()) { s_logger.debug("Deleted all snapshots for volume: " + volumeId + " under account: " + accountId); diff --git a/server/src/com/cloud/template/S3SyncTask.java b/server/src/com/cloud/template/S3SyncTask.java new file mode 100644 index 00000000000..ed179dc8961 --- /dev/null +++ b/server/src/com/cloud/template/S3SyncTask.java @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.cloud.template; + +import static java.lang.String.*; + +import java.util.List; + +import org.apache.log4j.Logger; + +import com.cloud.agent.api.to.S3TO; +import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.dao.VMTemplateDao; +import com.cloud.storage.s3.S3Manager; + +final class S3SyncTask implements Runnable { + + private static final Logger LOGGER = Logger.getLogger(S3SyncTask.class); + + private final VMTemplateDao vmTemplateDao; + private final S3Manager s3Mgr; + + S3SyncTask(final VMTemplateDao vmTemplateDao, final S3Manager s3Mgr) { + + super(); + + assert vmTemplateDao != null; + assert s3Mgr != null; + + this.vmTemplateDao = vmTemplateDao; + this.s3Mgr = s3Mgr; + + } + + @Override + public void run() { + + try { + + final S3TO s3 = s3Mgr.getS3TO(); + + if (s3 == null) { + LOGGER.warn("S3 sync skipped because no S3 instance is configured."); + return; + } + + final List candidateTemplates = vmTemplateDao + .findTemplatesToSyncToS3(); + + if (candidateTemplates.isEmpty()) { + LOGGER.debug("All templates are synced with S3."); + return; + } + + for (VMTemplateVO candidateTemplate : candidateTemplates) { + + if (LOGGER.isInfoEnabled()) { + LOGGER.info(format( + "Uploading template %1$s (id: %2$s) to S3.", + candidateTemplate.getName(), + candidateTemplate.getId())); + } + + s3Mgr.uploadTemplateToS3FromSecondaryStorage(candidateTemplate); + + } + + LOGGER.debug("Completed S3 template sync task."); + + } catch (Exception e) { + LOGGER.warn( + "S3 Sync Task ignored exception, and will continue to execute.", + e); + } + + } + +} diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java index 74da1e23f8c..8bc122c0c44 100755 --- a/server/src/com/cloud/template/TemplateManagerImpl.java +++ b/server/src/com/cloud/template/TemplateManagerImpl.java @@ -106,10 +106,12 @@ import com.cloud.storage.dao.UploadDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplateHostDao; import com.cloud.storage.dao.VMTemplatePoolDao; +import com.cloud.storage.dao.VMTemplateS3Dao; import com.cloud.storage.dao.VMTemplateSwiftDao; import com.cloud.storage.dao.VMTemplateZoneDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.download.DownloadMonitor; +import com.cloud.storage.s3.S3Manager; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.swift.SwiftManager; import com.cloud.storage.upload.UploadMonitor; @@ -172,8 +174,12 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe @Inject SwiftManager _swiftMgr; @Inject + S3Manager _s3Mgr; + @Inject VMTemplateSwiftDao _tmpltSwiftDao; @Inject + VMTemplateS3Dao _vmS3TemplateDao; + @Inject ConfigurationDao _configDao; @Inject ClusterDao _clusterDao; @@ -200,6 +206,7 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe ExecutorService _preloadExecutor; ScheduledExecutorService _swiftTemplateSyncExecutor; + private ScheduledExecutorService _s3TemplateSyncExecutor = null; @Inject (adapter=TemplateAdapter.class) protected Adapters _adapters; @@ -337,10 +344,14 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe } } - if (zoneId == null) { + if (zoneId == null && _swiftMgr.isSwiftEnabled()) { zoneId = _swiftMgr.chooseZoneForTmpltExtract(templateId); } + if (zoneId == null && _s3Mgr.isS3Enabled()) { + zoneId = _s3Mgr.chooseZoneForTemplateExtract(template); + } + if (_dcDao.findById(zoneId) == null) { throw new IllegalArgumentException("Please specify a valid zone."); } @@ -373,7 +384,13 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe if (swift != null && sservers != null) { downloadTemplateFromSwiftToSecondaryStorage(zoneId, templateId); } + } else if (tmpltHostRef == null && _s3Mgr.isS3Enabled()) { + if (sservers != null) { + _s3Mgr.downloadTemplateFromS3ToSecondaryStorage(zoneId, + templateId, _primaryStorageDownloadWait); + } } + if (tmpltHostRef == null) { throw new InvalidParameterValueException("The " + desc + " has not been downloaded "); } @@ -587,6 +604,12 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe s_logger.error("Unable to find a secondary storage host who has completely downloaded the template."); return null; } + result = _s3Mgr.downloadTemplateFromS3ToSecondaryStorage(dcId, + templateId, _primaryStorageDownloadWait); + if (result != null) { + s_logger.error("Unable to find a secondary storage host who has completely downloaded the template."); + return null; + } templateHostRef = _storageMgr.findVmTemplateHost(templateId, pool); if (templateHostRef == null || templateHostRef.getDownloadState() != Status.DOWNLOADED) { s_logger.error("Unable to find a secondary storage host who has completely downloaded the template."); @@ -637,7 +660,7 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe } String url = origUrl + "/" + templateHostRef.getInstallPath(); PrimaryStorageDownloadCommand dcmd = new PrimaryStorageDownloadCommand(template.getUniqueName(), url, template.getFormat(), - template.getAccountId(), pool.getId(), pool.getUuid(), _primaryStorageDownloadWait); + template.getAccountId(), pool, _primaryStorageDownloadWait); HostVO secondaryStorageHost = _hostDao.findById(templateHostRef.getHostId()); assert(secondaryStorageHost != null); dcmd.setSecondaryStorageUrl(secondaryStorageHost.getStorageUrl()); @@ -701,6 +724,12 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe s_logger.error("Unable to find a secondary storage host who has completely downloaded the template."); return null; } + result = _s3Mgr.downloadTemplateFromS3ToSecondaryStorage(dcId, + templateId, _primaryStorageDownloadWait); + if (result != null) { + s_logger.error("Unable to find a secondary storage host who has completely downloaded the template."); + return null; + } templateHostRef = _storageMgr.findVmTemplateHost(templateId, pool); if (templateHostRef == null || templateHostRef.getDownloadState() != Status.DOWNLOADED) { s_logger.error("Unable to find a secondary storage host who has completely downloaded the template."); @@ -816,6 +845,12 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe if (_swiftMgr.isSwiftEnabled()) { throw new CloudRuntimeException("copytemplate API is disabled in Swift setup, templates in Swift can be accessed by all Zones"); } + + if (_s3Mgr.isS3Enabled()) { + throw new CloudRuntimeException( + "copytemplate API is disabled in S3 setup -- S3 templates are accessible in all zones."); + } + //Verify parameters if (sourceZoneId == destZoneId) { throw new InvalidParameterValueException("Please specify different source and destination zones."); @@ -996,12 +1031,32 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe @Override public boolean start() { _swiftTemplateSyncExecutor.scheduleAtFixedRate(getSwiftTemplateSyncTask(), 60, 60, TimeUnit.SECONDS); + + if (_s3TemplateSyncExecutor != null) { + + final int initialDelay = 60; + final int period = 60; + + _s3TemplateSyncExecutor.scheduleAtFixedRate(new S3SyncTask( + this._tmpltDao, this._s3Mgr), initialDelay, period, + TimeUnit.SECONDS); + s_logger.info(String.format("Started S3 sync task to execute " + + "execute every %1$s after an initial delay of %2$s.", + period, initialDelay)); + + } + return true; } @Override public boolean stop() { _swiftTemplateSyncExecutor.shutdownNow(); + + if (_s3TemplateSyncExecutor != null) { + _s3TemplateSyncExecutor.shutdownNow(); + } + return true; } @@ -1034,7 +1089,16 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe _storagePoolMaxWaitSeconds = NumbersUtil.parseInt(_configDao.getValue(Config.StoragePoolMaxWaitSeconds.key()), 3600); _preloadExecutor = Executors.newFixedThreadPool(8, new NamedThreadFactory("Template-Preloader")); _swiftTemplateSyncExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("swift-template-sync-Executor")); - return false; + + if (_s3Mgr.isS3Enabled()) { + _s3TemplateSyncExecutor = Executors + .newSingleThreadScheduledExecutor(new NamedThreadFactory( + "s3-template-sync")); + } else { + s_logger.info("S3 secondary storage synchronization is disabled."); + } + + return false; } protected TemplateManagerImpl() { @@ -1188,13 +1252,19 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe if (cmd.getZoneId() == null && _swiftMgr.isSwiftEnabled()) { _swiftMgr.deleteTemplate(cmd); } + if (cmd.getZoneId() == null && _s3Mgr.isS3Enabled()) { + _s3Mgr.deleteTemplate(cmd.getId(), caller.getAccountId()); + } + TemplateAdapter adapter = getAdapter(template.getHypervisorType()); TemplateProfile profile = adapter.prepareDelete(cmd); boolean result = adapter.delete(profile); if (result){ - if (cmd.getZoneId() == null && _swiftMgr.isSwiftEnabled()) { - List templateZones = _tmpltZoneDao.listByZoneTemplate(null, templateId); + if (cmd.getZoneId() == null + && (_swiftMgr.isSwiftEnabled() || _s3Mgr.isS3Enabled())) { + List templateZones = _tmpltZoneDao + .listByZoneTemplate(null, templateId); if (templateZones != null) { for (VMTemplateZoneVO templateZone : templateZones) { _tmpltZoneDao.remove(templateZone.getId()); @@ -1227,6 +1297,10 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe if (cmd.getZoneId() == null && _swiftMgr.isSwiftEnabled()) { _swiftMgr.deleteIso(cmd); } + if (cmd.getZoneId() == null && _s3Mgr.isS3Enabled()) { + _s3Mgr.deleteTemplate(caller.getAccountId(), templateId); + } + if (zoneId != null && (_ssvmMgr.findSecondaryStorageHost(zoneId) == null)) { throw new InvalidParameterValueException("Failed to find a secondary storage host in the specified zone."); } @@ -1234,8 +1308,10 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe TemplateProfile profile = adapter.prepareDelete(cmd); boolean result = adapter.delete(profile); if (result) { - if (cmd.getZoneId() == null && _swiftMgr.isSwiftEnabled()) { - List templateZones = _tmpltZoneDao.listByZoneTemplate(null, templateId); + if (cmd.getZoneId() == null + && (_swiftMgr.isSwiftEnabled() || _s3Mgr.isS3Enabled())) { + List templateZones = _tmpltZoneDao + .listByZoneTemplate(null, templateId); if (templateZones != null) { for (VMTemplateZoneVO templateZone : templateZones) { _tmpltZoneDao.remove(templateZone.getId()); diff --git a/server/src/com/cloud/upgrade/dao/Upgrade40to41.java b/server/src/com/cloud/upgrade/dao/Upgrade40to41.java index 3ba0ed8a737..e23837d49f8 100644 --- a/server/src/com/cloud/upgrade/dao/Upgrade40to41.java +++ b/server/src/com/cloud/upgrade/dao/Upgrade40to41.java @@ -17,8 +17,14 @@ package com.cloud.upgrade.dao; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.script.Script; + import java.io.File; import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; @@ -78,6 +84,7 @@ public class Upgrade40to41 implements DbUpgrade { */ @Override public void performDataMigration(Connection conn) { + upgradeEIPNetworkOfferings(conn); } /* (non-Javadoc) @@ -88,4 +95,36 @@ public class Upgrade40to41 implements DbUpgrade { return new File[0]; } + private void upgradeEIPNetworkOfferings(Connection conn) { + PreparedStatement pstmt = null; + ResultSet rs = null; + + try { + pstmt = conn.prepareStatement("select id, elastic_ip_service from `cloud`.`network_offerings` where traffic_type='Guest'"); + rs = pstmt.executeQuery(); + while (rs.next()) { + long id = rs.getLong(1); + // check if elastic IP service is enabled for network offering + if (rs.getLong(2) != 0) { + //update network offering with eip_associate_public_ip set to true + pstmt = conn.prepareStatement("UPDATE `cloud`.`network_offerings` set eip_associate_public_ip=? where id=?"); + pstmt.setBoolean(1, true); + pstmt.setLong(2, id); + pstmt.executeUpdate(); + } + } + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to set elastic_ip_service for network offerings with EIP service enabled.", e); + } finally { + try { + if (rs != null) { + rs.close(); + } + if (pstmt != null) { + pstmt.close(); + } + } catch (SQLException e) { + } + } + } } diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 6608987ee5a..12645fad9b1 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -41,21 +41,9 @@ import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import com.cloud.acl.ControlledEntity.ACLType; +import com.cloud.acl.SecurityChecker.AccessType; import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.AttachIsoCommand; -import com.cloud.agent.api.AttachVolumeAnswer; -import com.cloud.agent.api.AttachVolumeCommand; -import com.cloud.agent.api.ComputeChecksumCommand; -import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand; -import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand; -import com.cloud.agent.api.GetVmStatsAnswer; -import com.cloud.agent.api.GetVmStatsCommand; -import com.cloud.agent.api.SnapshotCommand; -import com.cloud.agent.api.StartAnswer; -import com.cloud.agent.api.StopAnswer; -import com.cloud.agent.api.UpgradeSnapshotCommand; -import com.cloud.agent.api.VmStatsEntry; +import com.cloud.agent.api.*; import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.VirtualMachineTO; @@ -101,37 +89,18 @@ import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; import com.cloud.event.UsageEventVO; import com.cloud.event.dao.UsageEventDao; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ManagementServerException; -import com.cloud.exception.OperationTimedoutException; -import com.cloud.exception.PermissionDeniedException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.exception.StorageUnavailableException; -import com.cloud.exception.VirtualMachineMigrationException; +import com.cloud.exception.*; import com.cloud.ha.HighAvailabilityManager; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao; -import com.cloud.network.IPAddressVO; -import com.cloud.network.LoadBalancerVMMapVO; -import com.cloud.network.Network; +import com.cloud.network.*; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; -import com.cloud.network.NetworkManager; -import com.cloud.network.NetworkVO; import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.dao.FirewallRulesDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.LoadBalancerVMMapDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.dao.PhysicalNetworkDao; +import com.cloud.network.dao.*; import com.cloud.network.element.UserDataServiceProvider; import com.cloud.network.lb.LoadBalancingRulesManager; import com.cloud.network.rules.FirewallManager; @@ -159,49 +128,18 @@ import com.cloud.resource.ResourceState; import com.cloud.server.Criteria; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; -import com.cloud.storage.DiskOfferingVO; -import com.cloud.storage.GuestOSVO; -import com.cloud.storage.Snapshot; -import com.cloud.storage.SnapshotVO; -import com.cloud.storage.Storage; +import com.cloud.storage.*; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Storage.TemplateType; -import com.cloud.storage.StorageManager; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolStatus; -import com.cloud.storage.StoragePoolVO; -import com.cloud.storage.VMTemplateHostVO; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; -import com.cloud.storage.VMTemplateVO; -import com.cloud.storage.VMTemplateZoneVO; -import com.cloud.storage.Volume; import com.cloud.storage.Volume.Type; -import com.cloud.storage.VolumeHostVO; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.DiskOfferingDao; -import com.cloud.storage.dao.GuestOSDao; -import com.cloud.storage.dao.SnapshotDao; -import com.cloud.storage.dao.StoragePoolDao; -import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.storage.dao.VMTemplateDetailsDao; -import com.cloud.storage.dao.VMTemplateHostDao; -import com.cloud.storage.dao.VMTemplateZoneDao; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.storage.dao.VolumeHostDao; +import com.cloud.storage.dao.*; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.template.VirtualMachineTemplate; import com.cloud.template.VirtualMachineTemplate.BootloaderType; -import com.cloud.user.Account; -import com.cloud.user.AccountManager; -import com.cloud.user.AccountService; -import com.cloud.user.AccountVO; -import com.cloud.user.ResourceLimitService; -import com.cloud.user.SSHKeyPair; -import com.cloud.user.User; -import com.cloud.user.UserContext; -import com.cloud.user.UserVO; +import com.cloud.user.*; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.SSHKeyPairDao; import com.cloud.user.dao.UserDao; @@ -227,12 +165,16 @@ import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.fsm.NoTransitionException; import com.cloud.utils.net.NetUtils; import com.cloud.vm.VirtualMachine.State; -import com.cloud.vm.dao.InstanceGroupDao; -import com.cloud.vm.dao.InstanceGroupVMMapDao; -import com.cloud.vm.dao.NicDao; -import com.cloud.vm.dao.UserVmDao; -import com.cloud.vm.dao.UserVmDetailsDao; -import com.cloud.vm.dao.VMInstanceDao; +import com.cloud.vm.dao.*; +import org.apache.commons.codec.binary.Base64; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.util.*; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; @Local(value = { UserVmManager.class, UserVmService.class }) public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager { @@ -1547,7 +1489,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if( snapshot.getSwiftId() != null && snapshot.getSwiftId() != 0 ) { _snapshotMgr.downloadSnapshotsFromSwift(snapshot); } - cmd = new CreatePrivateTemplateFromSnapshotCommand(pool.getUuid(), secondaryStorageURL, dcId, accountId, snapshot.getVolumeId(), backupSnapshotUUID, snapshot.getName(), + cmd = new CreatePrivateTemplateFromSnapshotCommand(pool, secondaryStorageURL, dcId, accountId, snapshot.getVolumeId(), backupSnapshotUUID, snapshot.getName(), origTemplateInstallPath, templateId, name, _createprivatetemplatefromsnapshotwait); } else if (volumeId != null) { VolumeVO volume = _volsDao.findById(volumeId); @@ -1569,7 +1511,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager secondaryStorageURL = secondaryStorageHost.getStorageUrl(); pool = _storagePoolDao.findById(volume.getPoolId()); - cmd = new CreatePrivateTemplateFromVolumeCommand(pool.getUuid(), secondaryStorageURL, templateId, accountId, command.getTemplateName(), uniqueName, volume.getPath(), vmName, _createprivatetemplatefromvolumewait); + cmd = new CreatePrivateTemplateFromVolumeCommand(pool, secondaryStorageURL, templateId, accountId, command.getTemplateName(), uniqueName, volume.getPath(), vmName, _createprivatetemplatefromvolumewait); } else { throw new CloudRuntimeException("Creating private Template need to specify snapshotId or volumeId"); @@ -2176,8 +2118,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager isSecurityGroupEnabledNetworkUsed = true; } else { - // Verify that all the networks are Direct/Guest/AccountSpecific; can't create combination of SG enabled network and - // regular networks + // Verify that all the networks are Shared/Guest; can't create combination of SG enabled and disabled networks for (Long networkId : networkIdList) { NetworkVO network = _networkDao.findById(networkId); @@ -2193,21 +2134,17 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } isSecurityGroupEnabledNetworkUsed = true; - } + } - if (network.getTrafficType() != TrafficType.Guest || network.getGuestType() != Network.GuestType.Shared || (network.getGuestType() == Network.GuestType.Shared && !isSecurityGroupEnabled)) { - throw new InvalidParameterValueException("Can specify only Direct Guest Account specific networks when deploy vm in Security Group enabled zone"); + if (!(network.getTrafficType() == TrafficType.Guest && network.getGuestType() == Network.GuestType.Shared)) { + throw new InvalidParameterValueException("Can specify only Shared Guest networks when" + + " deploy vm in Advance Security Group enabled zone"); } // Perform account permission check - if (network.getGuestType() != Network.GuestType.Shared) { - // Check account permissions - List networkMap = _networkDao.listBy(owner.getId(), network.getId()); - if (networkMap == null || networkMap.isEmpty()) { - throw new PermissionDeniedException("Unable to create a vm using network with id " + network.getId() + ", permission denied"); - } + if (network.getAclType() == ACLType.Account) { + _accountMgr.checkAccess(caller, AccessType.UseNetwork, false, network); } - networkList.add(network); } } @@ -2268,7 +2205,6 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { // get Virtual networks List virtualNetworks = _networkMgr.listNetworksForAccount(owner.getId(), zone.getId(), Network.GuestType.Isolated); - if (virtualNetworks.isEmpty()) { long physicalNetworkId = _networkMgr.findPhysicalNetworkId(zone.getId(), requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType()); // Validate physical network @@ -2284,7 +2220,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } else if (virtualNetworks.size() > 1) { throw new InvalidParameterValueException("More than 1 default Isolated networks are found for account " + owner + "; please specify networkIds"); } else { - defaultNetwork = virtualNetworks.get(0); + defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId()); } } else { throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); @@ -2864,6 +2800,10 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (ip != null && ip.getSystem()) { UserContext ctx = UserContext.current(); try { + long networkId = ip.getAssociatedWithNetworkId(); + Network guestNetwork = _networkMgr.getNetwork(networkId); + NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); + assert (offering.getAssociatePublicIP() == true) : "User VM should not have system owned public IP associated with it when offering configured not to associate public IP."; _rulesMgr.disableStaticNat(ip.getId(), ctx.getCaller(), ctx.getCallerUserId(), true); } catch (Exception ex) { s_logger.warn("Failed to disable static nat and release system ip " + ip + " as a part of vm " + profile.getVirtualMachine() + " stop due to exception ", ex); @@ -3183,10 +3123,6 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (zone != null) { sc.setParameters("dataCenterId", zone); - - if (state == null) { - sc.setParameters("stateNEQ", "Destroyed"); - } } if (pod != null) { sc.setParameters("podId", pod); @@ -3632,7 +3568,6 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { // get Virtual networks List virtualNetworks = _networkMgr.listNetworksForAccount(newAccount.getId(), zone.getId(), Network.GuestType.Isolated); - if (virtualNetworks.isEmpty()) { long physicalNetworkId = _networkMgr.findPhysicalNetworkId(zone.getId(), requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType()); // Validate physical network @@ -3640,7 +3575,6 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (physicalNetwork == null) { throw new InvalidParameterValueException("Unable to find physical network with id: "+physicalNetworkId + " and tag: " +requiredOfferings.get(0).getTags()); } - s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + requiredOfferings.get(0).getId() + " as a part of deployVM process"); Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), @@ -3651,7 +3585,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new InvalidParameterValueException("More than 1 default Isolated networks are found " + "for account " + newAccount + "; please specify networkIds"); } else { - defaultNetwork = virtualNetworks.get(0); + defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId()); } } else { throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); diff --git a/server/src/com/cloud/vm/dao/NicDao.java b/server/src/com/cloud/vm/dao/NicDao.java index 762048b65bf..af3c7b379c1 100644 --- a/server/src/com/cloud/vm/dao/NicDao.java +++ b/server/src/com/cloud/vm/dao/NicDao.java @@ -58,4 +58,6 @@ public interface NicDao extends GenericDao { NicVO findByNetworkIdInstanceIdAndBroadcastUri(long networkId, long instanceId, String broadcastUri); NicVO findByIp4AddressAndNetworkIdAndInstanceId(long networkId, long instanceId, String ip4Address); + + NicVO findByMacAddress(String macAddress); } diff --git a/server/src/com/cloud/vm/dao/NicDaoImpl.java b/server/src/com/cloud/vm/dao/NicDaoImpl.java index 3cd7fa6b488..00da2eb96a4 100644 --- a/server/src/com/cloud/vm/dao/NicDaoImpl.java +++ b/server/src/com/cloud/vm/dao/NicDaoImpl.java @@ -50,6 +50,7 @@ public class NicDaoImpl extends GenericDaoBase implements NicDao { AllFieldsSearch.and("address", AllFieldsSearch.entity().getIp4Address(), Op.EQ); AllFieldsSearch.and("isDefault", AllFieldsSearch.entity().isDefaultNic(), Op.EQ); AllFieldsSearch.and("broadcastUri", AllFieldsSearch.entity().getBroadcastUri(), Op.EQ); + AllFieldsSearch.and("macAddress", AllFieldsSearch.entity().getMacAddress(), Op.EQ); AllFieldsSearch.done(); IpSearch = createSearchBuilder(String.class); @@ -199,4 +200,11 @@ public class NicDaoImpl extends GenericDaoBase implements NicDao { sc.setParameters("address", ip4Address); return findOneBy(sc); } + + @Override + public NicVO findByMacAddress(String macAddress) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("macAddress", macAddress); + return findOneBy(sc); + } } diff --git a/server/test/com/cloud/network/MockNetworkManagerImpl.java b/server/test/com/cloud/network/MockNetworkManagerImpl.java index bcc9ba2b604..071069c78eb 100755 --- a/server/test/com/cloud/network/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/network/MockNetworkManagerImpl.java @@ -16,14 +16,6 @@ // under the License. package com.cloud.network; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - import com.cloud.acl.ControlledEntity.ACLType; import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd; import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd; @@ -35,12 +27,7 @@ import com.cloud.dc.Vlan.VlanType; import com.cloud.deploy.DataCenterDeployment; import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeploymentPlan; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InsufficientVirtualNetworkCapcityException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; +import com.cloud.exception.*; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.Network.Capability; import com.cloud.network.Network.GuestType; @@ -61,13 +48,14 @@ import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.utils.Pair; import com.cloud.utils.component.Manager; -import com.cloud.vm.Nic; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachineProfile; -import com.cloud.vm.VirtualMachineProfileImpl; +import com.cloud.vm.*; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; @Local(value = { NetworkManager.class, NetworkService.class }) public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkService { @@ -796,10 +784,10 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } /* (non-Javadoc) - * @see com.cloud.network.NetworkService#allocateIP(com.cloud.user.Account, boolean, long) + * @see com.cloud.network.NetworkService#allocateIP(com.cloud.user.Account, long, Long) */ @Override - public IpAddress allocateIP(Account ipOwner, boolean isSystem, long zoneId) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException { + public IpAddress allocateIP(Account ipOwner, long zoneId, Long networkId) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException { // TODO Auto-generated method stub return null; } @@ -939,7 +927,6 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } /* (non-Javadoc) -<<<<<<< HEAD * @see com.cloud.network.NetworkManager#getDefaultPublicTrafficLabel(long, com.cloud.hypervisor.Hypervisor.HypervisorType) */ @Override @@ -950,9 +937,6 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS /* (non-Javadoc) * @see com.cloud.network.NetworkManager#assignSourceNatIpAddressToGuestNetwork(com.cloud.user.Account, com.cloud.network.Network) -======= - * @see com.cloud.network.NetworkManager#getNicProfile(com.cloud.vm.VirtualMachine, long) ->>>>>>> ddb9e49... VPC: unittest preparation */ @Override public PublicIp assignSourceNatIpAddressToGuestNetwork(Account owner, Network guestNetwork) throws InsufficientAddressCapacityException, ConcurrentOperationException { @@ -1007,7 +991,6 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } /* (non-Javadoc) -<<<<<<< HEAD * @see com.cloud.network.NetworkManager#getSite2SiteVpnElements() */ @Override @@ -1018,9 +1001,6 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS /* (non-Javadoc) * @see com.cloud.network.NetworkManager#isPrivateGateway(com.cloud.vm.Nic) -======= - * @see com.cloud.network.NetworkService#canUseForDeploy(com.cloud.network.Network) ->>>>>>> ddb9e49... VPC: unittest preparation */ @Override public boolean isPrivateGateway(Nic guestNic) { diff --git a/server/test/com/cloud/vpc/MockNetworkManagerImpl.java b/server/test/com/cloud/vpc/MockNetworkManagerImpl.java index adb80f08178..2525111d36a 100644 --- a/server/test/com/cloud/vpc/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/vpc/MockNetworkManagerImpl.java @@ -38,30 +38,14 @@ import com.cloud.dc.Vlan.VlanType; import com.cloud.deploy.DataCenterDeployment; import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeploymentPlan; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InsufficientVirtualNetworkCapcityException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; +import com.cloud.exception.*; import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.network.IPAddressVO; -import com.cloud.network.IpAddress; -import com.cloud.network.Network; +import com.cloud.network.*; import com.cloud.network.Network.Capability; import com.cloud.network.Network.GuestType; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; -import com.cloud.network.NetworkManager; -import com.cloud.network.NetworkProfile; -import com.cloud.network.NetworkService; -import com.cloud.network.NetworkVO; import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.PhysicalNetworkSetupInfo; -import com.cloud.network.PhysicalNetworkTrafficType; -import com.cloud.network.PublicIpAddress; import com.cloud.network.addr.PublicIp; import com.cloud.network.dao.NetworkServiceMapDao; import com.cloud.network.element.NetworkElement; @@ -80,14 +64,13 @@ import com.cloud.utils.Pair; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; -import com.cloud.vm.Nic; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachineProfile; -import com.cloud.vm.VirtualMachineProfileImpl; +import com.cloud.vm.*; import com.cloud.vpc.dao.MockVpcVirtualRouterElement; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.util.*; @Local(value = { NetworkManager.class, NetworkService.class }) public class MockNetworkManagerImpl implements NetworkManager, Manager{ @@ -1493,7 +1476,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager{ * @see com.cloud.network.NetworkService#allocateIP(com.cloud.user.Account, boolean, long) */ @Override - public IpAddress allocateIP(Account ipOwner, boolean isSystem, long zoneId) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException { + public IpAddress allocateIP(Account ipOwner, long zoneId, Long networkId) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException { // TODO Auto-generated method stub return null; } diff --git a/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java b/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java index 2a675b3a217..509d9c72f73 100644 --- a/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java +++ b/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java @@ -342,4 +342,13 @@ public class MockNetworkDaoImpl extends GenericDaoBase implemen return 0; } + /* (non-Javadoc) + * @see com.cloud.network.dao.NetworkDao#listNetworksByAccount(long, long, com.cloud.network.Network.GuestType, boolean) + */ + @Override + public List listNetworksByAccount(long accountId, long zoneId, GuestType type, boolean isSystem) { + // TODO Auto-generated method stub + return null; + } + } diff --git a/setup/db/create-schema-premium.sql b/setup/db/create-schema-premium.sql index d84718ee56a..2f86c0b9ab5 100644 --- a/setup/db/create-schema-premium.sql +++ b/setup/db/create-schema-premium.sql @@ -136,6 +136,7 @@ CREATE TABLE `cloud_usage`.`account` ( `removed` datetime COMMENT 'date removed', `cleanup_needed` tinyint(1) NOT NULL default '0', `network_domain` varchar(100) COMMENT 'Network domain name of the Vms of the account', + `default_zone_id` bigint unsigned, CONSTRAINT `uc_account__uuid` UNIQUE (`uuid`), PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/setup/db/create-schema-simulator.sql b/setup/db/create-schema-simulator.sql index 1ab838b1e73..6d4a130e2ba 100644 --- a/setup/db/create-schema-simulator.sql +++ b/setup/db/create-schema-simulator.sql @@ -76,6 +76,7 @@ CREATE TABLE `simulator`.`mockvm` ( `vnc_port` bigint unsigned, `memory` bigint unsigned, `cpu` bigint unsigned, + `bootargs` varchar(255), PRIMARY KEY (`id`), INDEX `i_mockvm__host_id`(`host_id`), INDEX `i_mockvm__state`(`state`), diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index c9c75af7f41..a95f190a458 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -146,6 +146,8 @@ DROP TABLE IF EXISTS `cloud`.`s2s_vpn_gateway`; DROP TABLE IF EXISTS `cloud`.`s2s_vpn_connection`; DROP TABLE IF EXISTS `cloud`,`external_nicira_nvp_devices`; DROP TABLE IF EXISTS `cloud`,`nicira_nvp_nic_map`; +DROP TABLE IF EXISTS `cloud`,`s3`; +DROP TABLE IF EXISTS `cloud`,`template_s3_ref`; DROP TABLE IF EXISTS `cloud`,`nicira_nvp_router_map`; DROP TABLE IF EXISTS `cloud`.`autoscale_vmgroup_policy_map`; DROP TABLE IF EXISTS `cloud`.`autoscale_policy_condition_map`; @@ -304,6 +306,7 @@ CREATE TABLE `cloud`.`network_offerings` ( `state` char(32) COMMENT 'state of the network offering that has Disabled value by default', `guest_type` char(32) COMMENT 'type of guest network that can be shared or isolated', `elastic_ip_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if the network offering provides elastic ip service', + `eip_associate_public_ip` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if public IP is associated with user VM creation by default when EIP service is enabled.', `elastic_lb_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if the network offering provides elastic lb service', `specify_ip_ranges` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if the network offering provides an ability to define ip ranges', PRIMARY KEY (`id`), @@ -480,12 +483,14 @@ CREATE TABLE `cloud`.`snapshots` ( `removed` datetime COMMENT 'Date removed. not null if removed', `backup_snap_id` varchar(255) COMMENT 'Back up uuid of the snapshot', `swift_id` bigint unsigned COMMENT 'which swift', + `s3_id` bigint unsigned COMMENT 'S3 to which this snapshot will be stored', `sechost_id` bigint unsigned COMMENT 'secondary storage host id', `prev_snap_id` bigint unsigned COMMENT 'Id of the most recent snapshot', `hypervisor_type` varchar(32) NOT NULL COMMENT 'hypervisor that the snapshot was taken under', `version` varchar(32) COMMENT 'snapshot version', PRIMARY KEY (`id`), CONSTRAINT `uc_snapshots__uuid` UNIQUE (`uuid`), + CONSTRAINT `fk_snapshots__s3_id` FOREIGN KEY `fk_snapshots__s3_id` (`s3_id`) REFERENCES `s3` (`id`), INDEX `i_snapshots__removed`(`removed`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; @@ -1851,6 +1856,36 @@ CREATE TABLE `cloud`.`swift` ( CONSTRAINT `uc_swift__uuid` UNIQUE (`uuid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE `cloud`.`s3` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', + `uuid` varchar(40), + `access_key` varchar(20) NOT NULL COMMENT ' The S3 access key', + `secret_key` varchar(40) NOT NULL COMMENT ' The S3 secret key', + `end_point` varchar(1024) COMMENT ' The S3 host', + `bucket` varchar(63) NOT NULL COMMENT ' The S3 host', + `https` tinyint unsigned DEFAULT NULL COMMENT ' Flag indicating whether or not to connect over HTTPS', + `connection_timeout` integer COMMENT ' The amount of time to wait (in milliseconds) when initially establishing a connection before giving up and timing out.', + `max_error_retry` integer COMMENT ' The maximum number of retry attempts for failed retryable requests (ex: 5xx error responses from services).', + `socket_timeout` integer COMMENT ' The amount of time to wait (in milliseconds) for data to be transfered over an established, open connection before the connection times out and is closed.', + `created` datetime COMMENT 'date the s3 first signed on', + PRIMARY KEY (`id`), + CONSTRAINT `uc_s3__uuid` UNIQUE (`uuid`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`template_s3_ref` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', + `s3_id` bigint unsigned NOT NULL COMMENT ' Associated S3 instance id', + `template_id` bigint unsigned NOT NULL COMMENT ' Associated template id', + `created` DATETIME NOT NULL COMMENT ' The creation timestamp', + `size` bigint unsigned COMMENT ' The size of the object', + `physical_size` bigint unsigned DEFAULT 0 COMMENT ' The physical size of the object', + PRIMARY KEY (`id`), + CONSTRAINT `uc_template_s3_ref__template_id` UNIQUE (`template_id`), + CONSTRAINT `fk_template_s3_ref__s3_id` FOREIGN KEY `fk_template_s3_ref__s3_id` (`s3_id`) REFERENCES `s3` (`id`) ON DELETE CASCADE, + CONSTRAINT `fk_template_s3_ref__template_id` FOREIGN KEY `fk_template_s3_ref__template_id` (`template_id`) REFERENCES `vm_template` (`id`), + INDEX `i_template_s3_ref__s3_id`(`s3_id`), + INDEX `i_template_s3_ref__template_id`(`template_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `cloud`.`op_host_transfer` ( `id` bigint unsigned UNIQUE NOT NULL COMMENT 'Id of the host', diff --git a/setup/db/db/schema-302to40.sql b/setup/db/db/schema-302to40.sql index 0c4efa33025..a947ac1bee6 100644 --- a/setup/db/db/schema-302to40.sql +++ b/setup/db/db/schema-302to40.sql @@ -477,3 +477,4 @@ INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'manag UPDATE `cloud`.`configuration` set description ='Uuid of the service offering used by console proxy; if NULL - system offering will be used' where name ='consoleproxy.service.offering'; UPDATE `cloud`.`user` SET PASSWORD=RAND() WHERE id=1; +ALTER TABLE `cloud_usage`.`account` ADD COLUMN `default_zone_id` bigint unsigned; diff --git a/setup/db/db/schema-40to410.sql b/setup/db/db/schema-40to410.sql index 487f1c1c768..6c58bd91872 100644 --- a/setup/db/db/schema-40to410.sql +++ b/setup/db/db/schema-40to410.sql @@ -637,4 +637,3 @@ left join host_tags on host_tags.host_id = host.id left join op_host_capacity mem_caps on host.id = mem_caps.host_id and mem_caps.capacity_type = 0 left join op_host_capacity cpu_caps on host.id = cpu_caps.host_id and cpu_caps.capacity_type = 1 left join async_job on async_job.instance_id = host.id and async_job.instance_type = "Host" and async_job.job_status = 0; - diff --git a/test/integration/component/test_snapshots.py b/test/integration/component/test_snapshots.py index 27c960f1b16..8659f14309a 100644 --- a/test/integration/component/test_snapshots.py +++ b/test/integration/component/test_snapshots.py @@ -105,7 +105,7 @@ class Services: "templates": { "displaytext": 'Template', "name": 'Template', - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', + "ostype": "CentOS 5.3 (64-bit)", "templatefilter": 'self', }, "diskdevice": "/dev/xvda", @@ -117,8 +117,7 @@ class Services: "sub_lvl_dir1": "test1", "sub_lvl_dir2": "test2", "random_data": "random.data", - - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', + "ostype": "CentOS 5.3 (64-bit)", # Cent OS 5.3 (64 bit) "sleep": 60, "timeout": 10, @@ -139,11 +138,11 @@ class TestSnapshotRootDisk(cloudstackTestCase): template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) cls.services["domainid"] = cls.domain.id cls.services["server_without_disk"]["zoneid"] = cls.zone.id - cls.services["template"] = template.id + cls.services["templates"]["ostypeid"] = template.ostypeid cls.services["zoneid"] = cls.zone.id # Create VMs, NAT Rules etc @@ -364,7 +363,7 @@ class TestSnapshots(cloudstackTestCase): template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) cls.services["domainid"] = cls.domain.id @@ -373,7 +372,7 @@ class TestSnapshots(cloudstackTestCase): cls.services["server_without_disk"]["zoneid"] = cls.zone.id - cls.services["template"] = template.id + cls.services["templates"]["ostypeid"] = template.ostypeid cls.services["zoneid"] = cls.zone.id cls.services["diskoffering"] = cls.disk_offering.id @@ -1195,12 +1194,11 @@ class TestCreateVMsnapshotTemplate(cloudstackTestCase): cls.template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) cls.services["domainid"] = cls.domain.id cls.services["server"]["zoneid"] = cls.zone.id - cls.services["template"] = cls.template.id # Create VMs, NAT Rules etc cls.account = Account.create( @@ -1491,7 +1489,7 @@ class TestAccountSnapshotClean(cloudstackTestCase): template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) cls.services["server"]["zoneid"] = cls.zone.id @@ -1843,7 +1841,7 @@ class TestSnapshotDetachedDisk(cloudstackTestCase): template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) cls.services["server"]["zoneid"] = cls.zone.id cls.services["server"]["diskoffering"] = cls.disk_offering.id @@ -2126,7 +2124,7 @@ class TestSnapshotLimit(cloudstackTestCase): template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) cls.services["server"]["zoneid"] = cls.zone.id @@ -2384,7 +2382,7 @@ class TestSnapshotEvents(cloudstackTestCase): template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) cls.services["server"]["zoneid"] = cls.zone.id diff --git a/test/integration/component/test_templates.py b/test/integration/component/test_templates.py index e6b2dd6c476..e9be63d66b8 100644 --- a/test/integration/component/test_templates.py +++ b/test/integration/component/test_templates.py @@ -283,6 +283,13 @@ class TestTemplates(cloudstackTestCase): # Get Zone, templates etc cls.domain = get_domain(cls.api_client, cls.services) cls.zone = get_zone(cls.api_client, cls.services) + #populate second zone id for iso copy + cmd = listZones.listZonesCmd() + zones = cls.api_client.listZones(cmd) + if not isinstance(zones, list): + raise Exception("Failed to find zones.") + if len(zones) >= 2: + cls.services["destzoneid"] = zones[1].id template = get_template( cls.api_client, @@ -467,6 +474,36 @@ class TestTemplates(cloudstackTestCase): ) # Cleanup- Delete the copied template + timeout = self.services["timeout"] + while True: + time.sleep(self.services["sleep"]) + list_template_response = list_templates( + self.apiclient, + templatefilter=\ + self.services["templatefilter"], + id=self.template_2.id, + zoneid=self.services["destzoneid"] + ) + self.assertEqual( + isinstance(list_template_response, list), + True, + "Check list response returns a valid list" + ) + self.assertNotEqual( + len(list_template_response), + 0, + "Check template extracted in List Templates" + ) + + template_response = list_template_response[0] + if template_response.isready == True: + break + + if timeout == 0: + raise Exception( + "Failed to download copied template(ID: %s)" % template_response.id) + + timeout = timeout - 1 cmd = deleteTemplate.deleteTemplateCmd() cmd.id = self.template.id cmd.zoneid = self.services["destzoneid"] diff --git a/test/integration/smoke/test_iso.py b/test/integration/smoke/test_iso.py index 0215d892e5c..22d424f86cc 100644 --- a/test/integration/smoke/test_iso.py +++ b/test/integration/smoke/test_iso.py @@ -55,7 +55,7 @@ class Services: "isextractable": True, "isfeatured": True, "ispublic": True, - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', + "ostype": "CentOS 5.3 (64-bit)", }, "iso_2": { @@ -66,12 +66,10 @@ class Services: "isextractable": True, "isfeatured": True, "ispublic": True, - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', + "ostype": "CentOS 5.3 (64-bit)", "mode": 'HTTP_DOWNLOAD', # Used in Extract template, value must be HTTP_DOWNLOAD }, - "destzoneid": 5, - # Copy ISO from one zone to another (Destination Zone) "isfeatured": True, "ispublic": True, "isextractable": True, @@ -79,7 +77,7 @@ class Services: "passwordenabled": True, "sleep": 60, "timeout": 10, - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', + "ostype": "CentOS 5.3 (64-bit)", # CentOS 5.3 (64 bit) "mode": 'advanced' # Networking mode: Basic or Advanced @@ -103,7 +101,18 @@ class TestCreateIso(cloudstackTestCase): self.services["account"], domainid=self.domain.id ) - + # Finding the OsTypeId from Ostype + ostypes = list_os_types( + self.apiclient, + description=self.services["ostype"] + ) + if not isinstance(ostypes, list): + raise unittest.SkipTest("OSTypeId for given description not found") + + self.services["iso_1"]["ostypeid"] = ostypes[0].id + self.services["iso_2"]["ostypeid"] = ostypes[0].id + self.services["ostypeid"] = ostypes[0].id + self.cleanup = [self.account] return @@ -192,6 +201,13 @@ class TestISO(cloudstackTestCase): cls.services["iso_1"]["zoneid"] = cls.zone.id cls.services["iso_2"]["zoneid"] = cls.zone.id cls.services["sourcezoneid"] = cls.zone.id + #populate second zone id for iso copy + cmd = listZones.listZonesCmd() + zones = cls.api_client.listZones(cmd) + if not isinstance(zones, list): + raise Exception("Failed to find zones.") + if len(zones) >= 2: + cls.services["destzoneid"] = zones[1].id #Create an account, ISOs etc. cls.account = Account.create( @@ -200,6 +216,18 @@ class TestISO(cloudstackTestCase): domainid=cls.domain.id ) cls.services["account"] = cls.account.account.name + # Finding the OsTypeId from Ostype + ostypes = list_os_types( + cls.api_client, + description=self.services["ostype"] + ) + if not isinstance(ostypes, list): + raise unittest.SkipTest("OSTypeId for given description not found") + + self.services["iso_1"]["ostypeid"] = ostypes[0].id + self.services["iso_2"]["ostypeid"] = ostypes[0].id + self.services["ostypeid"] = ostypes[0].id + cls.iso_1 = Iso.create( cls.api_client, cls.services["iso_1"], @@ -501,6 +529,35 @@ class TestISO(cloudstackTestCase): self.debug("Cleanup copied ISO: %s" % iso_response.id) # Cleanup- Delete the copied ISO + timeout = self.services["timeout"] + while True: + time.sleep(self.services["sleep"]) + list_iso_response = list_isos( + self.apiclient, + id=self.iso_2.id, + zoneid=self.services["destzoneid"] + ) + self.assertEqual( + isinstance(list_iso_response, list), + True, + "Check list response returns a valid list" + ) + + self.assertNotEqual( + len(list_iso_response), + 0, + "Check template extracted in List ISO" + ) + + iso_response = list_iso_response[0] + if iso_response.isready == True: + break + + if timeout == 0: + raise Exception( + "Failed to download copied iso(ID: %s)" % iso_response.id) + + timeout = timeout - 1 cmd = deleteIso.deleteIsoCmd() cmd.id = iso_response.id cmd.zoneid = self.services["destzoneid"] diff --git a/test/integration/smoke/test_network.py b/test/integration/smoke/test_network.py index 0a3a3c3bd74..e78cc43fe33 100644 --- a/test/integration/smoke/test_network.py +++ b/test/integration/smoke/test_network.py @@ -36,7 +36,7 @@ class Services: def __init__(self): self.services = { - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', + "ostype": "CentOS 5.3 (64-bit)", # Cent OS 5.3 (64 bit) "mode": 'advanced', # Networking mode: Basic or advanced @@ -305,7 +305,7 @@ class TestPortForwarding(cloudstackTestCase): template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) #Create an account, network, VM and IP addresses cls.account = Account.create( @@ -604,7 +604,7 @@ class TestLoadBalancingRule(cloudstackTestCase): template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) cls.services["server"]["zoneid"] = cls.zone.id @@ -1076,7 +1076,7 @@ class TestRebootRouter(cloudstackTestCase): template = get_template( self.apiclient, self.zone.id, - self.services["ostypeid"] + self.services["ostype"] ) self.services["server"]["zoneid"] = self.zone.id @@ -1236,7 +1236,7 @@ class TestAssignRemoveLB(cloudstackTestCase): template = get_template( self.apiclient, self.zone.id, - self.services["ostypeid"] + self.services["ostype"] ) self.services["server"]["zoneid"] = self.zone.id @@ -1495,7 +1495,7 @@ class TestReleaseIP(cloudstackTestCase): template = get_template( self.apiclient, self.zone.id, - self.services["ostypeid"] + self.services["ostype"] ) self.services["server"]["zoneid"] = self.zone.id @@ -1635,7 +1635,7 @@ class TestDeleteAccount(cloudstackTestCase): template = get_template( self.apiclient, self.zone.id, - self.services["ostypeid"] + self.services["ostype"] ) self.services["server"]["zoneid"] = self.zone.id diff --git a/test/integration/smoke/test_routers.py b/test/integration/smoke/test_routers.py index 967533965ae..93dc7606ace 100644 --- a/test/integration/smoke/test_routers.py +++ b/test/integration/smoke/test_routers.py @@ -61,7 +61,7 @@ class Services: "username": "testuser", "password": "password", }, - "ostypeid":'01853327-513e-4508-9628-f1f55db1946f', + "ostype": "CentOS 5.3 (64-bit)", "sleep": 60, "timeout": 10, "mode": 'advanced', #Networking mode: Basic, Advanced @@ -84,7 +84,7 @@ class TestRouterServices(cloudstackTestCase): template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) cls.services["virtual_machine"]["zoneid"] = cls.zone.id diff --git a/test/integration/smoke/test_templates.py b/test/integration/smoke/test_templates.py index 9a7f6b1459c..d450a5d8122 100644 --- a/test/integration/smoke/test_templates.py +++ b/test/integration/smoke/test_templates.py @@ -75,26 +75,24 @@ class Services: "template_1": { "displaytext": "Cent OS Template", "name": "Cent OS Template", - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', + "ostype": "CentOS 5.3 (64-bit)", }, "template_2": { "displaytext": "Public Template", "name": "Public template", - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', + "ostype": "CentOS 5.3 (64-bit)", "isfeatured": True, "ispublic": True, "isextractable": True, "mode": "HTTP_DOWNLOAD", }, "templatefilter": 'self', - "destzoneid": 5, - # For Copy template (Destination zone) "isfeatured": True, "ispublic": True, "isextractable": False, "bootable": True, "passwordenabled": True, - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', + "ostype": "CentOS 5.3 (64-bit)", "mode": 'advanced', # Networking mode: Advanced, basic "sleep": 30, @@ -135,8 +133,12 @@ class TestCreateTemplate(cloudstackTestCase): template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) + cls.services["template_1"]["ostypeid"] = template.ostypeid + cls.services["template_2"]["ostypeid"] = template.ostypeid + cls.services["ostypeid"] = template.ostypeid + cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.services["volume"]["diskoffering"] = cls.disk_offering.id cls.services["volume"]["zoneid"] = cls.zone.id @@ -291,6 +293,14 @@ class TestTemplates(cloudstackTestCase): # Get Zone, Domain and templates cls.domain = get_domain(cls.api_client, cls.services) cls.zone = get_zone(cls.api_client, cls.services) + #populate second zone id for iso copy + cmd = listZones.listZonesCmd() + zones = cls.api_client.listZones(cmd) + if not isinstance(zones, list): + raise Exception("Failed to find zones.") + if len(zones) >= 2: + cls.services["destzoneid"] = zones[1].id + cls.disk_offering = DiskOffering.create( cls.api_client, cls.services["disk_offering"] @@ -298,7 +308,7 @@ class TestTemplates(cloudstackTestCase): template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.services["volume"]["diskoffering"] = cls.disk_offering.id @@ -306,6 +316,10 @@ class TestTemplates(cloudstackTestCase): cls.services["template_2"]["zoneid"] = cls.zone.id cls.services["sourcezoneid"] = cls.zone.id + cls.services["template_1"]["ostypeid"] = template.ostypeid + cls.services["template_2"]["ostypeid"] = template.ostypeid + cls.services["ostypeid"] = template.ostypeid + cls.account = Account.create( cls.api_client, cls.services["account"], @@ -692,6 +706,36 @@ class TestTemplates(cloudstackTestCase): ) # Cleanup- Delete the copied template + timeout = self.services["timeout"] + while True: + time.sleep(self.services["sleep"]) + list_template_response = list_templates( + self.apiclient, + templatefilter=\ + self.services["templatefilter"], + id=self.template_2.id, + zoneid=self.services["destzoneid"] + ) + self.assertEqual( + isinstance(list_template_response, list), + True, + "Check list response returns a valid list" + ) + self.assertNotEqual( + len(list_template_response), + 0, + "Check template extracted in List Templates" + ) + + template_response = list_template_response[0] + if template_response.isready == True: + break + + if timeout == 0: + raise Exception( + "Failed to download copied template(ID: %s)" % template_response.id) + + timeout = timeout - 1 cmd = deleteTemplate.deleteTemplateCmd() cmd.id = template_response.id cmd.zoneid = self.services["destzoneid"] diff --git a/test/integration/smoke/test_vm_life_cycle.py b/test/integration/smoke/test_vm_life_cycle.py index a6d0c106526..1633c538342 100644 --- a/test/integration/smoke/test_vm_life_cycle.py +++ b/test/integration/smoke/test_vm_life_cycle.py @@ -90,7 +90,7 @@ class Services: "displaytext": "Small Instance", "cpunumber": 1, "cpuspeed": 100, - "memory": 256 + "memory": 256, }, "medium": { @@ -100,7 +100,7 @@ class Services: "displaytext": "Medium Instance", "cpunumber": 1, "cpuspeed": 100, - "memory": 256 + "memory": 256, } }, "iso": # ISO settings for Attach/Detach ISO tests @@ -109,7 +109,7 @@ class Services: "name": "testISO", "url": "http://iso.linuxquestions.org/download/504/1819/http/gd4.tuwien.ac.at/dsl-4.4.10.iso", # Source URL where ISO is located - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', + "ostype": 'CentOS 5.3 (64-bit)', "mode": 'HTTP_DOWNLOAD', # Downloading existing ISO }, "template": { @@ -123,9 +123,8 @@ class Services: "sleep": 60, "timeout": 10, #Migrate VM to hostid - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', + "ostype": 'CentOS 5.3 (64-bit)', # CentOS 5.3 (64-bit) - "mode":'advanced', } @@ -139,11 +138,19 @@ class TestDeployVM(cloudstackTestCase): # Get Zone, Domain and templates domain = get_domain(self.apiclient, self.services) zone = get_zone(self.apiclient, self.services) + self.services['mode'] = zone.networktype + + #if local storage is enabled, alter the offerings to use localstorage + #this step is needed for devcloud + if zone.localstorageenabled == True: + self.services["service_offerings"]["tiny"]["storagetype"] = 'local' + self.services["service_offerings"]["small"]["storagetype"] = 'local' + self.services["service_offerings"]["medium"]["storagetype"] = 'local' template = get_template( self.apiclient, zone.id, - self.services["ostypeid"] + self.services["ostype"] ) # Set Zones and disk offerings self.services["small"]["zoneid"] = zone.id @@ -170,7 +177,7 @@ class TestDeployVM(cloudstackTestCase): self.account ] - @attr(tags = ["advanced", "advancedns", "smoke", "basic", "sg"]) + @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg"]) def test_deploy_vm(self): """Test Deploy Virtual Machine """ @@ -185,7 +192,8 @@ class TestDeployVM(cloudstackTestCase): self.services["small"], accountid=self.account.account.name, domainid=self.account.account.domainid, - serviceofferingid=self.service_offering.id + serviceofferingid=self.service_offering.id, + mode=self.services['mode'] ) list_vm_response = list_virtual_machines( @@ -242,10 +250,19 @@ class TestVMLifeCycle(cloudstackTestCase): # Get Zone, Domain and templates domain = get_domain(cls.api_client, cls.services) zone = get_zone(cls.api_client, cls.services) + cls.services['mode'] = zone.networktype + + #if local storage is enabled, alter the offerings to use localstorage + #this step is needed for devcloud + if zone.localstorageenabled == True: + cls.services["service_offerings"]["tiny"]["storagetype"] = 'local' + cls.services["service_offerings"]["small"]["storagetype"] = 'local' + cls.services["service_offerings"]["medium"]["storagetype"] = 'local' + template = get_template( cls.api_client, zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) # Set Zones and disk offerings cls.services["small"]["zoneid"] = zone.id @@ -319,7 +336,7 @@ class TestVMLifeCycle(cloudstackTestCase): return - @attr(tags = ["advanced", "advancedns", "smoke", "basic", "sg"]) + @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg"]) def test_01_stop_vm(self): """Test Stop Virtual Machine """ @@ -355,7 +372,7 @@ class TestVMLifeCycle(cloudstackTestCase): ) return - @attr(tags = ["advanced", "advancedns", "smoke", "basic", "sg"]) + @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg"]) def test_02_start_vm(self): """Test Start Virtual Machine """ @@ -393,7 +410,7 @@ class TestVMLifeCycle(cloudstackTestCase): ) return - @attr(tags = ["advanced", "advancedns", "smoke", "basic", "sg"]) + @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg"]) def test_03_reboot_vm(self): """Test Reboot Virtual Machine """ @@ -669,7 +686,7 @@ class TestVMLifeCycle(cloudstackTestCase): ) return - @attr(tags = ["advanced", "advancedns", "smoke", "basic", "sg"]) + @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg"]) def test_06_destroy_vm(self): """Test destroy Virtual Machine """ @@ -705,7 +722,7 @@ class TestVMLifeCycle(cloudstackTestCase): ) return - @attr(tags = ["advanced", "advancedns", "smoke", "basic", "sg"]) + @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg"]) def test_07_restore_vm(self): """Test recover Virtual Machine """ @@ -818,7 +835,7 @@ class TestVMLifeCycle(cloudstackTestCase): @attr(configuration = "expunge.interval") @attr(configuration = "expunge.delay") - @attr(tags = ["advanced", "advancedns", "smoke", "basic", "sg"]) + @attr(tags = ["devcloud", "advanced", "advancedns", "smoke", "basic", "sg"]) def test_09_expunge_vm(self): """Test destroy(expunge) Virtual Machine """ @@ -999,7 +1016,7 @@ class TestVMPasswordEnabled(cloudstackTestCase): template = get_template( cls.api_client, zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) # Set Zones and disk offerings cls.services["small"]["zoneid"] = zone.id @@ -1065,7 +1082,7 @@ class TestVMPasswordEnabled(cloudstackTestCase): "Exception: Unable to find root volume foe VM: %s" % cls.virtual_machine.id) - cls.services["template"]["ostypeid"] = cls.services["ostypeid"] + cls.services["template"]["ostype"] = cls.services["ostype"] #Create templates for Edit, Delete & update permissions testcases cls.pw_enabled_template = Template.create( cls.api_client, diff --git a/test/integration/smoke/test_volumes.py b/test/integration/smoke/test_volumes.py index f8128081d39..2d0cd491672 100644 --- a/test/integration/smoke/test_volumes.py +++ b/test/integration/smoke/test_volumes.py @@ -75,8 +75,8 @@ class Services: "publicport": 22, "protocol": 'TCP', "diskdevice": "/dev/xvdb", - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', - "mode": 'advanced', + "ostype": 'CentOS 5.3 (64-bit)', + "mode": 'basic', "sleep": 60, "timeout": 10, } @@ -104,7 +104,7 @@ class TestCreateVolume(cloudstackTestCase): template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) cls.services["domainid"] = cls.domain.id cls.services["zoneid"] = cls.zone.id @@ -286,7 +286,7 @@ class TestVolumes(cloudstackTestCase): template = get_template( cls.api_client, cls.zone.id, - cls.services["ostypeid"] + cls.services["ostype"] ) cls.services["domainid"] = cls.domain.id cls.services["zoneid"] = cls.zone.id diff --git a/tools/apidoc/gen_toc.py b/tools/apidoc/gen_toc.py index eeaf2a29cc2..abff8d15980 100644 --- a/tools/apidoc/gen_toc.py +++ b/tools/apidoc/gen_toc.py @@ -116,6 +116,7 @@ known_categories = { 'LB': 'Load Balancer', 'ldap': 'LDAP', 'Swift': 'Swift', + 'S3' : 'S3', 'SecondaryStorage': 'Host', 'Project': 'Project', 'Lun': 'Storage', diff --git a/tools/cli/cloudmonkey/cloudmonkey.py b/tools/cli/cloudmonkey/cloudmonkey.py index 8ceba4a0a15..edb62ccc801 100644 --- a/tools/cli/cloudmonkey/cloudmonkey.py +++ b/tools/cli/cloudmonkey/cloudmonkey.py @@ -26,7 +26,6 @@ try: import logging import os import pdb - import sets import shlex import sys import time @@ -37,6 +36,7 @@ try: from urllib2 import HTTPError, URLError from httplib import BadStatusLine + from prettytable import PrettyTable from common import __version__, config_file, config_fields from common import grammar, precached_verbs from marvin.cloudstackConnection import cloudConnection @@ -65,7 +65,7 @@ logger = logging.getLogger(__name__) completions = cloudstackAPI.__all__ -class CloudStackShell(cmd.Cmd): +class CloudMonkeyShell(cmd.Cmd, object): intro = ("☠Apache CloudStack 🵠cloudmonkey " + __version__ + ". Type help or ? to list commands.\n") ruler = "=" @@ -133,6 +133,15 @@ class CloudStackShell(cmd.Cmd): def emptyline(self): pass + def cmdloop(self, intro=None): + print self.intro + while True: + try: + super(CloudMonkeyShell, self).cmdloop(intro="") + self.postloop() + except KeyboardInterrupt: + print("^C") + def print_shell(self, *args): try: for arg in args: @@ -164,29 +173,58 @@ class CloudStackShell(cmd.Cmd): except Exception, e: print colored.red("Error: "), e - def print_result(self, result): + def print_result(self, result, result_filter=None): if result is None or len(result) == 0: return - def print_result_as_dict(result): + def printer_helper(printer, toprow): + if printer: + print printer + return PrettyTable(toprow) + + def print_result_tabular(result, result_filter=None): + toprow = None + printer = None + for node in result: + if toprow != node.keys(): + if result_filter is not None and len(result_filter) != 0: + commonkeys = filter(lambda x: x in node.keys(), + result_filter) + if commonkeys != toprow: + toprow = commonkeys + printer = printer_helper(printer, toprow) + else: + toprow = node.keys() + printer = printer_helper(printer, toprow) + row = map(lambda x: node[x], toprow) + if printer and row: + printer.add_row(row) + if printer: + print printer + + def print_result_as_dict(result, result_filter=None): for key in result.keys(): if not (isinstance(result[key], list) or isinstance(result[key], dict)): self.print_shell("%s = %s" % (key, result[key])) else: - self.print_shell(key + ":\n" + len(key) * "=") - self.print_result(result[key]) + self.print_shell(key + ":\n" + len(key) * self.ruler) + self.print_result(result[key], result_filter) - def print_result_as_list(result): + def print_result_as_list(result, result_filter=None): for node in result: + # Tabular print if it's a list of dict and tabularize is true + if isinstance(node, dict) and self.tabularize == 'true': + print_result_tabular(result, result_filter) + break self.print_result(node) if len(result) > 1: self.print_shell(self.ruler * 80) if isinstance(result, dict): - print_result_as_dict(result) + print_result_as_dict(result, result_filter) elif isinstance(result, list): - print_result_as_list(result) + print_result_as_list(result, result_filter) elif isinstance(result, str): print result elif not (str(result) is None): @@ -272,8 +310,12 @@ class CloudStackShell(cmd.Cmd): args_dict = dict(map(lambda x: [x.partition("=")[0], x.partition("=")[2]], args[1:])[x] for x in range(len(args) - 1)) + field_filter = None + if 'filter' in args_dict: + field_filter = filter(lambda x: x is not '', + map(lambda x: x.strip(), + args_dict.pop('filter').split(','))) - # FIXME: With precaching, dynamic loading can be removed api_cmd_str = "%sCmd" % api_name api_mod = self.get_api_module(api_name, [api_cmd_str]) if api_mod is None: @@ -289,8 +331,8 @@ class CloudStackShell(cmd.Cmd): setattr(api_cmd, attribute, args_dict[attribute]) command = api_cmd() - missing_args = list(sets.Set(command.required).difference( - sets.Set(args_dict.keys()))) + missing_args = filter(lambda x: x not in args_dict.keys(), + command.required) if len(missing_args) > 0: self.print_shell("Missing arguments:", ' '.join(missing_args)) @@ -304,7 +346,9 @@ class CloudStackShell(cmd.Cmd): if result is None: return try: - self.print_result(result.values()) + # Response is in the key "apiname+response" (lowercase) + self.print_result(result[api_name.lower() + 'response'], + field_filter) print except Exception as e: self.print_shell("🙈 Error on parsing and printing", e) @@ -358,6 +402,7 @@ class CloudStackShell(cmd.Cmd): self.cache_verbs[verb][subject][1]) search_string = text + autocompletions.append("filter=") return [s for s in autocompletions if s.startswith(search_string)] def do_api(self, args): @@ -379,7 +424,7 @@ class CloudStackShell(cmd.Cmd): def do_set(self, args): """ - Set config for CloudStack CLI. Available options are: + Set config for cloudmonkey. For example, options can be: host, port, apikey, secretkey, log_file, history_file You may also edit your ~/.cloudmonkey_config instead of using set. @@ -451,13 +496,13 @@ class CloudStackShell(cmd.Cmd): def do_exit(self, args): """ - Quit Apache CloudStack CLI + Quit CloudMonkey CLI """ return self.do_quit(args) def do_quit(self, args): """ - Quit Apache CloudStack CLI + Quit CloudMonkey CLI """ self.print_shell("Bye!") return self.do_EOF(args) @@ -466,12 +511,12 @@ class CloudStackShell(cmd.Cmd): """ Quit on Ctrl+d or EOF """ - return True + sys.exit() def main(): # Create handlers on the fly using closures - self = CloudStackShell + self = CloudMonkeyShell global grammar for rule in grammar: def add_grammar(rule): @@ -487,7 +532,6 @@ def main(): try: args_partition = args.partition(" ") res = self.cache_verbs[rule][args_partition[0]] - except KeyError, e: self.print_shell("Error: invalid %s api arg" % rule, e) return @@ -502,7 +546,7 @@ def main(): grammar_handler.__name__ = 'do_' + rule setattr(self, grammar_handler.__name__, grammar_handler) - shell = CloudStackShell() + shell = CloudMonkeyShell() if len(sys.argv) > 1: shell.onecmd(' '.join(sys.argv[1:])) else: diff --git a/tools/cli/cloudmonkey/common.py b/tools/cli/cloudmonkey/common.py index 8a64a5d1a27..3199af26c85 100644 --- a/tools/cli/cloudmonkey/common.py +++ b/tools/cli/cloudmonkey/common.py @@ -33,6 +33,7 @@ config_fields = {'host': 'localhost', 'port': '8080', 'apikey': '', 'secretkey': '', 'timeout': '3600', 'asyncblock': 'true', 'prompt': '🵠cloudmonkey>', 'color': 'true', + 'tabularize': 'false', 'log_file': os.path.expanduser('~/.cloudmonkey_log'), 'history_file': diff --git a/tools/cli/setup.py b/tools/cli/setup.py index 4343eef0d21..739c044f7dd 100644 --- a/tools/cli/setup.py +++ b/tools/cli/setup.py @@ -26,7 +26,9 @@ from cloudmonkey import __version__ name = 'cloudmonkey' version = __version__ -requires = ['clint>=0.3.0',] +requires = ['clint>=0.3.0', + 'prettytable>=0.6', + ] try: import readline diff --git a/tools/devcloud/README.md b/tools/devcloud/README.md new file mode 100644 index 00000000000..410c36f5ea5 --- /dev/null +++ b/tools/devcloud/README.md @@ -0,0 +1,102 @@ +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. + +=========================================================== + +NOTE - This folder is a work in progress. The project has not determined +how to best establish a nightly DevCloud build process, or how to distribute +the image. + +=========================================================== + +# Setting up Tools and Environment + + - Install [RVM](https://rvm.io/rvm/install) + - Setup paths: + export PATH=~/.rvm/bin:$PATH + - Install Ruby 1.9.3, if it installed some other version: + rvm install 1.9.3 + +All the dependencies will be fetched automatically. + +Vagrant: https://github.com/chipchilders/vagrant.git +Veewee: https://github.com/jedi4ever/veewee.git + +devcloudbase/Ubuntu: http://releases.ubuntu.com/12.04/ubuntu-12.04.1-server-i386.iso + +To save some time if you've downloaded iso of your distro, put the isos in: +tools/devcloud/deps/boxes/basebox-build/iso/ + +Note, gem would require gcc-4.2, make sure link exists: + + sudo ln -s /usr/bin/gcc /usr/bin/gcc-4.2 + +# How to build DevCloud + +DevCloud build scripts are in src/ +Move to src/deps/ to start the build process: + + cd src/deps/ + +Clean up any old stuff: + + ./boxer.sh -c all + +Build the dependent vms: + + ./boxer.sh -b all + +Now, start DevCloud: + + # Go back to the devcloud homedir + cd ../ + # Bring up the devcloud vm + vagrant up + +If you get a vagrant error, at that point, try: + + source .rvmrc + vagrant up + +# CloudStack Build Automation in DevCloud + +If you want to compile cloudstack in the devcloud vm: + + vim puppet/modules/devcloud/manifests/params.pp + +and set + + $build_cloudstack = true + +alternately, if you do not want to build cloudstack in the devcloud vm, set: + + $build_cloudstack = false + + +It will now bring up the devcloud vm for this first time. Note that it will +attempt to download the SSVM and CPVM templates so it will take a long time to +launch initially. It will also git clone the cloudstack repository and attempt +to build an launch it. + +You can optionally speed things up by packaging a successful devcloud instance +build. This will make subsequent launches must faster since it won't have to +re-downoad the SSVM and CPVM. Once it has successfully been built, you can run: + + #exports the devcloud vagrant instance and adds it as "devcloud" to vagrant boxlist + ./boxit.sh + #modifies the Vagrant file to use this newly added instance + sed -i 's,devcloudbase-xen,devcloud,g' Vagrantfile diff --git a/tools/devcloud/basebuild/Vagrantfile b/tools/devcloud/basebuild/Vagrantfile deleted file mode 100644 index a1f0740bc84..00000000000 --- a/tools/devcloud/basebuild/Vagrantfile +++ /dev/null @@ -1,51 +0,0 @@ -# -*- mode: ruby -*- -# vi: set ft=ruby : - -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -Vagrant::Config.run do |config| - config.vm.box = "devcloudbase" - # TODO: Get a URL to host the base image - # config.vm.box_url = "http://domain.com/path/to/above.box" - config.vm.guest = :xen - config.ssh.username = "devcloud" - - # Uncomment this line to enable the console for debugging the - # build process. - #config.vm.boot_mode = :gui - - # Setup port forwarding - config.vm.forward_port 22, 2222 - config.vm.forward_port 8080, 8080 - config.vm.forward_port 8443, 8443 - config.vm.forward_port 5901, 5901 - config.vm.forward_port 8787, 8787 - config.vm.forward_port 8250, 8250 - - # Ensure the VM has the right virtual resources - #config.vm. - - config.vm.provision :puppet do |puppet| - puppet.manifests_path = "puppet-devcloudinitial" - puppet.manifest_file = "init.pp" - puppet.with_ssh = true - puppet.pp_path = "/etc/puppet" - puppet.module_path = "puppet-devcloudinitial" - end - -end diff --git a/tools/devcloud/basebuild/puppet-devcloudinitial/files/network.conf b/tools/devcloud/basebuild/puppet-devcloudinitial/files/network.conf deleted file mode 100644 index 7096907a5ff..00000000000 --- a/tools/devcloud/basebuild/puppet-devcloudinitial/files/network.conf +++ /dev/null @@ -1 +0,0 @@ -bridge diff --git a/tools/devcloud/basebuild/puppet-devcloudinitial/manifests/init.pp b/tools/devcloud/basebuild/puppet-devcloudinitial/manifests/init.pp deleted file mode 100644 index ded206759e2..00000000000 --- a/tools/devcloud/basebuild/puppet-devcloudinitial/manifests/init.pp +++ /dev/null @@ -1,106 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -class puppet-devcloudinitial { - - package { 'linux-headers-3.2.0-23-generic': - ensure => latest, - } - - package { 'xen-hypervisor-4.1-i386': - ensure => latest, - } - - package { 'xcp-xapi': - require => Package['xen-hypervisor-4.1-i386'], - ensure => latest, - } - - file { '/etc/xcp/network.conf': - require => Package['xcp-xapi'], - ensure => 'file', - source => 'puppet:///modules/puppet-devcloudinitial/network.conf', - group => '0', - mode => '644', - owner => '0', - } - - file { '/etc/init.d/xend': - require => Package['xcp-xapi'], - ensure => 'file', - source => 'puppet:///modules/puppet-devcloudinitial/xend', - group => '0', - owner => '0', - mode => '755', - } - - service { 'xendomains': - require => Package['xcp-xapi'], - ensure => 'stopped', - enable => 'false', - } - - file { '/etc/default/grub': - require => Package['xen-hypervisor-4.1-i386'], - ensure => 'file', - source => 'puppet:///modules/puppet-devcloudinitial/grub', - group => '0', - mode => '644', - owner => '0', - } - - exec { "/usr/sbin/update-grub": - subscribe => File['/etc/default/grub'], - refreshonly => true, - cwd => '/', - } - - file { '/usr/share/qemu': - require => Package['xen-hypervisor-4.1-i386'], - ensure => 'directory', - group => '0', - mode => '755', - owner => '0', - } - - file { '/usr/share/qemu/keymaps': - require => File['/usr/share/qemu'], - ensure => 'link', - group => '0', - mode => '777', - owner => '0', - target => '/usr/share/qemu-linaro/keymaps', - } - - file { '/etc/network/interfaces': - ensure => 'file', - source => 'puppet:///modules/puppet-devcloudinitial/interfaces', - group => '0', - mode => '644', - owner => '0', - } - - file { '/etc/default/xen': - require => Package['xen-hypervisor-4.1-i386'], - ensure => 'file', - source => 'puppet:///modules/puppet-devcloudinitial/xen-defaults', - group => '0', - mode => '644', - owner => '0', - } - -} diff --git a/tools/devcloud/build_vagrant_basebox.sh b/tools/devcloud/build_vagrant_basebox.sh deleted file mode 100755 index c90a6c9ba60..00000000000 --- a/tools/devcloud/build_vagrant_basebox.sh +++ /dev/null @@ -1,99 +0,0 @@ -#!/bin/bash -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -# Assumes that rvm is installed and you have ruby 1.9.2 installed -# Assumes that you have virtual box installed -# Assumes that you have wget installed -set -x -PROGNAME=$(basename $0) -function error_exit { - - # Display error message and exit - echo "${PROGNAME}: $*" 1>&2 - exit 1 -} - - -# Load RVM into a shell session *as a function* -if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then -# First try to load from a user install - source "$HOME/.rvm/scripts/rvm" - -elif [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then - -# Then try to load from a root install - source "/usr/local/rvm/scripts/rvm" - -else - - printf "ERROR: An RVM installation was not found.\n" - -fi - -mkdir ~/builddevcloud || error_exit -cd ~/builddevcloud || error_exit -git clone https://github.com/jedi4ever/veewee.git || error_exit -#TODO: We need to get this patched version of Vagrant to the upstream project -# or implement the desired changes to Vagrant as plugin modules and -# host it within the ASF git repo -git clone https://github.com/chipchilders/vagrant.git || error_exit -export rvm_trust_rvmrcs_flag=1 || error_exit -cd vagrant || error_exit -bundle install || error_exit "could not bundle install vagrant" -rake install || error_exit "could not rake vagrant" -cd ~/builddevcloud/veewee || error_exit -cp -R templates/ubuntu-12.04-server-i386 templates/ubuntu-12.04.1-server-i386 -cp -R templates/ubuntu-12.04-server-i386-packages templates/ubuntu-12.04.1-server-i386-packages -bundle install || error_exit -rake install || error_exit -bundle exec vagrant basebox define 'devcloudbase' 'ubuntu-12.04.1-server-i386' || error_exit "couldn't basebox define" -wget --no-check-certificate -O ./definitions/devcloudbase/definition.rb https://git-wip-us.apache.org/repos/asf\?p\=incubator-cloudstack.git\;a\=blob_plain\;f\=tools/devcloud/veewee/definition.rb\;hb\=HEAD || error_exit "couldn't get file" -wget --no-check-certificate -O ./definitions/devcloudbase/postinstall.sh https://git-wip-us.apache.org/repos/asf\?p\=incubator-cloudstack.git\;a\=blob_plain\;f\=tools/devcloud/veewee/postinstall.sh\;hb\=HEAD || error_exit "couldn't get file" -wget --no-check-certificate -O ./definitions/devcloudbase/preseed.cfg https://git-wip-us.apache.org/repos/asf\?p\=incubator-cloudstack.git\;a\=blob_plain\;f\=tools/devcloud/veewee/preseed.cfg\;hb\=HEAD || error_exit "couldn't get file" -bundle exec vagrant basebox build 'devcloudbase' -f -a -n || error_exit "couldn't basebox build" -# possibly use -r here too ^ -bundle exec vagrant basebox export 'devcloudbase' -f || error_exit "couldn't basebox export" -bundle exec vagrant basebox destroy 'devcloudbase' -f || error_exit "couldn't basebox destroy" -bundle exec vagrant box add 'devcloudbase' 'devcloudbase.box' -f || error_exit "couldn't basebox add" -rm -f devcloudbase.box || error_exit -cd ~/builddevcloud/vagrant || error_exit -mkdir devcloudbase || error_exit -cd devcloudbase || error_exit -mkdir puppet-devcloudinitial || error_exit -mkdir puppet-devcloudinitial/files || error_exit -mkdir puppet-devcloudinitial/manifests || error_exit -wget --no-check-certificate -O Vagrantfile "https://git-wip-us.apache.org/repos/asf?p=incubator-cloudstack.git;a=blob_plain;f=tools/devcloud/basebuild/Vagrantfile;hb=HEAD" || error_exit -wget --no-check-certificate -O puppet-devcloudinitial/init.pp "https://git-wip-us.apache.org/repos/asf?p=incubator-cloudstack.git;a=blob_plain;f=tools/devcloud/basebuild/puppet-devcloudinitial/init.pp;hb=HEAD" || error_exit -wget --no-check-certificate -O puppet-devcloudinitial/Modulefile "https://git-wip-us.apache.org/repos/asf?p=incubator-cloudstack.git;a=blob_plain;f=tools/devcloud/basebuild/puppet-devcloudinitial/Modulefile;hb=HEAD" || error_exit -wget --no-check-certificate -O puppet-devcloudinitial/files/grub "https://git-wip-us.apache.org/repos/asf?p=incubator-cloudstack.git;a=blob_plain;f=tools/devcloud/basebuild/puppet-devcloudinitial/files/grub;hb=HEAD" || error_exit -wget --no-check-certificate -O puppet-devcloudinitial/files/interfaces "https://git-wip-us.apache.org/repos/asf?p=incubator-cloudstack.git;a=blob_plain;f=tools/devcloud/basebuild/puppet-devcloudinitial/files/interfaces;hb=HEAD" || error_exit -wget --no-check-certificate -O puppet-devcloudinitial/files/network.conf "https://git-wip-us.apache.org/repos/asf?p=incubator-cloudstack.git;a=blob_plain;f=tools/devcloud/basebuild/puppet-devcloudinitial/files/network.conf;hb=HEAD" || error_exit -wget --no-check-certificate -O puppet-devcloudinitial/files/xen-defaults "https://git-wip-us.apache.org/repos/asf?p=incubator-cloudstack.git;a=blob_plain;f=tools/devcloud/basebuild/puppet-devcloudinitial/files/xen-defaults;hb=HEAD" || error_exit -wget --no-check-certificate -O puppet-devcloudinitial/files/xend "https://git-wip-us.apache.org/repos/asf?p=incubator-cloudstack.git;a=blob_plain;f=tools/devcloud/basebuild/puppet-devcloudinitial/files/xend;hb=HEAD" || error_exit -wget --no-check-certificate -O puppet-devcloudinitial/manifests/init.pp "https://git-wip-us.apache.org/repos/asf?p=incubator-cloudstack.git;a=blob_plain;f=tools/devcloud/basebuild/puppet-devcloudinitial/manifests/init.pp;hb=HEAD" || error_exit -cd ~/builddevcloud/vagrant/ -bundle install || error_exit -rake install || error_exit -cd ~/builddevcloud/vagrant/devcloudbase/ -bundle exec vagrant up || error_exit "vagrant up failed" -bundle exec vagrant halt || error_exit "vagrant halt failed" -bundle exec vagrant package default --output ~/devcloud.box || error_exit "vagrant package failed" -bundle exec vagrant destroy -f || error_exit "vagrant destroy failed" -bundle exec vagrant box remove devcloudbase virtualbox || error_exit "vagrant box remove failed" - -echo "Your new devcloud base box is stored in ~/devcloud.box" diff --git a/tools/devcloud/devcloud.cfg b/tools/devcloud/devcloud.cfg index d0ea32c36aa..8d296eb7b98 100644 --- a/tools/devcloud/devcloud.cfg +++ b/tools/devcloud/devcloud.cfg @@ -80,36 +80,6 @@ "file": "/tmp/testcase.log" } ], - "globalConfig": [ - { - "name": "expunge.workers", - "value": "3" - }, - { - "name": "expunge.delay", - "value": "60" - }, - { - "name": "expunge.interval", - "value": "60" - }, - { - "name":"enable.ec2.api", - "value":"true" - }, - { - "name":"system.vm.use.local.storage", - "value":"true" - }, - { - "name":"enable.s3.api", - "value":"true" - }, - { - "name":"host", - "value":"192.168.56.1" - } - ], "mgtSvr": [ { "mgtSvrIp": "127.0.0.1", diff --git a/tools/devcloud/devcloud.sql b/tools/devcloud/devcloud.sql index 6bcbcf7e6c5..cebf5a3702e 100644 --- a/tools/devcloud/devcloud.sql +++ b/tools/devcloud/devcloud.sql @@ -26,6 +26,14 @@ INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','cons INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','ssvm.ram.size','100'); INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','ssvm.cpu.mhz','100'); INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'system.vm.use.local.storage', 'true'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'expunge.workers', '3'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'expunge.delay', '60'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'expunge.interval', '60'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'enable.ec2.api', 'true'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'enable.s3.api', 'true'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'host', '192.168.56.1'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'management.network.cidr', '192.168.56.0/24'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'secstorage.allowed.internal.sites', '192.168.56.0/8'); UPDATE `cloud`.`configuration` SET value='10' where name = 'storage.overprovisioning.factor'; UPDATE `cloud`.`configuration` SET value='10' where name = 'cpu.overprovisioning.factor'; UPDATE `cloud`.`configuration` SET value='10' where name = 'mem.overprovisioning.factor'; diff --git a/tools/devcloud/devcloudbox/puppet-devcloud/manifests/init.pp b/tools/devcloud/devcloudbox/puppet-devcloud/manifests/init.pp deleted file mode 100644 index 3dc74a18206..00000000000 --- a/tools/devcloud/devcloudbox/puppet-devcloud/manifests/init.pp +++ /dev/null @@ -1,348 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -class puppet-devcloud { - - package { 'ebtables': - ensure => latest, - } - - service { 'ebtables': - require => Package['ebtables'], - ensure => 'running', - enable => 'true', - } - - package { 'iptables': - ensure => latest, - } - - file { '/etc/iptables.save': - require => Package['iptables'], - ensure => 'file', - source => 'puppet:///modules/puppet-devcloud/iptables.save', - group => '0', - mode => '644', - owner => '0', - } - - file { '/tmp/configebtables.sh': - ensure => 'file', - source => 'puppet:///modules/puppet-devcloud/configebtables.sh', - group => '0', - mode => '777', - owner => '0', - } - - exec { "/tmp/configebtables.sh": - require => [ - File['/tmp/configebtables.sh'], - Service['ebtables'] - ], - subscribe => Package['ebtables'], - refreshonly => true, - cwd => '/', - path => '/sbin/:/usr/bin/:/bin', - } - - package { 'nfs-server': - ensure => latest, - } - - file { '/opt/storage': - ensure => 'directory', - group => '0', - mode => '755', - owner => '0', - } - - file { '/opt/storage/secondary': - ensure => 'directory', - group => '0', - mode => '755', - owner => '0', - } - - file { '/opt/storage/secondary/template': - ensure => 'directory', - group => '0', - mode => '755', - owner => '0', - } - - file { '/opt/storage/secondary/template/tmpl': - ensure => 'directory', - group => '0', - mode => '755', - owner => '0', - } - - file { '/opt/storage/secondary/template/tmpl/1': - ensure => 'directory', - group => '0', - mode => '755', - owner => '0', - } - - file { '/opt/storage/secondary/template/tmpl/1/1': - ensure => 'directory', - group => '0', - mode => '755', - owner => '0', - } - - file { '/opt/storage/secondary/template/tmpl/1/5': - ensure => 'directory', - group => '0', - mode => '755', - owner => '0', - } - - file { '/etc/exports': - require => Package['nfs-server'], - ensure => 'file', - source => 'puppet:///modules/puppet-devcloud/exports', - mode => '644', - owner => '0', - group => '0', - } - - service { 'nfs-kernel-server': - require => Package['nfs-server'], - ensure => 'running', - enable => 'true', - } - -# TODO - it would be great to have an MD5 sum to check for each of these downloads, so that the files can be re-downloaded if they have been changed. - - exec { '/usr/bin/wget http://download.cloud.com/templates/devcloud/defaulttemplates/1/dc68eb4c-228c-4a78-84fa-b80ae178fbfd.vhd -P /opt/storage/secondary/template/tmpl/1/1/': - creates => '/opt/storage/secondary/template/tmpl/1/1/dc68eb4c-228c-4a78-84fa-b80ae178fbfd.vhd', - require => File['/opt/storage/secondary/template/tmpl/1/1/'], - timeout => '0', - } - - exec { '/usr/bin/wget http://download.cloud.com/templates/devcloud/defaulttemplates/1/template.properties -P /opt/storage/secondary/template/tmpl/1/1/': - creates => '/opt/storage/secondary/template/tmpl/1/1/template.properties', - require => File['/opt/storage/secondary/template/tmpl/1/1/'], - } - - exec { '/usr/bin/wget http://download.cloud.com/templates/devcloud/defaulttemplates/5/ce5b212e-215a-3461-94fb-814a635b2215.vhd -P /opt/storage/secondary/template/tmpl/1/5/': - creates => '/opt/storage/secondary/template/tmpl/1/5/ce5b212e-215a-3461-94fb-814a635b2215.vhd', - require => File['/opt/storage/secondary/template/tmpl/1/5/'], - timeout => '0', - } - - exec { '/usr/bin/wget http://download.cloud.com/templates/devcloud/defaulttemplates/5/template.properties -P /opt/storage/secondary/template/tmpl/1/5/': - creates => '/opt/storage/secondary/template/tmpl/1/5/template.properties', - require => File['/opt/storage/secondary/template/tmpl/1/5/'], - } - - exec { 'getecho': - command => '/usr/bin/wget http://download.cloud.com/templates/devcloud/echo -P /usr/lib/xcp/plugins/', - creates => '/usr/lib/xcp/plugins/echo', - } - - exec { '/bin/chmod -R 777 /usr/lib/xcp': - require => Exec['getecho'], - } - - file { '/opt/storage/primary': - ensure => 'directory', - group => '0', - mode => '755', - owner => '0', - } - - file { '/tmp/configlocalstorage.sh': - ensure => 'file', - group => '0', - mode => '777', - owner => '0', - source => 'puppet:///modules/puppet-devcloud/configlocalstorage.sh', - } - - exec { "configlocal": - require => [ - File['/opt/storage/primary'], - File['/tmp/configlocalstorage.sh'] - ], - command => '/tmp/configlocalstorage.sh', - cwd => '/', - } - - file { '/tmp/configvnc.sh': - ensure => 'file', - source => 'puppet:///modules/puppet-devcloud/configvnc.sh', - mode => '777', - group => '0', - owner => '0', - } - - exec { "configvnc": - require => File['/tmp/configvnc.sh'], - command => '/tmp/configvnc.sh', - cwd => '/', - } - - package { 'git': - ensure => latest, - } - - package { 'unzip': - ensure => latest, - } - - package { 'mysql-server': - ensure => latest, - } - - package { 'ant': - ensure => latest, - } - - package { 'openjdk-6-jdk': - ensure => latest, - } - - file { '/opt/cloudstack': - ensure => 'directory', - group => '0', - mode => '755', - owner => '0', - } - - file { '/tmp/updatecode.sh': - ensure => 'file', - source => 'puppet:///modules/puppet-devcloud/updatecode.sh', - mode => '777', - owner => '0', - group => '0', - } - - exec { 'get_code': - require => [ - Package['git'], - File['/opt/cloudstack/'], - File['/tmp/updatecode.sh'] - ], - command => '/tmp/updatecode.sh', - cwd => '/opt/cloudstack/', - timeout => '0', - } - - file { '/opt/cloudstack/incubator-cloudstack/target': - ensure => 'directory', - group => '0', - mode => '755', - owner => '0', - require => Exec['get_code'], - } - - file { '/opt/cloudstack/incubator-cloudstack/dist': - ensure => 'directory', - group => '0', - mode => '755', - owner => '0', - require => Exec['get_code'], - } - - exec { 'downloadtomcat': - command => '/usr/bin/wget http://archive.apache.org/dist/tomcat/tomcat-6/v6.0.32/bin/apache-tomcat-6.0.32.zip -P /opt/cloudstack/', - creates => '/opt/cloudstack/apache-tomcat-6.0.32.zip', - require => File['/opt/cloudstack/'], - timeout => '0', - } - - exec { "unziptomcat": - require => [ - Package['unzip'], - Exec["downloadtomcat"] - ], - creates => "/opt/cloudstack/apache-tomcat-6.0.32", - command => "/usr/bin/unzip apache-tomcat-6.0.32.zip", - cwd => "/opt/cloudstack", - timeout => '0', - } - - exec { "catalina_home": - require => Exec["unziptomcat"], - unless => '/bin/grep CATALINA_HOME /root/.bashrc', - command => '/bin/echo "export CATALINA_HOME=/opt/cloudstack/apache-tomcat-6.0.32" >> /root/.bashrc', - cwd => '/', - } - - package { 'mkisofs': - ensure => latest, - } - - file { '/opt/cloudstack/buildcloudstack.sh': - ensure => 'file', - source => 'puppet:///modules/puppet-devcloud/builddevcloud.sh', - mode => '777', - owner => '0', - group => '0', - } - - file { '/opt/cloudstack/installmaven.sh': - ensure => 'file', - source => 'puppet:///modules/puppet-devcloud/installmaven.sh', - mode => '777', - owner => '0', - group => '0', - } - - exec { "install_maven": - require => File['/opt/cloudstack/installmaven.sh'], - command => '/opt/cloudstack/installmaven.sh', - cwd => '/opt/cloudstack', - creates => '/opt/cloudstack/apache-maven-3.0.4/', - timeout => '0', - } - - exec { "build_cloudstack": - require => [ - Package['ant'], - Exec['install_maven'], - Exec["catalina_home"], - File['/opt/cloudstack/incubator-cloudstack/dist'], - File['/opt/cloudstack/incubator-cloudstack/target'], - Package['mkisofs'], - File['/opt/cloudstack/buildcloudstack.sh'] - ], - command => "/opt/cloudstack/buildcloudstack.sh", - cwd => "/opt/cloudstack/", - timeout => '0', - } - - file { '/opt/cloudstack/startdevcloud.sh': - ensure => 'file', - source => 'puppet:///modules/puppet-devcloud/startdevcloud.sh', - mode => '777', - owner => '0', - group => '0', - } - - exec { "start_cloudstack": - require => [ - Exec["build_cloudstack"], - File["/opt/cloudstack/startdevcloud.sh"] - ], - command => "/opt/cloudstack/startdevcloud.sh", - cwd => "/opt/cloudstack/", - } - -} diff --git a/tools/devcloud/devcloudsetup.sh b/tools/devcloud/devcloudsetup.sh deleted file mode 100644 index f8b69faa92e..00000000000 --- a/tools/devcloud/devcloudsetup.sh +++ /dev/null @@ -1,151 +0,0 @@ -#!/bin/bash -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -fileSvr="http://download.cloud.com/templates/devcloud/" -install_xen() { - aptitude update - echo "install xen" - aptitude -y install linux-headers-3.2.0-23-generic-pae - aptitude -y install xen-hypervisor-4.1-i386 xcp-xapi - echo "configure xen" - - sed -i -e 's/xend_start$/#xend_start/' -e 's/xend_stop$/#xend_stop/' /etc/init.d/xend - update-rc.d xendomains disable - - sed -i 's/GRUB_DEFAULT=.\+/GRUB_DEFAULT="Xen 4.1-i386"/' /etc/default/grub - echo 'GRUB_CMDLINE_XEN_DEFAULT="dom0_mem=512M,max:512M"' | cat /etc/default/grub - >> /etc/default/newgrub - mv /etc/default/newgrub /etc/default/grub - update-grub - - mkdir /usr/share/qemu - ln -s /usr/share/qemu-linaro/keymaps /usr/share/qemu/keymaps - -cat > /etc/network/interfaces << EOF -# The loopback network interface -auto lo -iface lo inet loopback - -# The primary network interface -auto xenbr0 -iface xenbr0 inet dhcp - gateway 10.0.2.2 - bridge_ports eth0 - - -auto eth0 -iface eth0 inet dhcp -pre-up iptables-save < /etc/iptables.save -pre-up /etc/init.d/ebtables load -EOF - - echo TOOLSTACK=xapi > /etc/default/xen - echo bridge > /etc/xcp/network.conf - - echo "set root password" - echo "root:password" | chpasswd - - echo "reboot" - reboot -} - -postsetup() { - #check xen dom0 is working - xe host-list > /dev/null - if [ $? -gt 0 ]; then - print "xen dom0 is not running, make sure dom0 is installed" - exit 1 - fi - - #disable virtualbox dhcp server for Vms created by cloudstack - apt-get install ebtables - iptables -A POSTROUTING -t mangle -p udp --dport bootpc -j CHECKSUM --checksum-fill - mac=`ifconfig xenbr0 |grep HWaddr |awk '{print $5}'` - ebtables -I FORWARD -d ! $mac -i eth0 -p IPV4 --ip-prot udp --ip-dport 67:68 -j DROP - iptables-save > /etc/iptables.save - /etc/init.d/ebtables save - - echo "configure NFS server" - aptitude -y install nfs-server - if [ ! -d /opt/storage/secondary ];then - mkdir -p /opt/storage/secondary - mkdir -p /opt/storage/secondary/template/tmpl/1/1 - mkdir -p /opt/storage/secondary/template/tmpl/1/5 - - echo "/opt/storage/secondary *(rw,no_subtree_check,no_root_squash,fsid=0)" > /etc/exports - wget $fileSvr/defaulttemplates/1/dc68eb4c-228c-4a78-84fa-b80ae178fbfd.vhd -P /opt/storage/secondary/template/tmpl/1/1/ - wget $fileSvr/defaulttemplates/1/template.properties -P /opt/storage/secondary/template/tmpl/1/1/ - wget $fileSvr/defaulttemplates/5/ce5b212e-215a-3461-94fb-814a635b2215.vhd -P /opt/storage/secondary/template/tmpl/1/5/ - wget $fileSvr/defaulttemplates/5/template.properties -P /opt/storage/secondary/template/tmpl/1/5/ - /etc/init.d/nfs-kernel-server restart - fi - - echo "configure local storage" - if [ ! -d /opt/storage/primary ]; then - mkdir -p /opt/storage/primary - hostuuid=`xe host-list |grep uuid|awk '{print $5}'` - xe sr-create host-uuid=$hostuuid name-label=local-storage shared=false type=file device-config:location=/opt/storage/primary - fi - - echo "generate ssh key" - ssh-keygen -A -q - - echo "configure xcp" - wget $fileSvr/echo -P /usr/lib/xcp/plugins/ - chmod -R 777 /usr/lib/xcp - - sed -i 's/VNCTERM_LISTEN=.\+/VNCTERM_LISTEN="-v 0.0.0.0:1"/' /usr/lib/xcp/lib/vncterm-wrapper - - echo "install cloudstack " - - if [ ! -d /opt/cloudstack ];then - aptitude -y install git unzip openjdk-6-jdk mysql-server ant - mkdir /opt/cloudstack - cd /opt/cloudstack - git clone https://git-wip-us.apache.org/repos/asf/incubator-cloudstack.git - mkdir incubator-cloudstack/target - mkdir incubator-cloudstack/dist - wget http://archive.apache.org/dist/tomcat/tomcat-6/v6.0.32/bin/apache-tomcat-6.0.32.zip -P /opt/cloudstack/ - unzip apache-tomcat-6.0.32.zip - echo "export CATALINA_HOME=/opt/cloudstack/apache-tomcat-6.0.32" >> /root/.bashrc - cd ~ - fi - - echo "devCloud is ready to use" -} -usage() { - print "$0 -p: presetup enviroment, e.g. install xen, configure xcp etc" - print "$0 -P: postsetup, install cloudstack, prepare template etc" -} - -while getopts "pP" OPTION -do - case $OPTION in - p) - install_xen - exit 0 - ;; - P) - postsetup - exit 0 - ;; - ?) - usage - exit - ;; - esac -done diff --git a/tools/devcloud/src/.rvmrc b/tools/devcloud/src/.rvmrc new file mode 100644 index 00000000000..7e51d62af9f --- /dev/null +++ b/tools/devcloud/src/.rvmrc @@ -0,0 +1,24 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +rvm use ruby-1.9.3@vagrant-xen-cloudstack --create +export VAGRANT_HOME=$HOME/.vagrant.d-xen-cloudstack +bundle check > /dev/null 2>&1 +RETVAL=$? +if [ $RETVAL -ne 0 ]; then + bundle install +fi diff --git a/tools/devcloud/basebuild/puppet-devcloudinitial/files/interfaces b/tools/devcloud/src/Gemfile similarity index 73% rename from tools/devcloud/basebuild/puppet-devcloudinitial/files/interfaces rename to tools/devcloud/src/Gemfile index f65507911ab..2790c4a52a0 100644 --- a/tools/devcloud/basebuild/puppet-devcloudinitial/files/interfaces +++ b/tools/devcloud/src/Gemfile @@ -5,9 +5,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -15,19 +15,5 @@ # specific language governing permissions and limitations # under the License. -# The loopback network interface -auto lo -iface lo inet loopback - -# The primary network interface -auto xenbr0 -iface xenbr0 inet dhcp - gateway 10.0.2.2 - bridge_ports eth0 - - -auto eth0 -iface eth0 inet dhcp -pre-up iptables-save < /etc/iptables.save -pre-up /etc/init.d/ebtables load - +source 'https://rubygems.org' +gem 'vagrant', :git => 'https://github.com/chipchilders/vagrant' diff --git a/tools/devcloud/devcloudbox/Vagrantfile b/tools/devcloud/src/Vagrantfile similarity index 57% rename from tools/devcloud/devcloudbox/Vagrantfile rename to tools/devcloud/src/Vagrantfile index 121a9f58a94..3f0d9045bb6 100644 --- a/tools/devcloud/devcloudbox/Vagrantfile +++ b/tools/devcloud/src/Vagrantfile @@ -8,9 +8,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -19,33 +19,40 @@ # under the License. Vagrant::Config.run do |config| - config.vm.box = "devcloud" - # TODO: Get a URL to host the base image - # config.vm.box_url = "http://domain.com/path/to/above.box" + config.vm.network :hostonly, "192.168.56.10", :auto_config => false + #config.vm.box = "devcloud" + config.vm.box = "devcloudbase-xen" + #config.vm.box_url = "http://basho-cloudstack.s3.amazonaws.com/devcloud.box" + config.vm.guest = :xen config.ssh.username = "devcloud" - - # Uncomment this line to enable the console for debugging the + config.vm.host_name = "devcloud.local" + # Uncomment this line to enable the console for debugging the # build process. # config.vm.boot_mode = :gui # Setup port forwarding - config.vm.forward_port 22, 2222 + config.vm.forward_port 22, 7222 + config.vm.forward_port 3306, 3306 config.vm.forward_port 8080, 8080 config.vm.forward_port 8443, 8443 config.vm.forward_port 5901, 5901 config.vm.forward_port 8787, 8787 config.vm.forward_port 8250, 8250 - + config.vm.forward_port 8096, 8096 + config.vm.forward_port 7080, 7080 # Ensure the VM has the right virtual resources #config.vm. - + config.vm.customize ["modifyvm", :id, "--memory", 2048] + config.vm.customize ["modifyvm", :id, "--nicpromisc2", "allow-all"] + config.vm.provision :shell, :path => "waitforxe.sh" config.vm.provision :puppet do |puppet| - puppet.manifests_path = "puppet-devcloud" - puppet.manifest_file = "init.pp" - puppet.with_ssh = true - puppet.pp_path = "/etc/puppet" - puppet.module_path = "puppet-devcloud" + puppet.with_ssh = true + puppet.manifests_path = File.join 'puppet', 'manifests' + puppet.module_path = File.join 'puppet', 'modules', 'devcloud' + puppet.manifest_file = 'vagrant-devcloud.pp' + puppet.options = ['--pluginsync', '--trace', '--debug', '--verbose'] end + end diff --git a/tools/devcloud/src/boxit.sh b/tools/devcloud/src/boxit.sh new file mode 100755 index 00000000000..dae53cee6bc --- /dev/null +++ b/tools/devcloud/src/boxit.sh @@ -0,0 +1,21 @@ +#! /bin/bash -ex +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +vagrant halt +vagrant package default --output devcloud.box +vagrant box add devcloud devcloud.box -f diff --git a/tools/devcloud/src/deps/boxer.sh b/tools/devcloud/src/deps/boxer.sh new file mode 100755 index 00000000000..72d9cd1e6f3 --- /dev/null +++ b/tools/devcloud/src/deps/boxer.sh @@ -0,0 +1,184 @@ +#! /bin/bash +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Load RVM into a shell session *as a function* +if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then +# First try to load from a user install + source "$HOME/.rvm/scripts/rvm" +elif [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then +# Then try to load from a root install + source "/usr/local/rvm/scripts/rvm" +else + printf "ERROR: An RVM installation was not found.\n" +fi + +BASEDIR=$PWD/boxes +DEVCLOUD_BASEBUILD_DIR=$BASEDIR/basebox-build +echo $DEVCLOUD_BASEBUILD_DIR +DEVCLOUD_XEN_BASEBUILD_DIR=$BASEDIR/xenbox-build +DEVCLOUD_BASE_NAME='devcloudbase' +DEVCLOUD_XEN_BASE_NAME='devcloudbase-xen' +OS='ubuntu-12.04.1-server-i386' + + +basebox() { + set +x + rvm rvmrc trust $DEVCLOUD_BASEBUILD_DIR/ + case "$1" in + build) + cd $DEVCLOUD_BASEBUILD_DIR/ + set -ex + vagrant basebox define $DEVCLOUD_BASE_NAME $OS + cp definition.rb postinstall.sh preseed.cfg definitions/$DEVCLOUD_BASE_NAME/ + vagrant basebox build $DEVCLOUD_BASE_NAME -f -a -n -r + vagrant basebox export $DEVCLOUD_BASE_NAME -f + set +ex + cd $DEVCLOUD_XEN_BASEBUILD_DIR + set -ex + vagrant box add $DEVCLOUD_BASE_NAME $DEVCLOUD_BASEBUILD_DIR/${DEVCLOUD_BASE_NAME}.box -f + ;; + clean) + cd $DEVCLOUD_BASEBUILD_DIR/ + set -x + rm -f iso/*.iso + vagrant -f basebox destroy $DEVCLOUD_BASE_NAME #-f + vagrant basebox undefine $DEVCLOUD_BASE_NAME + #hackery to inherit the proper rvmrc for the hacked vagrant + set +x + cd $BAS$DEVCLOUD_XEN_BASEBUILD_DIR + set -x + vagrant -f box remove $DEVCLOUD_BASE_NAME virtualbox + set +x + cd $DEVCLOUD_BASEBUILD_DIR + set -x + rm -f ${DEVCLOUD_BASE_NAME}.box + set +x + cd $BASEDIR + #rvm --force gemset delete vagrant-release-cloudstack + ;; + esac +} + +xenbox() { + + set +x + rvm rvmrc trust $DEVCLOUD_XEN_BASEBUILD_DIR/ + case "$1" in + build) + cd $DEVCLOUD_XEN_BASEBUILD_DIR + + #adding it here because it needs to be added into the $VAGRANT_HOME of + #the hacked vagrant + set -ex + vagrant up + vagrant halt + vagrant package default --output ${DEVCLOUD_XEN_BASE_NAME}.box + vagrant box add $DEVCLOUD_XEN_BASE_NAME ${DEVCLOUD_XEN_BASE_NAME}.box -f + ;; + clean) + cd $DEVCLOUD_XEN_BASEBUILD_DIR + set -x + vagrant -f box remove $DEVCLOUD_XEN_BASE_NAME virtualbox + vagrant destroy -f + rm -f ${DEVCLOUD_XEN_BASE_NAME}.box + set +x + #rvm --force gemset delete vagrant-xen-cloudstack + set -x + ;; + esac +} +usage() { + +cat <&2 + echo "$usage" >&2 + exit 1 + ;; + esac +done +shift $((OPTIND - 1)) + +posargs=$@ + +#removes duplicate positionals + +posargs=$(echo "$posargs" | tr ' ' '\n' | nl | sort -u -k2 | sort -n | cut -f2-) + + + +for arg in $posargs; do + + case "$arg" in + basebox) + true + ;; + xenbox) + true + ;; + all) + true + ;; + *) + usage + exit 1 + ;; + esac + +done + +cd $BASEDIR + +for arg in $posargs; do + case "$1" in + "all") + case "$action" in + clean) + xenbox $action + basebox $action + ;; + build) + basebox $action + xenbox $action + ;; + esac + ;; + $arg) + $arg $action + ;; + esac +done diff --git a/tools/devcloud/src/deps/boxes/basebox-build/.rvmrc b/tools/devcloud/src/deps/boxes/basebox-build/.rvmrc new file mode 100644 index 00000000000..3c8c66c97f9 --- /dev/null +++ b/tools/devcloud/src/deps/boxes/basebox-build/.rvmrc @@ -0,0 +1,24 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +rvm use ruby-1.9.3@vagrant-release-cloudstack --create +export VAGRANT_HOME=$HOME/.vagrant.d-release-cloudstack +bundle check > /dev/null 2>&1 +RETVAL=$? +if [ $RETVAL -ne 0 ]; then + bundle install +fi diff --git a/tools/devcloud/src/deps/boxes/basebox-build/Gemfile b/tools/devcloud/src/deps/boxes/basebox-build/Gemfile new file mode 100644 index 00000000000..dae53be6dd0 --- /dev/null +++ b/tools/devcloud/src/deps/boxes/basebox-build/Gemfile @@ -0,0 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +source 'https://rubygems.org' +gem 'veewee', :git => 'https://github.com/jedi4ever/veewee.git' +gem 'em-winrm' diff --git a/tools/devcloud/devcloudbox/puppet-devcloud/init.pp b/tools/devcloud/src/deps/boxes/basebox-build/Vagrantfile similarity index 96% rename from tools/devcloud/devcloudbox/puppet-devcloud/init.pp rename to tools/devcloud/src/deps/boxes/basebox-build/Vagrantfile index 2574392251a..245692337bc 100644 --- a/tools/devcloud/devcloudbox/puppet-devcloud/init.pp +++ b/tools/devcloud/src/deps/boxes/basebox-build/Vagrantfile @@ -5,9 +5,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -15,4 +15,3 @@ # specific language governing permissions and limitations # under the License. -include puppet-devcloud diff --git a/tools/devcloud/veewee/definition.rb b/tools/devcloud/src/deps/boxes/basebox-build/definition.rb similarity index 93% rename from tools/devcloud/veewee/definition.rb rename to tools/devcloud/src/deps/boxes/basebox-build/definition.rb index cb0a9079520..24668421c5d 100644 --- a/tools/devcloud/veewee/definition.rb +++ b/tools/devcloud/src/deps/boxes/basebox-build/definition.rb @@ -5,9 +5,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -15,7 +15,6 @@ # specific language governing permissions and limitations # under the License. - Veewee::Session.declare({ :cpu_count => '1', :memory_size=> '2048', @@ -28,9 +27,13 @@ Veewee::Session.declare({ :iso_md5 => '32184a83c8b5e6031e1264e5c499bc03', :iso_download_timeout => "1000", :boot_wait => "4", - :ioapic => "on", - :nestedpaging => "on", - :hwvirtex => "on", + :virtualbox => { + :vm_options => [ + "ioapic" => "on", + "hwvirtex" => "on", + "nestedpaging" => "on" + ] + }, :boot_cmd_sequence => [ '', '/install/vmlinuz noapic preseed/url=http://%IP%:%PORT%/preseed.cfg ', diff --git a/tools/devcloud/veewee/postinstall.sh b/tools/devcloud/src/deps/boxes/basebox-build/postinstall.sh similarity index 99% rename from tools/devcloud/veewee/postinstall.sh rename to tools/devcloud/src/deps/boxes/basebox-build/postinstall.sh index aeafafef17d..217d23024aa 100644 --- a/tools/devcloud/veewee/postinstall.sh +++ b/tools/devcloud/src/deps/boxes/basebox-build/postinstall.sh @@ -5,9 +5,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -40,4 +40,3 @@ chown -R devcloud /home/devcloud/.ssh # Zero out the free space to save space in the final image: dd if=/dev/zero of=/EMPTY bs=1M rm -f /EMPTY - diff --git a/tools/devcloud/veewee/preseed.cfg b/tools/devcloud/src/deps/boxes/basebox-build/preseed.cfg similarity index 99% rename from tools/devcloud/veewee/preseed.cfg rename to tools/devcloud/src/deps/boxes/basebox-build/preseed.cfg index 4a97171e76f..00bae613647 100644 --- a/tools/devcloud/veewee/preseed.cfg +++ b/tools/devcloud/src/deps/boxes/basebox-build/preseed.cfg @@ -5,9 +5,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/tools/devcloud/src/deps/boxes/xenbox-build/.rvmrc b/tools/devcloud/src/deps/boxes/xenbox-build/.rvmrc new file mode 100644 index 00000000000..7e51d62af9f --- /dev/null +++ b/tools/devcloud/src/deps/boxes/xenbox-build/.rvmrc @@ -0,0 +1,24 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +rvm use ruby-1.9.3@vagrant-xen-cloudstack --create +export VAGRANT_HOME=$HOME/.vagrant.d-xen-cloudstack +bundle check > /dev/null 2>&1 +RETVAL=$? +if [ $RETVAL -ne 0 ]; then + bundle install +fi diff --git a/tools/devcloud/src/deps/boxes/xenbox-build/Gemfile b/tools/devcloud/src/deps/boxes/xenbox-build/Gemfile new file mode 100644 index 00000000000..2790c4a52a0 --- /dev/null +++ b/tools/devcloud/src/deps/boxes/xenbox-build/Gemfile @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +source 'https://rubygems.org' +gem 'vagrant', :git => 'https://github.com/chipchilders/vagrant' diff --git a/tools/devcloud/src/deps/boxes/xenbox-build/Vagrantfile b/tools/devcloud/src/deps/boxes/xenbox-build/Vagrantfile new file mode 100644 index 00000000000..58e9e64a1d0 --- /dev/null +++ b/tools/devcloud/src/deps/boxes/xenbox-build/Vagrantfile @@ -0,0 +1,52 @@ + # -*- mode: ruby -*- +# vi: set ft=ruby : + +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +Vagrant::Config.run do |config| + config.vm.box = "devcloudbase" + # TODO: Get a URL to host the base image + # config.vm.box_url = "http://domain.com/path/to/above.box" + config.vm.guest = :xen + config.ssh.username = "devcloud" + config.vm.host_name = "devcloud.local" + + # Uncomment this line to enable the console for debugging the + # build process. + #config.vm.boot_mode = :gui + + # Setup port forwarding + # config.vm.forward_port 22, 2222 + # config.vm.forward_port 8080, 8080 + # config.vm.forward_port 8443, 8443 + # config.vm.forward_port 5901, 5901 + # config.vm.forward_port 8787, 8787 + # config.vm.forward_port 8250, 8250 + + # Ensure the VM has the right virtual resources + #config.vm. + + config.vm.provision :puppet do |puppet| + puppet.with_ssh = true + puppet.manifests_path = File.join 'puppet', 'manifests' + puppet.module_path = File.join 'puppet', 'modules', 'devcloudinitial' + puppet.manifest_file = 'vagrant-devcloudinitial.pp' + puppet.options = ['--trace', '--debug', '--verbose'] + end + +end diff --git a/tools/devcloud/src/deps/boxes/xenbox-build/puppet/manifests/site.pp b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/manifests/site.pp new file mode 100644 index 00000000000..13a83393a91 --- /dev/null +++ b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/manifests/site.pp @@ -0,0 +1,16 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. diff --git a/tools/devcloud/src/deps/boxes/xenbox-build/puppet/manifests/vagrant-devcloudinitial.pp b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/manifests/vagrant-devcloudinitial.pp new file mode 100644 index 00000000000..0d48071536a --- /dev/null +++ b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/manifests/vagrant-devcloudinitial.pp @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permission s and limitations +# under the License. + +node default { include devcloudinitial } diff --git a/tools/devcloud/basebuild/puppet-devcloudinitial/Modulefile b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/Modulefile similarity index 100% rename from tools/devcloud/basebuild/puppet-devcloudinitial/Modulefile rename to tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/Modulefile diff --git a/tools/devcloud/basebuild/puppet-devcloudinitial/files/grub b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/grub similarity index 99% rename from tools/devcloud/basebuild/puppet-devcloudinitial/files/grub rename to tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/grub index be14e82f7c5..d5de16c536b 100644 --- a/tools/devcloud/basebuild/puppet-devcloudinitial/files/grub +++ b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/grub @@ -5,9 +5,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/interfaces b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/interfaces new file mode 100644 index 00000000000..0c197209d10 --- /dev/null +++ b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/interfaces @@ -0,0 +1,45 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +auto lo +iface lo inet loopback + +auto eth0 +iface eth0 inet manual + +allow-hotplug eth1 +iface eth1 inet manual + +auto xenbr0 +iface xenbr0 inet dhcp + bridge_ports eth0 + dns_nameservers 8.8.8.8 8.8.4.4 + post-up route add default gw 10.0.2.2 + +auto xenbr1 +iface xenbr1 inet static + bridge_ports eth1 + address 192.168.56.10 + netmask 255.255.255.0 + network 192.168.56.0 + broadcast 192.168.56.255 + gateway 192.168.56.1 + dns_nameservers 8.8.8.8 8.8.4.4 + post-up route del default gw 192.168.56.1; route add default gw 192.168.56.1 metric 100; + + +pre-up iptables-save < /etc/iptables.save +pre-up /etc/init.d/ebtables load diff --git a/tools/devcloud/devcloudbox/puppet-devcloud/files/iptables.save b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/iptables.save similarity index 99% rename from tools/devcloud/devcloudbox/puppet-devcloud/files/iptables.save rename to tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/iptables.save index 333932723dc..07647f83bad 100644 --- a/tools/devcloud/devcloudbox/puppet-devcloud/files/iptables.save +++ b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/iptables.save @@ -5,9 +5,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/tools/devcloud/basebuild/puppet-devcloudinitial/files/xen-defaults b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/xen-defaults similarity index 99% rename from tools/devcloud/basebuild/puppet-devcloudinitial/files/xen-defaults rename to tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/xen-defaults index bc3dc67b522..908396812fb 100644 --- a/tools/devcloud/basebuild/puppet-devcloudinitial/files/xen-defaults +++ b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/xen-defaults @@ -5,9 +5,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/tools/devcloud/basebuild/puppet-devcloudinitial/files/xend b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/xend similarity index 99% rename from tools/devcloud/basebuild/puppet-devcloudinitial/files/xend rename to tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/xend index 19ebd49e226..4a532992f94 100644 --- a/tools/devcloud/basebuild/puppet-devcloudinitial/files/xend +++ b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/files/xend @@ -6,9 +6,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/manifests/init.pp b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/manifests/init.pp new file mode 100644 index 00000000000..e1f4c5ac271 --- /dev/null +++ b/tools/devcloud/src/deps/boxes/xenbox-build/puppet/modules/devcloudinitial/manifests/init.pp @@ -0,0 +1,119 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + + +class devcloudinitial { + + if $::architecture == 'x86_64'{ + $debarch='amd64' + } + else { + $debarch='i386' + } + + exec { "apt-update": + command => "/usr/bin/apt-get update" + } + + Exec["apt-update"] -> Package <| |> + + package { + "linux-headers-${::kernelrelease}": + ensure => latest; + "xen-hypervisor-4.1-${debarch}": + ensure => latest, + require => Package["linux-headers-${::kernelrelease}"]; + 'xcp-xapi': + ensure => latest, + require => Package["xen-hypervisor-4.1-${debarch}"]; + 'iptables': + ensure => latest; + 'ebtables': + ensure => latest; + } + + file { + '/etc/iptables.save': + ensure => 'file', + require => Package['iptables'], + source => 'puppet:///modules/devcloudinitial/iptables.save', + group => '0', + mode => '0644', + owner => '0'; + '/etc/xcp/network.conf': + ensure => 'file', + require => Package['xcp-xapi'], + content => "bridge", + group => '0', + mode => '0644', + owner => '0'; + '/etc/init.d/xend': + ensure => 'file', + require => Package['xcp-xapi'], + source => 'puppet:///modules/devcloudinitial/xend', + group => '0', + owner => '0', + mode => '0755'; + '/etc/default/grub': + ensure => 'file', + require => Package["xen-hypervisor-4.1-${debarch}"], + source => 'puppet:///modules/devcloudinitial/grub', + group => '0', + mode => '0644', + owner => '0'; + '/usr/share/qemu': + ensure => 'directory', + require => Package["xen-hypervisor-4.1-${debarch}"], + group => '0', + mode => '0755', + owner => '0'; + '/usr/share/qemu/keymaps': + ensure => 'link', + require => File['/usr/share/qemu'], + group => '0', + mode => '0777', + owner => '0', + target => '/usr/share/qemu-linaro/keymaps'; + '/etc/network/interfaces': + ensure => 'file', + source => 'puppet:///modules/devcloudinitial/interfaces', + group => '0', + mode => '0644', + owner => '0'; + '/etc/default/xen': + ensure => 'file', + require => Package["xen-hypervisor-4.1-${debarch}"], + source => 'puppet:///modules/devcloudinitial/xen-defaults', + group => '0', + mode => '0644', + owner => '0'; + } + + service { + 'xendomains': + ensure => 'stopped', + require => Package['xcp-xapi'], + enable => false; + } + + exec { '/usr/sbin/update-grub': + subscribe => File['/etc/default/grub'], + refreshonly => true, + cwd => '/', + } + +} diff --git a/tools/devcloud/basebuild/puppet-devcloudinitial/init.pp b/tools/devcloud/src/puppet/manifests/vagrant-devcloud.pp similarity index 95% rename from tools/devcloud/basebuild/puppet-devcloudinitial/init.pp rename to tools/devcloud/src/puppet/manifests/vagrant-devcloud.pp index 213ef597008..47b07dc6dd1 100644 --- a/tools/devcloud/basebuild/puppet-devcloudinitial/init.pp +++ b/tools/devcloud/src/puppet/manifests/vagrant-devcloud.pp @@ -5,9 +5,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -15,4 +15,4 @@ # specific language governing permissions and limitations # under the License. -include puppet-devcloudinitial +include devcloud diff --git a/tools/devcloud/devcloudbox/puppet-devcloud/Modulefile b/tools/devcloud/src/puppet/modules/devcloud/Modulefile similarity index 100% rename from tools/devcloud/devcloudbox/puppet-devcloud/Modulefile rename to tools/devcloud/src/puppet/modules/devcloud/Modulefile diff --git a/tools/devcloud/src/puppet/modules/devcloud/files/compare.sh b/tools/devcloud/src/puppet/modules/devcloud/files/compare.sh new file mode 100644 index 00000000000..e0ee95ca077 --- /dev/null +++ b/tools/devcloud/src/puppet/modules/devcloud/files/compare.sh @@ -0,0 +1,22 @@ +#! /bin/bash -eux +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +FILE=$1 +WORKING_DIR=$2 +cd $WORKING_DIR +test `grep $FILE ${WORKING_DIR}/md5sum.txt | awk '{print $1}'` == `md5sum $FILE |awk '{print $1}'` diff --git a/tools/devcloud/devcloudbox/puppet-devcloud/files/configebtables.sh b/tools/devcloud/src/puppet/modules/devcloud/files/configebtables.sh similarity index 99% rename from tools/devcloud/devcloudbox/puppet-devcloud/files/configebtables.sh rename to tools/devcloud/src/puppet/modules/devcloud/files/configebtables.sh index 741884ee665..83293336640 100644 --- a/tools/devcloud/devcloudbox/puppet-devcloud/files/configebtables.sh +++ b/tools/devcloud/src/puppet/modules/devcloud/files/configebtables.sh @@ -7,9 +7,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/tools/devcloud/devcloudbox/puppet-devcloud/files/configlocalstorage.sh b/tools/devcloud/src/puppet/modules/devcloud/files/configlocalstorage.sh similarity index 94% rename from tools/devcloud/devcloudbox/puppet-devcloud/files/configlocalstorage.sh rename to tools/devcloud/src/puppet/modules/devcloud/files/configlocalstorage.sh index ab47d2dad4f..3ed1a39dcd7 100644 --- a/tools/devcloud/devcloudbox/puppet-devcloud/files/configlocalstorage.sh +++ b/tools/devcloud/src/puppet/modules/devcloud/files/configlocalstorage.sh @@ -7,9 +7,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -19,7 +19,7 @@ /usr/bin/xe sr-list | /bin/grep local-storage rc=$? if [[ $rc != 0 ]] ; then - hostuuid=`xe host-list |grep uuid|awk '{print $5}'`; + hostuuid=`xe host-list |grep uuid|awk '{print $5}'`; xe sr-create host-uuid=$hostuuid name-label=local-storage shared=false type=file device-config:location=/opt/storage/primary fi exit 0 diff --git a/tools/devcloud/devcloudbox/puppet-devcloud/files/configvnc.sh b/tools/devcloud/src/puppet/modules/devcloud/files/configvnc.sh similarity index 99% rename from tools/devcloud/devcloudbox/puppet-devcloud/files/configvnc.sh rename to tools/devcloud/src/puppet/modules/devcloud/files/configvnc.sh index b13a7a307ab..b739dc6acb0 100644 --- a/tools/devcloud/devcloudbox/puppet-devcloud/files/configvnc.sh +++ b/tools/devcloud/src/puppet/modules/devcloud/files/configvnc.sh @@ -7,9 +7,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/tools/devcloud/devcloudbox/puppet-devcloud/files/exports b/tools/devcloud/src/puppet/modules/devcloud/files/exports similarity index 92% rename from tools/devcloud/devcloudbox/puppet-devcloud/files/exports rename to tools/devcloud/src/puppet/modules/devcloud/files/exports index c270c6306bd..1f9165011ac 100644 --- a/tools/devcloud/devcloudbox/puppet-devcloud/files/exports +++ b/tools/devcloud/src/puppet/modules/devcloud/files/exports @@ -5,9 +5,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -15,4 +15,5 @@ # specific language governing permissions and limitations # under the License. +/opt/storage/primary *(rw,no_subtree_check,no_root_squash,fsid=0) /opt/storage/secondary *(rw,no_subtree_check,no_root_squash,fsid=0) diff --git a/tools/devcloud/devcloudbox/puppet-devcloud/files/installmaven.sh b/tools/devcloud/src/puppet/modules/devcloud/files/installmaven.sh similarity index 99% rename from tools/devcloud/devcloudbox/puppet-devcloud/files/installmaven.sh rename to tools/devcloud/src/puppet/modules/devcloud/files/installmaven.sh index 48ffdfe8de7..8cd3df01c89 100644 --- a/tools/devcloud/devcloudbox/puppet-devcloud/files/installmaven.sh +++ b/tools/devcloud/src/puppet/modules/devcloud/files/installmaven.sh @@ -7,9 +7,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/tools/devcloud/devcloudbox/puppet-devcloud/files/startdevcloud.sh b/tools/devcloud/src/puppet/modules/devcloud/files/startdevcloud.sh similarity index 95% rename from tools/devcloud/devcloudbox/puppet-devcloud/files/startdevcloud.sh rename to tools/devcloud/src/puppet/modules/devcloud/files/startdevcloud.sh index f496891d40f..27a7a044851 100644 --- a/tools/devcloud/devcloudbox/puppet-devcloud/files/startdevcloud.sh +++ b/tools/devcloud/src/puppet/modules/devcloud/files/startdevcloud.sh @@ -7,9 +7,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -19,5 +19,5 @@ export CATALINA_HOME=/opt/cloudstack/apache-tomcat-6.0.32 cd /opt/cloudstack/incubator-cloudstack/ -nohup ant run > /dev/null 2>&1 & +nohup ant run > /dev/null 2>&1 & exit 0 diff --git a/tools/devcloud/devcloudbox/puppet-devcloud/files/updatecode.sh b/tools/devcloud/src/puppet/modules/devcloud/files/updatecode.sh similarity index 99% rename from tools/devcloud/devcloudbox/puppet-devcloud/files/updatecode.sh rename to tools/devcloud/src/puppet/modules/devcloud/files/updatecode.sh index 15e191aacb9..55259208c40 100644 --- a/tools/devcloud/devcloudbox/puppet-devcloud/files/updatecode.sh +++ b/tools/devcloud/src/puppet/modules/devcloud/files/updatecode.sh @@ -7,9 +7,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/tools/devcloud/src/puppet/modules/devcloud/lib/facter/xeninfo.rb b/tools/devcloud/src/puppet/modules/devcloud/lib/facter/xeninfo.rb new file mode 100644 index 00000000000..a0b8748577a --- /dev/null +++ b/tools/devcloud/src/puppet/modules/devcloud/lib/facter/xeninfo.rb @@ -0,0 +1,22 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permission s and limitations +# under the License. + +Facter.add(:xen_hostuuid) do + setcode do + uuid=Facter::Util::Resolution.exec('xe host-list |grep uuid|awk \'{print $5}\'') + end +end diff --git a/tools/devcloud/src/puppet/modules/devcloud/manifests/functions/httpdownload.pp b/tools/devcloud/src/puppet/modules/devcloud/manifests/functions/httpdownload.pp new file mode 100644 index 00000000000..2a88771beee --- /dev/null +++ b/tools/devcloud/src/puppet/modules/devcloud/manifests/functions/httpdownload.pp @@ -0,0 +1,37 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permission s and limitations +# under the License. + +define devcloud::functions::httpdownload () { + $file="${name['basedir']}/${name['basefile']}" + + exec { + "getfileifnotexist${name}": + command => "/usr/bin/wget ${name['url']}/${file} -O ${name['local_dir']}/${file}", + timeout => 0, + unless => "test -f ${name['local_dir']}/${file}", + require => [ File["${name['local_dir']}/${name['base_dir']}/"], + Exec["get_md5sums"] ]; + + + "getfileifnotmatch${name}": + command => "/usr/bin/wget ${name['url']}/${file} -O ${name['local_dir']}/${file}", + timeout => 0, + unless => "/usr/local/bin/compare.sh ${file} ${name['working_dir']} ", + require => [ Exec["getfileifnotexist${name}"], File["/usr/local/bin/compare.sh"] ] + } + +} diff --git a/tools/devcloud/src/puppet/modules/devcloud/manifests/init.pp b/tools/devcloud/src/puppet/modules/devcloud/manifests/init.pp new file mode 100644 index 00000000000..260e2542e01 --- /dev/null +++ b/tools/devcloud/src/puppet/modules/devcloud/manifests/init.pp @@ -0,0 +1,255 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permission s and limitations +# under the License. + + +class devcloud ( + + $cs_dir = $devcloud::params::cs_dir , + $devcloud_path = $devcloud::params::devcloud_path, + $gitrepo = $devcloud::params::gitrepo, + $storage_dir = $devcloud::params::storage_dir, + $tomcat_version = $devcloud::params::tomcat_version, + $tomcat_url = $devcloud::params::tomcat_url, + $tomcat_home = $devcloud::params::tomcat_home, + $maven_version = $devcloud::params::maven_version, + $maven_url = $devcloud::params::maven_url, + $maven_home = $devcloud::params::maven_home, + $downloads = $devcloud::params::downloads, + $md5sum_local = $devcloud::params::md5sum_local, + $md5sum_remote = $devcloud::params::md5sum_remote, + $hostuuid = $::xen_hostuuid, + $bridge_device_mac = $::macaddress_xenbr0, + $build_cloudstack = $devcloud::params::build_cloudstack + +) inherits devcloud::params { + + Exec { path => [ '/bin/', '/sbin/' , '/usr/bin/', '/usr/sbin/' ] } + + Exec["apt-update"] -> Package <| |> + + service { + 'ebtables': + ensure => 'running', + enable => true; + + 'nfs-kernel-server': + ensure => 'running', + require => Package['nfs-server'], + enable => true, + subscribe => File['/etc/exports']; + } + + package + { [ 'ant', + 'git', + 'python-mysql.connector', + 'mkisofs', + 'mysql-server', + 'nfs-server', + 'openjdk-6-jdk', + 'unzip' ]: + ensure => latest, + } + + exec { + + 'apt-update': + command => '/usr/bin/apt-get update'; + + 'get_md5sums': + command => "/usr/bin/wget -N ${md5sum_remote} -O ${md5sum_local}", + require => File["${storage_dir}/secondary/template/tmpl/1/"], + timeout => '0'; + + 'getecho': + command => "/usr/bin/wget ${devcloud_path}/echo -O /usr/lib/xcp/plugins/echo", + creates => '/usr/lib/xcp/plugins/echo'; + + 'setxcpperms': + command => '/bin/chmod -R 755 /usr/lib/xcp', + require => Exec['getecho']; + + 'get_code': + command => "git clone ${gitrepo}", + cwd => $cs_dir, + require => File[$cs_dir], + timeout => '7200', + creates => "${cs_dir}/incubator-cloudstack"; + + 'update_code': + command => 'git pull origin master', + cwd => "${cs_dir}/incubator-cloudstack", + timeout => '7200', + require => [ Exec['get_code']]; + + 'configlocal': + command => "xe sr-create host-uuid=${hostuuid} name-label=local-storage shared=false type=file device-config:location=${storage_dir}/primary", + cwd => '/', + unless => '/usr/bin/xe sr-list | /bin/egrep \'local-storage|Cloud Stack Local EXT Storage Pool\'', + require => [ + File["${storage_dir}/primary"], + ]; + + 'configvnc': + command => 'sed -i \'s/VNCTERM_LISTEN=.\+/VNCTERM_LISTEN="-v 0.0.0.0:1"/\' /usr/lib/xcp/lib/vncterm-wrapper', + onlyif => '/bin/grep "0.0.0.0:1" /usr/lib/xcp/lib/vncterm-wrapper'; + + 'downloadtomcat': + command => "/usr/bin/wget ${tomcat_url} -P ${cs_dir}/", + creates => "${cs_dir}/apache-tomcat-${tomcat_version}.zip", + require => File[$cs_dir], + timeout => '0'; + + 'unziptomcat': + require => [ + Package['unzip'], + Exec['downloadtomcat'] + ], + creates => $tomcat_home, + command => "/usr/bin/unzip apache-tomcat-${tomcat_version}.zip", + cwd => $cs_dir, + timeout => '0'; + + 'downloadmaven': + command => "/usr/bin/wget ${maven_url} -P ${cs_dir}/", + creates => "${cs_dir}/apache-maven-${maven_version}-bin.tar.gz", + require => Exec['unziptomcat'], + timeout => '0'; + + 'install_maven': + require => Exec['downloadmaven'], + creates => $maven_home, + command => "/bin/tar xzvf ${cs_dir}/apache-maven-${maven_version}-bin.tar.gz", + cwd => $cs_dir, + timeout => '0'; + + 'tomcatperms': + command => "chmod +x ${tomcat_home}/bin/*.sh", + require => Exec['unziptomcat']; + + 'catalina_home': + require => Exec['unziptomcat'], + unless => '/bin/grep CATALINA_HOME /root/.bashrc', + command => "/bin/echo \"export CATALINA_HOME=${tomcat_home}\" >> /root/.bashrc", + cwd => '/'; + + 'configebtables': + require => Service['ebtables'], + command => "/sbin/ebtables -I FORWARD -d ! ${bridge_device_mac} -i eth1 -p IPV4 --ip-prot udp --ip-dport 67:68 -j DROP", + unless => "/sbin/ebtables -L | grep \"-I FORWARD -d ! ${bridge_device_mac} -i eth1 -p IPV4 --ip-prot udp --ip-dport 67:68 -j DROP\"", + refreshonly => true, + cwd => '/', + path => '/sbin/:/usr/bin/:/bin' +} + + if $build_cloudstack { + + exec { + 'build_cloudstack': + require => [ + Package['ant','mkisofs'], + Exec['install_maven'], + File[ + "${cs_dir}/incubator-cloudstack/dist", + "${cs_dir}/incubator-cloudstack/target", + "${cs_dir}/buildcloudstack.sh"] + ], + command => "${cs_dir}/buildcloudstack.sh", + cwd => $cs_dir, + timeout => '0'; + } + } + + + file { + + [ $cs_dir, + $storage_dir, + "${storage_dir}/primary", + "${storage_dir}/secondary", + "${storage_dir}/secondary/template", + "${storage_dir}/secondary/template/tmpl", + "${storage_dir}/secondary/template/tmpl/1", + "${storage_dir}/secondary/template/tmpl/1/1", + "${storage_dir}/secondary/template/tmpl/1/5" ]: + ensure => 'directory', + group => '0', + mode => '0755', + owner => '0'; + + [ "${cs_dir}/incubator-cloudstack/dist", + "${cs_dir}/incubator-cloudstack/target" ] : + ensure => 'directory', + group => '0', + mode => '0755', + owner => '0', + require => [ Exec['update_code']]; + + "${cs_dir}/buildcloudstack.sh": + ensure => 'file', + mode => '0755', + owner => '0', + group => '0', + content => template('devcloud/buildcloudstack.sh.erb'); + + "${cs_dir}/startcloudstack.sh": + ensure => 'file', + mode => '0755', + owner => '0', + group => '0', + content => template('devcloud/startcloudstack.sh.erb'); + + '/root/.ssh' : + ensure => 'directory', + group => 'root', + mode => '0700', + owner => 'root'; + + "${cs_dir}/startdevcloud.sh": + ensure => 'file', + source => 'puppet:///modules/devcloud/startdevcloud.sh', + mode => '0755', + owner => '0', + group => '0'; + + '/usr/local/bin/compare.sh': + ensure => 'file', + source => 'puppet:///modules/devcloud/compare.sh', + mode => '0755', + owner => 'root', + group => 'root'; + + '/etc/exports': + ensure => 'file', + require => Package['nfs-server'], + source => 'puppet:///modules/devcloud/exports', + mode => '0644', + owner => '0', + group => '0'; + + } + + + devcloud::functions::httpdownload{ + $downloads: + require => + [ File["${storage_dir}/secondary/template/tmpl/1/1"], + File["${storage_dir}/secondary/template/tmpl/1/5"], + Exec['get_md5sums'] ] + } + +} diff --git a/tools/devcloud/src/puppet/modules/devcloud/manifests/params.pp b/tools/devcloud/src/puppet/modules/devcloud/manifests/params.pp new file mode 100644 index 00000000000..ff625c176f3 --- /dev/null +++ b/tools/devcloud/src/puppet/modules/devcloud/manifests/params.pp @@ -0,0 +1,78 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permission s and limitations +# under the License. + +# == Class: devcloud::params +# +# This class implements the module params pattern, but it's loaded using hiera +# as opposed to the 'default' usage of coding the parameter values in your +# manifest. +# +# == Usage +# +# Don't use this class directly; it's being used where it is needed +# +class devcloud::params { + + $cs_dir = '/opt/cloudstack' + $storage_dir = '/opt/storage' + $tomcat_version = '6.0.32' + $tomcat_url = "http://archive.apache.org/dist/tomcat/tomcat-6/v${tomcat_version}/bin/apache-tomcat-${tomcat_version}.zip" + $tomcat_home = "${cs_dir}/apache-tomcat-${tomcat_version}" + $maven_version = '3.0.4' + $maven_url = "http://apache.mirrors.pair.com/maven/maven-3/${maven_version}/binaries/apache-maven-${maven_version}-bin.tar.gz" + $maven_home = "${cs_dir}/apache-maven-${maven_version}" + $devcloud_path = 'http://download.cloud.com/templates/devcloud' + $template_path = "${devcloud_path}/defaulttemplates" + $md5sum_remote = "${template_path}/md5sum.txt" + $md5sum_local = "${storage_dir}/secondary/template/tmpl/1/md5sum.txt" + $template_dir = "${storage_dir}/secondary/template/tmpl/1" + $gitrepo = 'https://github.com/apache/incubator-cloudstack.git' + $build_cloudstack = false + + + $downloads = [ + + { + 'basefile' => 'template.properties', + 'basedir' => '1', + 'url' => $template_path, + 'local_dir' => $template_dir, + 'working_dir' => $template_dir + }, + { + 'basefile' => 'template.properties', + 'basedir' => '5', + 'url' => $template_path, + 'local_dir' => $template_dir, + 'working_dir' => $template_dir + }, + { + 'basefile' => 'dc68eb4c-228c-4a78-84fa-b80ae178fbfd.vhd', + 'basedir' => '1', + 'url' => $template_path, + 'local_dir' => $template_dir, + 'working_dir' => $template_dir + }, + { + 'basefile' => 'ce5b212e-215a-3461-94fb-814a635b2215.vhd', + 'basedir' => '5', + 'url' => $template_path, + 'local_dir' => $template_dir, + 'working_dir' => $template_dir + } + ] +} diff --git a/tools/devcloud/src/puppet/modules/devcloud/templates/buildcloudstack.sh.erb b/tools/devcloud/src/puppet/modules/devcloud/templates/buildcloudstack.sh.erb new file mode 100644 index 00000000000..acf9b0b3b95 --- /dev/null +++ b/tools/devcloud/src/puppet/modules/devcloud/templates/buildcloudstack.sh.erb @@ -0,0 +1,28 @@ +#!/bin/sh + +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +export CATALINA_HOME=<%= @tomcat_home %> +export M2_HOME=<%= @maven_home %> +export M2=$M2_HOME/bin +MAVEN_OPTS="-Xmx1024m -XX:MaxPermSize=800m -Xdebug -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n" +PATH=$M2:$PATH +cd <%= @cs_dir %>/incubator-cloudstack/ +<%= @maven_home %>/bin/mvn clean install -P developer,systemvm +<%= @maven_home %>/bin/mvn -pl developer,tools/devcloud -Ddeploydb -P developer +<%= @maven_home %>/bin/mvn -P developer -pl tools/devcloud -Ddeploysvr diff --git a/tools/devcloud/devcloudbox/puppet-devcloud/files/builddevcloud.sh b/tools/devcloud/src/puppet/modules/devcloud/templates/startcloudstack.sh.erb similarity index 74% rename from tools/devcloud/devcloudbox/puppet-devcloud/files/builddevcloud.sh rename to tools/devcloud/src/puppet/modules/devcloud/templates/startcloudstack.sh.erb index 03bd854e015..4a07711591b 100644 --- a/tools/devcloud/devcloudbox/puppet-devcloud/files/builddevcloud.sh +++ b/tools/devcloud/src/puppet/modules/devcloud/templates/startcloudstack.sh.erb @@ -7,9 +7,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -17,12 +17,10 @@ # specific language governing permissions and limitations # under the License. -export CATALINA_HOME=/opt/cloudstack/apache-tomcat-6.0.32 -export M2_HOME=/opt/cloudstack/apache-maven-3.0.4 +export CATALINA_HOME=<%= @tomcat_home %> +export M2_HOME=<%= @maven_home %> export M2=$M2_HOME/bin -MAVEN_OPTS="-Xms256m -Xmx512m" +MAVEN_OPTS="-Xmx1024m -XX:MaxPermSize=800m -Xdebug -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n" PATH=$M2:$PATH -cd /opt/cloudstack/incubator-cloudstack/ -/usr/bin/mvn -P deps -/usr/bin/mvn clean -/usr/bin/ant clean-all build-all deploy-server deploydb +cd <%= @cs_dir %>/incubator-cloudstack/ +<%= @maven_home %>/bin/mvn -pl client jetty:run & diff --git a/tools/devcloud/src/waitforxe.sh b/tools/devcloud/src/waitforxe.sh new file mode 100755 index 00000000000..637b9fc92c9 --- /dev/null +++ b/tools/devcloud/src/waitforxe.sh @@ -0,0 +1,39 @@ +#! /bin/bash +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +date +interval=20 +timeout=300 +command="xe host-list" + +count=0 +maxcount=$(($timeout/$interval)) + +until [ $count -gt $maxcount ]; do + if $command > /dev/null 2>&1; then + echo "\"$command\" executed successfully." + date + exit 0 + fi + let count=count+1 + echo "Waiting for \"$command\" to run successfully." + sleep $interval +done + +echo "\"$command\" failed to complete." +date diff --git a/tools/marvin/marvin/TestCaseExecuteEngine.py b/tools/marvin/marvin/TestCaseExecuteEngine.py index 06a8d72a00d..3c34c7efdfc 100644 --- a/tools/marvin/marvin/TestCaseExecuteEngine.py +++ b/tools/marvin/marvin/TestCaseExecuteEngine.py @@ -87,8 +87,8 @@ class TestCaseExecuteEngine(object): setattr(test, "config", self.config) setattr(test, "debug", partial(testCaseLogger, logger=testcaselogger)) setattr(test.__class__, "clstestclient", self.testclient) - if hasattr(test, "UserName"): - self.testclient.createNewApiClient(test.UserName, test.DomainName, test.AcctType) + if hasattr(test, "user"): #attribute when test is entirely executed as user + self.testclient.createUserApiClient(test.UserName, test.DomainName, test.AcctType) def run(self): if self.suite: diff --git a/tools/marvin/marvin/cloudstackConnection.py b/tools/marvin/marvin/cloudstackConnection.py index c8052130fe6..8c4e3251690 100644 --- a/tools/marvin/marvin/cloudstackConnection.py +++ b/tools/marvin/marvin/cloudstackConnection.py @@ -42,7 +42,7 @@ class cloudConnection(object): else: self.protocol=protocol self.path = path - if port == 8096: + if port == 8096 or (self.apiKey == None and self.securityKey == None): self.auth = False else: self.auth = True diff --git a/tools/marvin/marvin/cloudstackTestCase.py b/tools/marvin/marvin/cloudstackTestCase.py index 4ec764c58bf..7e557f8e6e6 100644 --- a/tools/marvin/marvin/cloudstackTestCase.py +++ b/tools/marvin/marvin/cloudstackTestCase.py @@ -31,7 +31,7 @@ import cloudstackTestClient # cls.AcctType = self.accounttype # return Wrapped -def UserName(Name, DomainName, AcctType): +def user(Name, DomainName, AcctType): def wrapper(cls): orig_init = cls.__init__ def __init__(self, *args, **kws): diff --git a/tools/marvin/marvin/cloudstackTestClient.py b/tools/marvin/marvin/cloudstackTestClient.py index 2bf14a00386..cb63179f40f 100644 --- a/tools/marvin/marvin/cloudstackTestClient.py +++ b/tools/marvin/marvin/cloudstackTestClient.py @@ -58,7 +58,7 @@ class cloudstackTestClient(object): """Generate Random Strings of variable length""" return ''.join(random.choice(chars) for x in range(size)) - def createNewApiClient(self, UserName, DomainName, acctType=0): + def createUserApiClient(self, UserName, DomainName, acctType=0): if not self.isAdminContext(): return self.apiClient @@ -88,7 +88,7 @@ class cloudstackTestClient(object): createAcctCmd = createAccount.createAccountCmd() createAcctCmd.accounttype = acctType createAcctCmd.domainid = domId - createAcctCmd.email = "test-" + self.random_gen() + "@citrix.com" + createAcctCmd.email = "test-" + self.random_gen() + "@cloudstack.org" createAcctCmd.firstname = UserName createAcctCmd.lastname = UserName createAcctCmd.password = mdf_pass @@ -111,16 +111,14 @@ class cloudstackTestClient(object): apiKey = registerUserRes.apikey securityKey = registerUserRes.secretkey - nConnection = cloudstackConnection.cloudConnection(self.connection.mgtSvr, self.connection.port, apiKey, securityKey, self.connection.asyncTimeout, self.connection.logging) - self.connection.close() - self.connection = nConnection - self.apiClient = cloudstackAPIClient.CloudStackAPIClient(self.connection) + newUserConnection = cloudstackConnection.cloudConnection(self.connection.mgtSvr, self.connection.port, apiKey, securityKey, self.connection.asyncTimeout, self.connection.logging) + self.userApiClient = cloudstackAPIClient.CloudStackAPIClient(newUserConnection) + self.userApiClient.connection = newUserConnection + return self.userApiClient def close(self): if self.connection is not None: self.connection.close() - if self.dbConnection is not None: - self.dbConnection.close() def getDbConnection(self): return self.dbConnection @@ -138,6 +136,17 @@ class cloudstackTestClient(object): def getApiClient(self): return self.apiClient + + def getUserApiClient(self, account, domain, type=0): + """ + 0 - user + 1 - admin + 2 - domain admin + """ + self.createUserApiClient(account, domain, type) + if hasattr(self, "userApiClient"): + return self.userApiClient + return None '''FixME, httplib has issue if more than one thread submitted''' def submitCmdsAndWait(self, cmds, workers=1): diff --git a/tools/marvin/marvin/deployDataCenter.py b/tools/marvin/marvin/deployDataCenter.py index bdf08cc2d2d..ba124cbced4 100644 --- a/tools/marvin/marvin/deployDataCenter.py +++ b/tools/marvin/marvin/deployDataCenter.py @@ -258,9 +258,9 @@ class deployDataCenters(): traffic_type = addTrafficType.addTrafficTypeCmd() traffic_type.physicalnetworkid = physical_network_id traffic_type.traffictype = traffictype.typ - if traffictype.labeldict: - traffic_type.kvmnetworklabel = traffictype.labeldict.xen - traffic_type.xennetworklabel = traffictype.labeldict.kvm + if traffictype.labeldict is not None: + traffic_type.kvmnetworklabel = traffictype.labeldict.kvm + traffic_type.xennetworklabel = traffictype.labeldict.xen traffic_type.vmwarenetworklabel = traffictype.labeldict.vmware return self.apiClient.addTrafficType(traffic_type) @@ -399,9 +399,9 @@ class deployDataCenters(): logging=self.testClientLogger) """config database""" - dbSvr = self.config.dbSvr - self.testClient.dbConfigure(dbSvr.dbSvr, dbSvr.port, dbSvr.user, \ - dbSvr.passwd, dbSvr.db) + #dbSvr = self.config.dbSvr + #self.testClient.dbConfigure(dbSvr.dbSvr, dbSvr.port, dbSvr.user, \ + # dbSvr.passwd, dbSvr.db) self.apiClient = self.testClient.getApiClient() def updateConfiguration(self, globalCfg): @@ -414,11 +414,29 @@ class deployDataCenters(): updateCfg.value = config.value self.apiClient.updateConfiguration(updateCfg) + def copyAttributesToCommand(self, source, command): + + map(lambda attr : setattr(command, attr, getattr(source, attr, None)), + filter(lambda attr : not attr.startswith("__") and + attr not in [ "required", "isAsync" ], dir(command))) + + + def configureS3(self, s3): + + if s3 is None: + return + + command = addS3.addS3Cmd() + + self.copyAttributesToCommand(s3, command) + + self.apiClient.addS3(command) + def deploy(self): self.loadCfg() - self.createZones(self.config.zones) self.updateConfiguration(self.config.globalConfig) - + self.createZones(self.config.zones) + self.configureS3(self.config.s3) if __name__ == "__main__": diff --git a/tools/marvin/marvin/integration/lib/base.py b/tools/marvin/marvin/integration/lib/base.py index 5001dafb5ec..0daea5dd579 100644 --- a/tools/marvin/marvin/integration/lib/base.py +++ b/tools/marvin/marvin/integration/lib/base.py @@ -203,16 +203,25 @@ class VirtualMachine: def __init__(self, items, services): self.__dict__.update(items) - self.username = services["username"] - self.password = services["password"] - self.ssh_port = services["ssh_port"] + if "username" in services: + self.username = services["username"] + else: + self.username = 'root' + if "password" in services: + self.password = services["password"] + else: + self.password = 'password' + if "ssh_port" in services: + self.ssh_port = services["ssh_port"] + else: + self.ssh_port = 22 self.ssh_client = None #extract out the ipaddress self.ipaddress = self.nic[0].ipaddress @classmethod def create(cls, apiclient, services, templateid=None, accountid=None, - domainid=None, networkids=None, serviceofferingid=None, + domainid=None, zoneid=None, networkids=None, serviceofferingid=None, securitygroupids=None, projectid=None, startvm=None, diskofferingid=None, hostid=None, mode='basic'): """Create the instance""" @@ -224,7 +233,10 @@ class VirtualMachine: elif "serviceoffering" in services: cmd.serviceofferingid = services["serviceoffering"] - cmd.zoneid = services["zoneid"] + if zoneid: + cmd.zoneid = zoneid + elif "zoneid" in services: + cmd.zoneid = services["zoneid"] cmd.hypervisor = services["hypervisor"] if accountid: @@ -547,7 +559,22 @@ class Template: cmd = createTemplate.createTemplateCmd() cmd.displaytext = services["displaytext"] cmd.name = "-".join([services["name"], random_gen()]) - cmd.ostypeid = services["ostypeid"] + if "ostypeid" in services: + cmd.ostypeid = services["ostypeid"] + elif "ostype" in services: + # Find OSTypeId from Os type + sub_cmd = listOsTypes.listOsTypesCmd() + sub_cmd.description = services["ostype"] + ostypes = apiclient.listOsTypes(sub_cmd) + + if not isinstance(ostypes, list): + raise Exception( + "Unable to find Ostype id with desc: %s" % + services["ostype"]) + cmd.ostypeid = ostypes[0].id + else: + raise Exception( + "Unable to find Ostype is required for creating template") cmd.isfeatured = services["isfeatured"] if "isfeatured" in services else False cmd.ispublic = services["ispublic"] if "ispublic" in services else False @@ -579,7 +606,24 @@ class Template: cmd.name = "-".join([services["name"], random_gen()]) cmd.format = services["format"] cmd.hypervisor = services["hypervisor"] - cmd.ostypeid = services["ostypeid"] + + if "ostypeid" in services: + cmd.ostypeid = services["ostypeid"] + elif "ostype" in services: + # Find OSTypeId from Os type + sub_cmd = listOsTypes.listOsTypesCmd() + sub_cmd.description = services["ostype"] + ostypes = apiclient.listOsTypes(sub_cmd) + + if not isinstance(ostypes, list): + raise Exception( + "Unable to find Ostype id with desc: %s" % + services["ostype"]) + cmd.ostypeid = ostypes[0].id + else: + raise Exception( + "Unable to find Ostype is required for registering template") + cmd.url = services["url"] if zoneid: @@ -615,7 +659,24 @@ class Template: services["name"], random_gen() ]) if random_name else services["name"] - cmd.ostypeid = services["ostypeid"] + + if "ostypeid" in services: + cmd.ostypeid = services["ostypeid"] + elif "ostype" in services: + # Find OSTypeId from Os type + sub_cmd = listOsTypes.listOsTypesCmd() + sub_cmd.description = services["ostype"] + ostypes = apiclient.listOsTypes(sub_cmd) + + if not isinstance(ostypes, list): + raise Exception( + "Unable to find Ostype id with desc: %s" % + services["ostype"]) + cmd.ostypeid = ostypes[0].id + else: + raise Exception( + "Unable to find Ostype is required for creating template") + cmd.snapshotid = snapshot.id return Template(apiclient.createTemplate(cmd).__dict__) @@ -695,7 +756,23 @@ class Iso: cmd = registerIso.registerIsoCmd() cmd.displaytext = services["displaytext"] cmd.name = services["name"] - cmd.ostypeid = services["ostypeid"] + if "ostypeid" in services: + cmd.ostypeid = services["ostypeid"] + elif "ostype" in services: + # Find OSTypeId from Os type + sub_cmd = listOsTypes.listOsTypesCmd() + sub_cmd.description = services["ostype"] + ostypes = apiclient.listOsTypes(sub_cmd) + + if not isinstance(ostypes, list): + raise Exception( + "Unable to find Ostype id with desc: %s" % + services["ostype"]) + cmd.ostypeid = ostypes[0].id + else: + raise Exception( + "Unable to find Ostype is required for creating ISO") + cmd.url = services["url"] cmd.zoneid = services["zoneid"] @@ -773,7 +850,7 @@ class PublicIPAddress: @classmethod def create(cls, apiclient, accountid=None, zoneid=None, domainid=None, - services=None, networkid=None, projectid=None): + services=None, networkid=None, projectid=None, vpcid=None): """Associate Public IP address""" cmd = associateIpAddress.associateIpAddressCmd() @@ -795,6 +872,9 @@ class PublicIPAddress: if projectid: cmd.projectid = projectid + + if vpcid: + cmd.vpcid = vpcid return PublicIPAddress(apiclient.associateIpAddress(cmd).__dict__) def delete(self, apiclient): @@ -821,7 +901,7 @@ class NATRule: @classmethod def create(cls, apiclient, virtual_machine, services, ipaddressid=None, - projectid=None): + projectid=None, networkid=None): """Create Port forwarding rule""" cmd = createPortForwardingRule.createPortForwardingRuleCmd() @@ -838,6 +918,9 @@ class NATRule: if projectid: cmd.projectid = projectid + if networkid: + cmd.networkid = networkid + return NATRule(apiclient.createPortForwardingRule(cmd).__dict__) def delete(self, apiclient): @@ -863,7 +946,7 @@ class StaticNATRule: self.__dict__.update(items) @classmethod - def create(cls, apiclient, services, ipaddressid=None): + def create(cls, apiclient, services, ipaddressid=None, vpcid=None): """Creates static ip forwarding rule""" cmd = createIpForwardingRule.createIpForwardingRuleCmd() @@ -881,6 +964,9 @@ class StaticNATRule: elif "ipaddressid" in services: cmd.ipaddressid = services["ipaddressid"] + if vpcid: + cmd.vpcid = vpcid + return StaticNATRule(apiclient.createIpForwardingRule(cmd).__dict__) def delete(self, apiclient): @@ -926,7 +1012,7 @@ class FireWallRule: @classmethod def create(cls, apiclient, ipaddressid, protocol, cidrlist=None, - startport=None, endport=None, projectid=None): + startport=None, endport=None, projectid=None, vpcid=None): """Create Firewall Rule""" cmd = createFirewallRule.createFirewallRuleCmd() cmd.ipaddressid = ipaddressid @@ -941,6 +1027,9 @@ class FireWallRule: if projectid: cmd.projectid = projectid + if vpcid: + cmd.vpcid = vpcid + return FireWallRule(apiclient.createFirewallRule(cmd).__dict__) def delete(self, apiclient): @@ -974,6 +1063,8 @@ class ServiceOffering: cmd.displaytext = services["displaytext"] cmd.memory = services["memory"] cmd.name = services["name"] + if "storagetype" in services: + cmd.storagetype = services["storagetype"] # Service Offering private to that domain if domainid: @@ -1438,7 +1529,8 @@ class Network: @classmethod def create(cls, apiclient, services, accountid=None, domainid=None, - networkofferingid=None, projectid=None, zoneid=None): + networkofferingid=None, projectid=None, zoneid=None, + gateway=None, netmask=None, vpcid=None, guestcidr=None): """Create Network for account""" cmd = createNetwork.createNetworkCmd() cmd.name = services["name"] @@ -1454,9 +1546,13 @@ class Network: elif "zoneid" in services: cmd.zoneid = services["zoneid"] - if "gateway" in services: + if gateway: + cmd.gateway = gateway + elif "gateway" in services: cmd.gateway = services["gateway"] - if "netmask" in services: + if netmask: + cmd.netmask = netmask + elif "netmask" in services: cmd.netmask = services["netmask"] if "startip" in services: cmd.startip = services["startip"] @@ -1473,7 +1569,10 @@ class Network: cmd.domainid = domainid if projectid: cmd.projectid = projectid - + if guestcidr: + cmd.guestcidr = guestcidr + if vpcid: + cmd.vpcid = vpcid return Network(apiclient.createNetwork(cmd).__dict__) def delete(self, apiclient): @@ -1497,7 +1596,7 @@ class Network: cmd = restartNetwork.restartNetworkCmd() cmd.id = self.id if cleanup: - cmd.cleanup = cleanup + cmd.cleanup = cleanup return(apiclient.restartNetwork(cmd)) @classmethod @@ -1509,6 +1608,50 @@ class Network: return(apiclient.listNetworks(cmd)) +class NetworkACL: + """Manage Network ACL lifecycle""" + + def __init__(self, items): + self.__dict__.update(items) + + @classmethod + def create(cls, apiclient, networkid, services, traffictype=None): + """Create network ACL rules(Ingress/Egress)""" + + cmd = createNetworkACL.createNetworkACLCmd() + cmd.networkid = networkid + if "protocol" in services: + cmd.protocol = services["protocol"] + + if services["protocol"] == 'ICMP': + cmd.icmptype = -1 + cmd.icmpcode = -1 + else: + cmd.startport = services["startport"] + cmd.endport = services["endport"] + + cmd.cidrlist = services["cidrlist"] + if traffictype: + cmd.traffictype = traffictype + # Defaulted to Ingress + return NetworkACL(apiclient.createNetworkACL(cmd).__dict__) + + def delete(self, apiclient): + """Delete network acl""" + + cmd = deleteNetworkACL.deleteNetworkACLCmd() + cmd.id = self.id + return apiclient.deleteNetworkACL(cmd) + + @classmethod + def list(cls, apiclient, **kwargs): + """List Network ACLs""" + + cmd = listNetworkACLs.listNetworkACLsCmd() + [setattr(cmd, k, v) for k, v in kwargs.items()] + return(apiclient.listNetworkACLs(cmd)) + + class Vpn: """Manage VPN life cycle""" @@ -1517,7 +1660,7 @@ class Vpn: @classmethod def create(cls, apiclient, publicipid, account=None, domainid=None, - projectid=None): + projectid=None, vpcid=None): """Create VPN for Public IP address""" cmd = createRemoteAccessVpn.createRemoteAccessVpnCmd() cmd.publicipid = publicipid @@ -1527,6 +1670,8 @@ class Vpn: cmd.domainid = domainid if projectid: cmd.projectid = projectid + if vpcid: + cmd.vpcid = vpcid return Vpn(apiclient.createRemoteAccessVpn(cmd).__dict__) def delete(self, apiclient): @@ -2144,3 +2289,106 @@ class NetworkServiceProvider: cmd = listNetworkServiceProviders.listNetworkServiceProvidersCmd() [setattr(cmd, k, v) for k, v in kwargs.items()] return(apiclient.listNetworkServiceProviders(cmd)) + +class VpcOffering: + """Manage VPC offerings""" + + def __init__(self, items): + self.__dict__.update(items) + + @classmethod + def create(cls, apiclient, services): + """Create vpc offering""" + + cmd = createVPCOffering.createVPCOfferingCmd() + cmd.name = "-".join([services["name"], random_gen()]) + cmd.displaytext = services["displaytext"] + cmd.supportedServices = services["supportedservices"] + return VpcOffering(apiclient.createVPCOffering(cmd).__dict__) + + def update(self, apiclient, name=None, displaytext=None, state=None): + """Updates existing VPC offering""" + + cmd = updateVPCOffering.updateVPCOfferingCmd() + cmd.id = self.id + if name: + cmd.name = name + if displaytext: + cmd.displaytext = displaytext + if state: + cmd.state = state + return apiclient.updateVPCOffering(cmd) + + @classmethod + def list(cls, apiclient, **kwargs): + """List the VPC offerings based on criteria specified""" + + cmd = listVPCOfferings.listVPCOfferingsCmd() + [setattr(cmd, k, v) for k, v in kwargs.items()] + return(apiclient.listVPCOfferings(cmd)) + + def delete(self, apiclient): + """Deletes existing VPC offering""" + + cmd = deleteVPCOffering.deleteVPCOfferingCmd() + cmd.id = self.id + return apiclient.deleteVPCOffering(cmd) + + +class VPC: + """Manage Virtual Private Connection""" + + def __init__(self, items): + self.__dict__.update(items) + + @classmethod + def create(cls, apiclient, services, vpcofferingid, + zoneid, networkDomain=None, account=None, domainid=None): + """Creates the virtual private connection (VPC)""" + + cmd = createVPC.createVPCCmd() + cmd.name = "-".join([services["name"], random_gen()]) + cmd.displaytext = "-".join([services["displaytext"], random_gen()]) + cmd.vpcofferingid = vpcofferingid + cmd.zoneid = zoneid + cmd.cidr = services["cidr"] + if account: + cmd.account = account + if domainid: + cmd.domainid = domainid + if networkDomain: + cmd.networkDomain = networkDomain + return VPC(apiclient.createVPC(cmd).__dict__) + + def update(self, apiclient, name=None, displaytext=None): + """Updates VPC configurations""" + + cmd = updateVPC.updateVPCCmd() + cmd.id = self.id + if name: + cmd.name = name + if displaytext: + cmd.displaytext = displaytext + return (apiclient.updateVPC(cmd)) + + def delete(self, apiclient): + """Delete VPC network""" + + cmd = deleteVPC.deleteVPCCmd() + cmd.id = self.id + return apiclient.deleteVPC(cmd) + + def restart(self, apiclient): + """Restarts the VPC connections""" + + cmd = restartVPC.restartVPCCmd() + cmd.id = self.id + return apiclient.restartVPC(cmd) + + @classmethod + def list(cls, apiclient, **kwargs): + """List VPCs""" + + cmd = listVPCs.listVPCsCmd() + [setattr(cmd, k, v) for k, v in kwargs.items()] + return(apiclient.listVPCs(cmd)) diff --git a/tools/marvin/marvin/integration/lib/common.py b/tools/marvin/marvin/integration/lib/common.py index b1c87bcf91d..69aa733420e 100644 --- a/tools/marvin/marvin/integration/lib/common.py +++ b/tools/marvin/marvin/integration/lib/common.py @@ -29,6 +29,30 @@ from base import * import time +def wait_for_cleanup(apiclient, configs=None): + """Sleeps till the cleanup configs passed""" + + # Configs list consists of the list of global configs + if not isinstance(configs, list): + return + for config in configs: + cmd = listConfigurations.listConfigurationsCmd() + cmd.name = config + cmd.listall = True + try: + config_descs = apiclient.listConfigurations(cmd) + except Exception as e: + raise Exception("Failed to fetch configurations: %s" % e) + + if not isinstance(config_descs, list): + raise Exception("List configs didn't returned a valid data") + + config_desc = config_descs[0] + # Sleep for the config_desc.value time + time.sleep(int(config_desc.value)) + return + + def get_domain(apiclient, services=None): "Returns a default domain" @@ -40,6 +64,7 @@ def get_domain(apiclient, services=None): domains = apiclient.listDomains(cmd) if isinstance(domains, list): + assert len(domains) > 0 return domains[0] else: raise Exception("Failed to find specified domain.") @@ -56,6 +81,7 @@ def get_zone(apiclient, services=None): zones = apiclient.listZones(cmd) if isinstance(zones, list): + assert len(zones) > 0, "There are no available zones in the deployment" return zones[0] else: raise Exception("Failed to find specified zone.") @@ -74,14 +100,25 @@ def get_pod(apiclient, zoneid, services=None): pods = apiclient.listPods(cmd) if isinstance(pods, list): + assert len(pods) > 0, "No pods found for zone %s"%zoneid return pods[0] else: raise Exception("Exception: Failed to find specified pod.") -def get_template(apiclient, zoneid, ostypeid=12, services=None): +def get_template(apiclient, zoneid, ostype, services=None): "Returns a template" + cmd = listOsTypes.listOsTypesCmd() + cmd.description = ostype + ostypes = apiclient.listOsTypes(cmd) + + if isinstance(ostypes, list): + ostypeid = ostypes[0].id + else: + raise Exception( + "Failed to find OS type with description: %s" % ostype) + cmd = listTemplates.listTemplatesCmd() cmd.templatefilter = 'featured' cmd.zoneid = zoneid @@ -92,9 +129,11 @@ def get_template(apiclient, zoneid, ostypeid=12, services=None): list_templates = apiclient.listTemplates(cmd) - for template in list_templates: - if template.ostypeid == ostypeid: - return template + if isinstance(list_templates, list): + assert len(list_templates) > 0, "received empty response on template of type %s"%ostype + for template in list_templates: + if template.ostypeid == ostypeid: + return template raise Exception("Exception: Failed to find template with OSTypeID: %s" % ostypeid) @@ -265,6 +304,14 @@ def update_resource_limit(apiclient, resourcetype, account=None, return +def list_os_types(apiclient, **kwargs): + """List all os types matching criteria""" + + cmd = listOsTypes.listOsTypesCmd() + [setattr(cmd, k, v) for k, v in kwargs.items()] + return(apiclient.listOsTypes(cmd)) + + def list_routers(apiclient, **kwargs): """List all Routers matching criteria""" @@ -513,3 +560,10 @@ def list_resource_limits(apiclient, **kwargs): cmd = listResourceLimits.listResourceLimitsCmd() [setattr(cmd, k, v) for k, v in kwargs.items()] return(apiclient.listResourceLimits(cmd)) + +def list_vpc_offerings(apiclient, **kwargs): + """ Lists VPC offerings """ + + cmd = listVPCOfferings.listVPCOfferingsCmd() + [setattr(cmd, k, v) for k, v in kwargs.items()] + return(apiclient.listVPCOfferings(cmd)) \ No newline at end of file diff --git a/tools/marvin/marvin/integration/lib/utils.py b/tools/marvin/marvin/integration/lib/utils.py index 05aed798a24..cff24a1b2d5 100644 --- a/tools/marvin/marvin/integration/lib/utils.py +++ b/tools/marvin/marvin/integration/lib/utils.py @@ -21,9 +21,6 @@ import marvin import time from marvin.remoteSSHClient import remoteSSHClient from marvin.cloudstackAPI import * -from marvin import cloudstackConnection -#from cloudstackConnection import cloudConnection -from marvin import configGenerator import logging import string import random @@ -136,12 +133,12 @@ def format_volume_to_ext3(ssh_client, device="/dev/sda"): def fetch_api_client(config_file='datacenterCfg'): """Fetch the Cloudstack API Client""" - config = configGenerator.get_setup_config(config_file) + config = marvin.configGenerator.get_setup_config(config_file) mgt = config.mgtSvr[0] testClientLogger = logging.getLogger("testClient") asyncTimeout = 3600 return cloudstackAPIClient.CloudStackAPIClient( - cloudstackConnection.cloudConnection( + marvin.cloudstackConnection.cloudConnection( mgt.mgtSvrIp, mgt.port, mgt.apiKey, diff --git a/tools/marvin/marvin/marvinPlugin.py b/tools/marvin/marvin/marvinPlugin.py index 01fbd6e39b1..c52596e6d43 100644 --- a/tools/marvin/marvin/marvinPlugin.py +++ b/tools/marvin/marvin/marvinPlugin.py @@ -119,6 +119,6 @@ class MarvinPlugin(Plugin): setattr(test, "config", self.config) setattr(test, "debug", partial(testCaseLogger, logger=testcaselogger)) setattr(test, "clstestclient", self.testclient) - if hasattr(test, "UserName"): - self.testclient.createNewApiClient(test.UserName, test.DomainName, test.AcctType) + if hasattr(test, "user"): #when the class-level attr applied. all test runs as 'user' + self.testclient.createUserApiClient(test.UserName, test.DomainName, test.AcctType) diff --git a/tools/marvin/marvin/remoteSSHClient.py b/tools/marvin/marvin/remoteSSHClient.py index 036e1c381e1..95a9adab53f 100644 --- a/tools/marvin/marvin/remoteSSHClient.py +++ b/tools/marvin/marvin/remoteSSHClient.py @@ -19,6 +19,7 @@ import paramiko import time import cloudstackException import contextlib +import logging from contextlib import closing class remoteSSHClient(object): @@ -29,11 +30,16 @@ class remoteSSHClient(object): self.passwd = passwd self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + self.logger = logging.getLogger('sshClient') + ch = logging.StreamHandler() + ch.setLevel(logging.DEBUG) + self.logger.addHandler(ch) retry_count = retries while True: try: self.ssh.connect(str(host),int(port), user, passwd) + self.logger.debug("connecting to server %s with user %s passwd %s"%(str(host), user, passwd)) except paramiko.SSHException, sshex: if retry_count == 0: raise cloudstackException.InvalidParameterException(repr(sshex)) @@ -46,6 +52,7 @@ class remoteSSHClient(object): def execute(self, command): stdin, stdout, stderr = self.ssh.exec_command(command) + self.logger.debug("sending command %s to host %s"%(command, str(self.host))) output = stdout.readlines() errors = stderr.readlines() results = [] @@ -57,7 +64,7 @@ class remoteSSHClient(object): else: for strOut in output: results.append(strOut.rstrip()) - + self.logger.debug("command %s returned %s"%(command, results)) return results def scp(self, srcFile, destPath): diff --git a/tools/marvin/marvin/setup.py b/tools/marvin/marvin/setup.py index dea67df8f89..07ff5b5a577 100644 --- a/tools/marvin/marvin/setup.py +++ b/tools/marvin/marvin/setup.py @@ -16,7 +16,13 @@ # under the License. import os -from setuptools import setup +try: + from setuptools import setup, find_packages +except ImportError: + from distribute_setup import use_setuptools + use_setuptools() + from setuptools import setup, find_packages + def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read().strip() diff --git a/tools/marvin/setup.py b/tools/marvin/setup.py index f0de384bfea..fea53d07f8a 100644 --- a/tools/marvin/setup.py +++ b/tools/marvin/setup.py @@ -20,10 +20,6 @@ from setuptools import setup from sys import version import sys -if version < "2.7": - print "Marvin needs at least python 2.7, found : \n%s"%version - sys.exit(1) - setup(name="Marvin", version="0.1.0", description="Marvin - Python client for testing cloudstack", diff --git a/tools/whisker/descriptor.xml b/tools/whisker/descriptor.xml index 0c573e38c6e..a94d60b612e 100644 --- a/tools/whisker/descriptor.xml +++ b/tools/whisker/descriptor.xml @@ -2634,6 +2634,29 @@ Copyright (c) 2004 Clinton Begin + + + +Copyright (c) 2010-2011 OpenStack, LLC. + + + + + + + + + +Copyright (c) 2010-2011 OpenStack, LLC. + + + + + + + + + @@ -2789,26 +2812,6 @@ All rights reserved. - - - -Copyright (c) 2010-2011 OpenStack, LLC. - - - - - - - - - -Copyright (c) 2010-2011 OpenStack, LLC. - - - - - - diff --git a/ui/css/cloudstack3.css b/ui/css/cloudstack3.css index 7d0a6b76894..a1a68cb774a 100644 --- a/ui/css/cloudstack3.css +++ b/ui/css/cloudstack3.css @@ -656,44 +656,12 @@ div.list-view div.toolbar div.section-switcher div.section-select label { position: absolute; } -/*** EULA*/ -.install-wizard .eula-copy { - width: 688px; - height: 480px; - background: #FFFFFF; - border: 1px solid #BCBCBC; - /*+box-shadow:0px 4px 10px #B9B9B9;*/ - -moz-box-shadow: 0px 4px 10px #B9B9B9; - -webkit-box-shadow: 0px 4px 10px #B9B9B9; - -o-box-shadow: 0px 4px 10px #B9B9B9; - box-shadow: 0px 4px 10px #B9B9B9; - padding: 5px; - /*+border-radius:4px;*/ - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - -khtml-border-radius: 4px; - border-radius: 4px; - border-radius: 4px 4px 4px 4px; - overflow: auto; - overflow-x: hidden; -} - -.install-wizard .eula-copy p { - font-size: 12px; - margin-top: 21px; -} - /*** Intro*/ .install-wizard .step.intro.what-is-cloudstack p { background: url(../images/bg-what-is-cloudstack.png) no-repeat 50% 237px; height: 540px; } -.install-wizard .step.intro.what-is-cloudplatform p { - background: url(../images/bg-what-is-cloudplatform.png) no-repeat 50% 237px; - height: 540px; -} - /*** Diagram*/ .install-wizard .diagram { width: 910px; @@ -1449,7 +1417,7 @@ div.list-view td.state.off span { -webkit-text-shadow: 0px 1px #EAEAEA; -o-text-shadow: 0px 1px #EAEAEA; text-shadow: 0px 1px #EAEAEA; - overflow:hidden; + overflow: hidden; } .quick-view-tooltip .detail-view .detail-group table td.value input[type=text] { @@ -2072,15 +2040,6 @@ div.detail-group.actions td { cursor: pointer; } -#header div.logo { - width: 170px; - height: 47px; - position: relative; - float: left; - margin: 4px 0 0 19px; - background: url(../images/logo-cloudplatform.png) no-repeat 0 center; -} - #header.nologo div.logo { width: 170px; height: 47px; @@ -6498,7 +6457,7 @@ label.error { .multi-wizard.zone-wizard .select-container.multi .drop-container { background: #DAE2EC; width: 484px; - height: 100px; + height: 114px; clear: both; position: relative; /*+border-radius:4px;*/ @@ -6538,10 +6497,10 @@ label.error { text-align: center; color: #959BA0; font-size: 13px; - /*+placement:shift 0px 24px;*/ + /*+placement:shift 0px 45px;*/ position: relative; left: 0px; - top: 24px; + top: 45px; } /*** Add physical network -- traffic type drag area*/ @@ -6769,20 +6728,20 @@ label.error { border-radius: 4px; border-radius: 4px 4px 4px 4px; border-top: 1px solid #FFFFFF; - /*+placement:shift -15px 61px;*/ + /*+placement:shift -16px 70px;*/ position: relative; - left: -15px; - top: 61px; + left: -16px; + top: 70px; } .multi-wizard.zone-wizard .drop-container .traffic-type-draggable > .edit-traffic-type:hover { background-position: 0px -105px; color: #FFFFFF; - /*+box-shadow:inset 0px 2px 1px #727272;*/ - -moz-box-shadow: inset 0px 2px 1px #727272; - -webkit-box-shadow: inset 0px 2px 1px #727272; - -o-box-shadow: inset 0px 2px 1px #727272; - box-shadow: inset 0px 2px 1px #727272; + /*+box-shadow:inset 0px -1px 1px #727272;*/ + -moz-box-shadow: inset 0px -1px 1px #727272; + -webkit-box-shadow: inset 0px -1px 1px #727272; + -o-box-shadow: inset 0px -1px 1px #727272; + box-shadow: inset 0px -1px 1px #727272; } .multi-wizard.zone-wizard .drop-container .traffic-type-draggable > .edit-traffic-type:hover span { @@ -6795,10 +6754,10 @@ label.error { } .multi-wizard.zone-wizard .drop-container .traffic-type-draggable:hover > .edit-traffic-type { - /*+placement:shift -7px 67px;*/ + /*+placement:shift -7px 76px;*/ position: relative; left: -7px; - top: 67px; + top: 76px; } .multi-wizard.zone-wizard .drop-container .traffic-type-draggable .edit-traffic-type span { @@ -6819,6 +6778,36 @@ label.error { padding: 7px 11px 0 7px; } +.multi-wizard.zone-wizard .traffic-type-draggable .edit-traffic-type span.name { + float: left; + width: 76px; + font-size: 10px; + padding: 2px; + color: #4E5F6F; + background: #DBE1E9; + /*+border-radius:4px 4px 0 0;*/ + -moz-border-radius: 4px 4px 0 0; + -webkit-border-radius: 4px 4px 0 0; + -khtml-border-radius: 4px 4px 0 0; + border-radius: 4px 4px 0 0; + /*+placement:shift -13px -16px;*/ + position: relative; + left: -13px; + top: -16px; + margin-bottom: -13px; + border: 1px solid #C3BCBC; + border-bottom: 1px solid #D1CDCD; + /*+box-shadow:inset 0px 1px 1px #F5F4F4;*/ + -moz-box-shadow: inset 0px 1px 1px #F5F4F4; + -webkit-box-shadow: inset 0px 1px 1px #F5F4F4; + -o-box-shadow: inset 0px 1px 1px #F5F4F4; + box-shadow: inset 0px 1px 1px #F5F4F4; +} + +.multi-wizard.zone-wizard .traffic-type-draggable .edit-traffic-type:hover span.name { + background: #C4C3C3; +} + /*** Configure guest network -- tabs*/ .multi-wizard.zone-wizard .setup-guest-traffic .ui-widget-content { width: 682px; @@ -11180,11 +11169,20 @@ div.ui-dialog div.autoscaler div.field-group div.form-container form div.form-it background-position: -168px -31px; } +.reset .icon{ +background-position: -168px -31px; +} + .restoreVM:hover .icon, .restore:hover .icon { background-position: -168px -613px; } + +.reset:hover .icon { + background-position: -168px -613px; +} + .enableVPN .icon { background-position: -198px -3px; } diff --git a/ui/dictionary.jsp b/ui/dictionary.jsp index e72481eeefc..203c9daa52e 100644 --- a/ui/dictionary.jsp +++ b/ui/dictionary.jsp @@ -25,6 +25,17 @@ under the License. <% long now = System.currentTimeMillis(); %>